Calendar Extender of AJAX Control Toolkit for ASP.Net 2.0 frameworks provides the AJAX based client side functionality to pick the date from popup calendar extender control. You can customize the date format and also the style of calendar user interface using CSS. AJAX Calendar control sets the date clicked by the user into the associated Textbox.
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TextBoxExample.ForeColor = Color.LightGoldenrodYellow;
TextBoxExample.ForeColor = Color.DeepPink;
TextBoxExample.Font.Bold = true;
TextBoxExample.Font.Size = FontUnit.Medium;
TextBoxExample.Font.Name = "Comic Sans MS";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Ajax CalendarExtender Example, How to use Ajax CalendarExtender in ASP.Net</title>
<style type="text/css">
.CSSCalendarexample
{
background-color:OrangeRed;
color:Snow;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">Ajax Control Toolkit Example: Using CalendarExtender</h2>
<hr width="500" align="left" color="CornFlowerBlue" />
<asp:ScriptManager
ID="ScriptManagerExample"
runat="server"
>
</asp:ScriptManager>
<cc1:CalendarExtender
ID="CalendarExtenderExample"
runat="server"
TargetControlID="TextBoxExample"
CssClass="CSSCalendarexample"
>
</cc1:CalendarExtender>
<asp:Label
ID="LabelExample"
runat="server"
ForeColor="DodgerBlue"
Font-Italic="true"
Font-Names="Comic Sans MS"
Font-Size="Large"
Text="Arrival Date: "
Font-Underline="true"
>
</asp:Label>
<asp:TextBox
ID="TextBoxExample"
runat="server"
>
</asp:TextBox>
</div>
</form>
</body>
</html>
Properties of Ajax CalendarExtender:
Animate: Accepts value as true/false. If true then it animates the calendar actions.
FirstDayOfWeek: It is an enumerator type collection that specifies to display the first of week in the calendar at runtime.
Format: You can set the different date formats using date formats e.g.: MMM dd, yyyy; MMM DDD dd, yyyy.
PopUpButtonID: You can specify the ID of image control, button control or linkbutton control to popup the calendar control. If PopUpButtonID is not specified then Calendar control popups when associated textbox gets focus.
PopUpPosition: This property sets the position of calendar control, that where should it appear such as BottomLeft of textbox, BottomRight, TopLeft, TopRight, Right or Left.
SelectedDate: You can specify the default date for the Calendar using SelectedDate Property. Calendar control initializes with the specified date.
TargetControlID: Specify the target TextBox ID in this property that will display the user selected date in the specified date format.
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TextBoxExample.ForeColor = Color.LightGoldenrodYellow;
TextBoxExample.ForeColor = Color.DeepPink;
TextBoxExample.Font.Bold = true;
TextBoxExample.Font.Size = FontUnit.Medium;
TextBoxExample.Font.Name = "Comic Sans MS";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Ajax CalendarExtender Example, How to use Ajax CalendarExtender in ASP.Net</title>
<style type="text/css">
.CSSCalendarexample
{
background-color:OrangeRed;
color:Snow;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">Ajax Control Toolkit Example: Using CalendarExtender</h2>
<hr width="500" align="left" color="CornFlowerBlue" />
<asp:ScriptManager
ID="ScriptManagerExample"
runat="server"
>
</asp:ScriptManager>
<cc1:CalendarExtender
ID="CalendarExtenderExample"
runat="server"
TargetControlID="TextBoxExample"
CssClass="CSSCalendarexample"
>
</cc1:CalendarExtender>
<asp:Label
ID="LabelExample"
runat="server"
ForeColor="DodgerBlue"
Font-Italic="true"
Font-Names="Comic Sans MS"
Font-Size="Large"
Text="Arrival Date: "
Font-Underline="true"
>
</asp:Label>
<asp:TextBox
ID="TextBoxExample"
runat="server"
>
</asp:TextBox>
</div>
</form>
</body>
</html>
Properties of Ajax CalendarExtender:
Animate: Accepts value as true/false. If true then it animates the calendar actions.
FirstDayOfWeek: It is an enumerator type collection that specifies to display the first of week in the calendar at runtime.
Format: You can set the different date formats using date formats e.g.: MMM dd, yyyy; MMM DDD dd, yyyy.
PopUpButtonID: You can specify the ID of image control, button control or linkbutton control to popup the calendar control. If PopUpButtonID is not specified then Calendar control popups when associated textbox gets focus.
PopUpPosition: This property sets the position of calendar control, that where should it appear such as BottomLeft of textbox, BottomRight, TopLeft, TopRight, Right or Left.
SelectedDate: You can specify the default date for the Calendar using SelectedDate Property. Calendar control initializes with the specified date.
TargetControlID: Specify the target TextBox ID in this property that will display the user selected date in the specified date format.
The ASP.NET Ajax client framework is essentially comprised of a set of JavaScript files that form part of a library commonly called the Microsoft Ajax Library. The major components that are included in this library are the following:
1. The Component Layer
2. The Core Services Layer
3. The Browser Compatibility Layer
The Core Component Layer
The Component Layer is comprised of a set of nonvisual components that provide support for asynchronous communication, networking, localization, XML and JSON serialization, ASP.NET application services, and so on.
The Core Services Layer
The Core Services Layer contains the ASP.NET Ajax Base Class Library and its extensions, which facilitate object-oriented programming and an extension to the existing JavaScript types.
The Browser Compatibility Layer
The Browser Compatibility Layer is responsible for providing cross-browser support for Ajax-enabled web pages—that is, support for browsers such as IE, Mozilla, Firefox, and so on.
1. The Component Layer
2. The Core Services Layer
3. The Browser Compatibility Layer
The Core Component Layer
The Component Layer is comprised of a set of nonvisual components that provide support for asynchronous communication, networking, localization, XML and JSON serialization, ASP.NET application services, and so on.
The Core Services Layer
The Core Services Layer contains the ASP.NET Ajax Base Class Library and its extensions, which facilitate object-oriented programming and an extension to the existing JavaScript types.
The Browser Compatibility Layer
The Browser Compatibility Layer is responsible for providing cross-browser support for Ajax-enabled web pages—that is, support for browsers such as IE, Mozilla, Firefox, and so on.
ASP.NET Ajax, formerly known as Atlas, is an extension of ASP.NET 2.0. It allows you to leverage the power of Ajax while developing ASP.NET Ajax web applications.
The MSDN states, “ASP.NET Ajax is a set of technologies to add Ajax (Asynchronous JavaScript and XML) support to ASP.NET. It consists of a client-side script framework, server controls, and more. Although Ajax is essentially a client-side technique, most of its real-world deployments call for server-side processing.”
The ASP.NET Ajax architecture has a framework developed for both client side and server side. The client-side framework comes in the form of the Microsoft Ajax Library. This Library includes a collection of client-side libraries that include support for creating client-side components, browser compatibility, managing asynchronous requests, web and application services, different core services in serialization,JavaScript base class extensions, and so on.
The ASP.NET Ajax server components consist of several web server controls and components to handle the flow and the user interface. It also shows the functionality of ASP.NET 2.0 Ajax server extensions, which include support for localization, globalization, debugging, tracing, web services, and application services.
Moreover, ASP.NET Ajax has come up with several server controls—namely, ScriptManager, UpdatePanel, UpdateProgress, and Timer—that enable a faster response. These controls are responsible for faster updates, better response times, and improved performance and efficiency. We’ll look at each of these controls in detail in the hours that follow.
ASP.NET Ajax also provides web services that can be used from the client script to work with different application services for forms authentication and user profiles.
There are several ASP.NET application services provided with the Ajax server extensions, which can be accessed by web service calls from the client script. This data transfer can be handled by different network components that make it easy to return results of a web service call.
The MSDN states, “ASP.NET Ajax is a set of technologies to add Ajax (Asynchronous JavaScript and XML) support to ASP.NET. It consists of a client-side script framework, server controls, and more. Although Ajax is essentially a client-side technique, most of its real-world deployments call for server-side processing.”
The ASP.NET Ajax architecture has a framework developed for both client side and server side. The client-side framework comes in the form of the Microsoft Ajax Library. This Library includes a collection of client-side libraries that include support for creating client-side components, browser compatibility, managing asynchronous requests, web and application services, different core services in serialization,JavaScript base class extensions, and so on.
The ASP.NET Ajax server components consist of several web server controls and components to handle the flow and the user interface. It also shows the functionality of ASP.NET 2.0 Ajax server extensions, which include support for localization, globalization, debugging, tracing, web services, and application services.
Moreover, ASP.NET Ajax has come up with several server controls—namely, ScriptManager, UpdatePanel, UpdateProgress, and Timer—that enable a faster response. These controls are responsible for faster updates, better response times, and improved performance and efficiency. We’ll look at each of these controls in detail in the hours that follow.
ASP.NET Ajax also provides web services that can be used from the client script to work with different application services for forms authentication and user profiles.
There are several ASP.NET application services provided with the Ajax server extensions, which can be accessed by web service calls from the client script. This data transfer can be handled by different network components that make it easy to return results of a web service call.
Like the CustomValidator control, the AjaxValidator control enables to create a custom server-side validation function. Unlike the CustomValidator control, however, the AjaxValidator control enables to call the custom validation function.
The AjaxValidator control uses AJAX (Asynchronous JavaScript and XML) to call the server-side validation function from the client. The advantage of using AJAX is that no postback to the server is apparent to the user.
Example : Imagine that you are creating a website form and you need to validate a User Name field. You want to make sure that the User Name entered does not already exist in the database. The AjaxValidator enables you to call a server-side validation function from the client to check whether the User Name is unique in the database.
AjaxValidator.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace myControls
{
public class AjaxValidator : BaseValidator, ICallbackEventHandler
{
public event ServerValidateEventHandler ServerValidate;
string _controlToValidateValue;
protected override void OnPreRender(EventArgs e)
{
String eventRef = Page.ClientScript.GetCallbackEventReference(this,““,““,““);
String includeScript =Page.ResolveClientUrl(“~/ClientScripts/AjaxValidator.js”);
Page.ClientScript.RegisterClientScriptInclude(“AjaxValidator”,includeScript);
String startupScript = String.Format(“document.getElementById(‘{0}’).evaluationfunction = ‘AjaxValidatorEvaluateIsValid’;”, this.ClientID);
Page.ClientScript.RegisterStartupScript(this.GetType(),“AjaxValidator”, startupScript, true);
base.OnPreRender(e);
}
protected override bool DetermineRenderUplevel()
{
return Context.Request.Browser.SupportsCallback;
}
public string GetCallbackResult()
{
return ExecuteValidationFunction(_controlToValidateValue).ToString();
}
public void RaiseCallbackEvent(string eventArgument)
{
_controlToValidateValue = eventArgument;
}
protected override bool EvaluateIsValid()
{
string controlToValidateValue = this.GetControlValidationValue
(this.ControlToValidate);
return ExecuteValidationFunction(controlToValidateValue);
}
private bool ExecuteValidationFunction(String controlToValidateValue)
{
ServerValidateEventArgs args = new ServerValidateEventArgs
(controlToValidateValue, this.IsValid);
if (ServerValidate != null)
ServerValidate(this, args);
return args.IsValid;
}
}
}
The control inherits from the BaseValidator class. It also implements the ICallbackEventHandler interface. The ICallbackEventHandler interface defines two methods that are called on the server when an AJAX request is made from the client.
In the OnPreRender() method, a JavaScript include file and startup script are registered. The JavaScript include file contains the client-side functions that are called when the AjaxValidator validates a form field on the client. The startup script associates the clientside AjaxValidatorEvaluateIsValid() function with the AjaxValidator control. The client-side validation framework automatically calls this JavaScript function when performing validation.
AjaxValidator.js
function AjaxValidatorEvaluateIsValid(val)
{
var value = ValidatorGetValue(val.controltovalidate);
WebForm_DoCallback(val.id, value, AjaxValidatorResult, val,
AjaxValidatorError, true);
return true;
}
function AjaxValidatorResult(returnValue, context)
{
if (returnValue == ‘True’)
context.isvalid = true;
else
context.isvalid = false;
ValidatorUpdateDisplay(context);
}
function AjaxValidatorError(message)
{
alert(‘Error: ‘ + message);
}
The AjaxValidatorEvaluateIsValid() JavaScript method initiates an AJAX call by calling the WebForm_DoCallback() method.
<%@ Page Language=”C#” %>
<%@ Register TagPrefix=”custom” Namespace=”myControls” %>
<%@ Import Namespace=”System.Data.SqlClient” %>
<%@ Import Namespace=”System.Web.Configuration” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
protected void AjaxValidator1_ServerValidate(object source,ServerValidateEventArgs args)
{
if (UserNameExists(args.Value))
args.IsValid = false;
else
args.IsValid = true;
}
>
private bool UserNameExists(string userName)
{
if username found in database return "true" else return "false"
}
return result;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Demo AjaxValidator</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label id=”lblUserName” Text=”User Name:” AssociatedControlID=”txtUserName” Runat=”server” />
<asp:TextBox id=”txtUserName” Runat=”server” />
<custom:AjaxValidator id=”AjaxValidator1” ControlToValidate=”txtUserName” Text=”User name already taken!” OnServerValidate=”AjaxValidator1_ServerValidate” Runat=”server” />
<asp:Button id=”btnSubmit” Text=”Submit” Runat=”server” OnClick=”btnSubmit_Click” />
</div>
</form>
</body>
</html>
The AjaxValidator control uses AJAX (Asynchronous JavaScript and XML) to call the server-side validation function from the client. The advantage of using AJAX is that no postback to the server is apparent to the user.
Example : Imagine that you are creating a website form and you need to validate a User Name field. You want to make sure that the User Name entered does not already exist in the database. The AjaxValidator enables you to call a server-side validation function from the client to check whether the User Name is unique in the database.
AjaxValidator.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace myControls
{
public class AjaxValidator : BaseValidator, ICallbackEventHandler
{
public event ServerValidateEventHandler ServerValidate;
string _controlToValidateValue;
protected override void OnPreRender(EventArgs e)
{
String eventRef = Page.ClientScript.GetCallbackEventReference(this,““,““,““);
String includeScript =Page.ResolveClientUrl(“~/ClientScripts/AjaxValidator.js”);
Page.ClientScript.RegisterClientScriptInclude(“AjaxValidator”,includeScript);
String startupScript = String.Format(“document.getElementById(‘{0}’).evaluationfunction = ‘AjaxValidatorEvaluateIsValid’;”, this.ClientID);
Page.ClientScript.RegisterStartupScript(this.GetType(),“AjaxValidator”, startupScript, true);
base.OnPreRender(e);
}
protected override bool DetermineRenderUplevel()
{
return Context.Request.Browser.SupportsCallback;
}
public string GetCallbackResult()
{
return ExecuteValidationFunction(_controlToValidateValue).ToString();
}
public void RaiseCallbackEvent(string eventArgument)
{
_controlToValidateValue = eventArgument;
}
protected override bool EvaluateIsValid()
{
string controlToValidateValue = this.GetControlValidationValue
(this.ControlToValidate);
return ExecuteValidationFunction(controlToValidateValue);
}
private bool ExecuteValidationFunction(String controlToValidateValue)
{
ServerValidateEventArgs args = new ServerValidateEventArgs
(controlToValidateValue, this.IsValid);
if (ServerValidate != null)
ServerValidate(this, args);
return args.IsValid;
}
}
}
The control inherits from the BaseValidator class. It also implements the ICallbackEventHandler interface. The ICallbackEventHandler interface defines two methods that are called on the server when an AJAX request is made from the client.
In the OnPreRender() method, a JavaScript include file and startup script are registered. The JavaScript include file contains the client-side functions that are called when the AjaxValidator validates a form field on the client. The startup script associates the clientside AjaxValidatorEvaluateIsValid() function with the AjaxValidator control. The client-side validation framework automatically calls this JavaScript function when performing validation.
AjaxValidator.js
function AjaxValidatorEvaluateIsValid(val)
{
var value = ValidatorGetValue(val.controltovalidate);
WebForm_DoCallback(val.id, value, AjaxValidatorResult, val,
AjaxValidatorError, true);
return true;
}
function AjaxValidatorResult(returnValue, context)
{
if (returnValue == ‘True’)
context.isvalid = true;
else
context.isvalid = false;
ValidatorUpdateDisplay(context);
}
function AjaxValidatorError(message)
{
alert(‘Error: ‘ + message);
}
<%@ Page Language=”C#” %>
<%@ Register TagPrefix=”custom” Namespace=”myControls” %>
<%@ Import Namespace=”System.Data.SqlClient” %>
<%@ Import Namespace=”System.Web.Configuration” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
protected void AjaxValidator1_ServerValidate(object source,ServerValidateEventArgs args)
{
if (UserNameExists(args.Value))
args.IsValid = false;
else
args.IsValid = true;
}
>
private bool UserNameExists(string userName)
{
if username found in database return "true" else return "false"
}
return result;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Demo AjaxValidator</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label id=”lblUserName” Text=”User Name:” AssociatedControlID=”txtUserName” Runat=”server” />
<asp:TextBox id=”txtUserName” Runat=”server” />
<custom:AjaxValidator id=”AjaxValidator1” ControlToValidate=”txtUserName” Text=”User name already taken!” OnServerValidate=”AjaxValidator1_ServerValidate” Runat=”server” />
<asp:Button id=”btnSubmit” Text=”Submit” Runat=”server” OnClick=”btnSubmit_Click” />
</div>
</form>
</body>
</html>
The difference between how a traditional web application model and an Ajax-based web application model works. In traditional web applications, when a form is submitted, a request is sent to the web server. The web server acts upon this and sends back the response in the form of a web page. In this process, a lot of bandwidth is consumed, as the entire page has to be submitted, and either the same page or a new page has to be sent back as a response. More often than not, during this postback, much of the HTML of the first page is present in the second page. This is the case for every user interaction that happens on the client browser. The result is higher response times from the server, which thus affect the overall performance and create a rich user experience.
On the other hand, when an Ajax-based web application sends requests to the web server, the web server in return sends only the data that is requested. This is usually done in SOAP, HTML, XML, plain text, or JSON, and using JavaScript on the client to process the response. In this process, the amount of data interchange between the server and client is greatly reduced, thus improving the responsiveness of the application. This enhances rich user experience as the web server saves a lot of time by processing only the data that is required.
On the other hand, when an Ajax-based web application sends requests to the web server, the web server in return sends only the data that is requested. This is usually done in SOAP, HTML, XML, plain text, or JSON, and using JavaScript on the client to process the response. In this process, the amount of data interchange between the server and client is greatly reduced, thus improving the responsiveness of the application. This enhances rich user experience as the web server saves a lot of time by processing only the data that is required.
The XMLHttpRequest object uses JavaScript to make requests to the server and process the response, thereby minimizing the postback delays. It can be called as an API that can be used by JavaScript to transfer XML and other formats of data between the server and client using HTTP. Microsoft invented this object; it was initially designed to load XML documents from JavaScript. The name XMLHttpRequest might be misleading because of the term XML, but, in fact, you can transfer the data in XML or other textbased formats. These formats can be plain text, HTML, or JSON. JSON is an acronym for JavaScript Object Notation. The XMLHttpRequest object plays an important role in the development of Ajax-style applications to implement responsive and dynamic web applications.
Creating the XMLHttpRequest Object
You can create the object for ActiveX by passing the name of the object to its constructor:
var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
The preceding syntax works for IE browsers; however, for Mozilla and Safari browsers, you can just make a call to the constructor of the XMLHttpRequest class without any arguments:
var xmlHttp = new XmlHttpRequest();
For Mozilla, Safari, and Opera browsers, this object is a native JavaScript object, as compared to IE 5.0 and 6.0 versions, where this comes as an ActiveXObject.Ironically, IE 7.0 has also made the XMLHttpRequest object a native JavaScript object. Because this object has different implementations for different browsers, and because this object is used in every web page for performing request and response, we can encapsulate all this into a single JavaScript file and expose a method called getXmlHttpRequestObject().
Let’s put this method and the variable xmlHttp in a JavaScript file called xmlhttp.js and include this JavaScript file in every web page. The later hours that use the XMLHttpRequest object will use this JavaScript file. The variable xmlHttp now holds the instance of the XMLHttpRequest object.
The following is the code snippet in the xmlhttp.js JavaScript file:
var xmlHttp = false;
function getXmlHttpRequestObject() {
// check for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
xmlHttp = new XMLHttpRequest();
}
catch(e) {
xmlHttp = false;
}
}
// check for IE/Windows ActiveX version
else if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch(e) {
try {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch(e) {
xmlHttp = false;
}
}
}
}
The getXmlHttpRequestObject() method encapsulates the functionality of instantiating the XMLHttpRequest object for different browsers. To perform any request using this object, we simply check the status of the variable xmlHttp. If it validates to false, then the object has not been instantiated—or else you get an instance of the XMLHttpRequest in this variable for use. The function getXmlHttpRequest() first checks for the native XMLHttpRequest object. Refer to the following code snippet:
if(window.XMLHttpRequest && !(window.ActiveXObject))
If window.XMLHttpRequest validates to true and window.ActiveXObject validates to false, then the native object instance is created and set to the variable xmlHttp.
This is executed for the Mozilla, Safari, Opera, and IE 7.0 browsers. The “else if” block checks for the existence of ActiveXObject. Refer to the following code snippet:
try {
xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch(e) {
try {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch(e) {
xmlHttp = false;
}
If the browser type is IE, an instance of type ActiveXObject is created and is set to the variable xmlHttp.
Creating the XMLHttpRequest Object
You can create the object for ActiveX by passing the name of the object to its constructor:
var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
The preceding syntax works for IE browsers; however, for Mozilla and Safari browsers, you can just make a call to the constructor of the XMLHttpRequest class without any arguments:
var xmlHttp = new XmlHttpRequest();
For Mozilla, Safari, and Opera browsers, this object is a native JavaScript object, as compared to IE 5.0 and 6.0 versions, where this comes as an ActiveXObject.Ironically, IE 7.0 has also made the XMLHttpRequest object a native JavaScript object. Because this object has different implementations for different browsers, and because this object is used in every web page for performing request and response, we can encapsulate all this into a single JavaScript file and expose a method called getXmlHttpRequestObject().
Let’s put this method and the variable xmlHttp in a JavaScript file called xmlhttp.js and include this JavaScript file in every web page. The later hours that use the XMLHttpRequest object will use this JavaScript file. The variable xmlHttp now holds the instance of the XMLHttpRequest object.
The following is the code snippet in the xmlhttp.js JavaScript file:
var xmlHttp = false;
function getXmlHttpRequestObject() {
// check for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
xmlHttp = new XMLHttpRequest();
}
catch(e) {
xmlHttp = false;
}
}
// check for IE/Windows ActiveX version
else if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch(e) {
try {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch(e) {
xmlHttp = false;
}
}
}
}
The getXmlHttpRequestObject() method encapsulates the functionality of instantiating the XMLHttpRequest object for different browsers. To perform any request using this object, we simply check the status of the variable xmlHttp. If it validates to false, then the object has not been instantiated—or else you get an instance of the XMLHttpRequest in this variable for use. The function getXmlHttpRequest() first checks for the native XMLHttpRequest object. Refer to the following code snippet:
if(window.XMLHttpRequest && !(window.ActiveXObject))
If window.XMLHttpRequest validates to true and window.ActiveXObject validates to false, then the native object instance is created and set to the variable xmlHttp.
This is executed for the Mozilla, Safari, Opera, and IE 7.0 browsers. The “else if” block checks for the existence of ActiveXObject. Refer to the following code snippet:
try {
xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch(e) {
try {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch(e) {
xmlHttp = false;
}
If the browser type is IE, an instance of type ActiveXObject is created and is set to the variable xmlHttp.
Over the past several years, more and more developers have been building AJAX-enabled web applications. An AJAX-enabled website uses a number of related web technologies to offer a more responsive user experience. Creating AJAX-enabled ASP.NET applications is amazingly easy thanks to Microsoft's ASP.NET AJAX framework. ASP.NET AJAX is built into ASP.NET 3.5 and Visual Studio 2008; it is also available as a separate download for ASP.NET 2.0 applications.
When building AJAX-enabled web pages with the ASP.NET AJAX framework, you must add precisely one ScriptManager control to each and every page that uses the framework. As its name implies, the ScriptManager manages the client-side script used in AJAX-enabled web pages. At a minimum, the ScriptManager emits HTML that instructs the browser to download the JavaScript files that makeup the ASP.NET AJAX Client Library. It can also be used to register custom JavaScript files, script-enabled web services, and custom application service functionality.
If your site uses master pages (as it should), you do not necessarily need to add a ScriptManager control to every single content page; rather, you can add a ScriptManager control to the master page. This tutorial shows how to add the ScriptManager control to the master page. It also looks at how to use the ScriptManagerProxy control to register custom scripts and script services in a specific content page.
When building AJAX-enabled web pages with the ASP.NET AJAX framework, you must add precisely one ScriptManager control to each and every page that uses the framework. As its name implies, the ScriptManager manages the client-side script used in AJAX-enabled web pages. At a minimum, the ScriptManager emits HTML that instructs the browser to download the JavaScript files that makeup the ASP.NET AJAX Client Library. It can also be used to register custom JavaScript files, script-enabled web services, and custom application service functionality.
If your site uses master pages (as it should), you do not necessarily need to add a ScriptManager control to every single content page; rather, you can add a ScriptManager control to the master page. This tutorial shows how to add the ScriptManager control to the master page. It also looks at how to use the ScriptManagerProxy control to register custom scripts and script services in a specific content page.
JSON Web Services really are the jumping off point between server-centric and client-centric web development. You can add all of the pretty, JavaScript-y, AJAX-y sugar you want to your UI, but if your page or control posts back, (weather or not it is asynchronously via an Update Panel) then it is still server-centric in terms of logic.
But by off-loading your logic to JSON Web Services, you are making your pages themselves each act like a nice client-centric MVC application. The HTML is obviously the view, the web services act as the model, since they will be processing business objects for persistence or returning them to the UI for consumption. Finally, a JavaScript file sits in between, acting as a controller.
Model - Web Service
using System;
using System.Web.Services;
using System.Web.Script.Services;
namespace MyWebApplication
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class JSONTestService : WebService
{
[WebMethod]
public void SetNewTest(Guid id, string text)
{
this.Application.Add(id.ToString(), text);
}
[WebMethod]
public string GetNewTest(Guid id)
{
return this.Application[id.ToString()].ToString();
}
[WebMethod]
public Guid CreateNew()
{
return Guid.NewGuid();
}
}
}
But normally, these web services will be processing full business objects. What I do is actually keep a variable on the client that stores my object, manipulate its properties via client-side events, (both of which are in the JavaScript file), and then pass the whole object to a web service for server-side manipulation.
View - Page / Control
<script type="text/javascript" language="javascript">
var txtGetNewTestID = '<% =this.txtGetNewTest.ClientID %>';
var txtSetNewTestID = '<% =this.txtSetNewTest.ClientID %>';
</script>
<table>
<tr>
<td>
</td>
<td>
<asp:Button id="btnNew" runat="server" Text="New" OnClientClick="GetNew(); return false;" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtSetNewTest" runat="server" />
</td>
<td>
<asp:Button ID="btnSetNewTest" runat="server" Text="Set" OnClientClick="SetNewTest(); return false;" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtGetNewTest" runat="server" />
</td>
<td>
<asp:Button ID="btnGet" runat="server" Text="Get" OnClientClick="GetNewTest(); return false;" />
</td>
</tr>
</table>
The only embedded JavaScript here is for variable declarations. Loose JavaScript files can't use the <% ... %> construct to call into .NET code, since they are not in the context of a page or control. So I like to expose the controls I'll need to manipulate this way, and then use $get(<control unique id>) in my JavaScript file to get a reference to the control.
You can still use server controls, and take advantage of the extensions they add to HTML controls. However, we don't want to cause a post back, as that will kill the state of our client objects. So for controls that always do an AutoPostBack, (like buttons) add "return false;" to end of the "client" event; this will not call __doPostback() behind the scenes.
Controller - JavaScript file
var _guid = null;
function GetNew()
{
MyWebApplication.JSONTestService.CreateNew(GetNewDone, OnError, null);
}
function GetNewDone(result)
{
_guid = result;
}
function SetNewTest()
{
MyWebApplication.JSONTestService.SetNewTest(_guid, $get(txtSetNewTestID).value, null, OnError, null);
}
function GetNewTest()
{
MyWebApplication.JSONTestService.GetNewTest(_guid, GetNewTestDone, OnError, null);
}
function GetNewTestDone(result)
{
$get(txtGetNewTestID).value = result;
}
function OnError(ex)
{
alert('Error: ' + ex._message);
}
If any of the server code in a web method on your web service throws an exception, the OnError JavaScript function here will be called. The variable passed is a JSON serialized Exception object, providing the description of the error, as well as a full stack trace! This way, you can still catch-and-log-and-rethrow your exceptions on the server, and gracefully deal with them on the client.
Another benefit to using a loose JavaScript file as the controller is that it provides a rich debugging experience. I wrote more about that here.
I know that using a JavaScript file as a controller in the MVC architecture is a stretch, but it works. Since you can swap .js files on the fly, they are kind of a configurable broker; as long as they handle events on the client and can, in response, call services on the server, the paradigm fits. This way, you can completely replace your back end, and then merely tweak your JavaScript file to keep communication between your persistence and your UI flowing.
The only thing left to do is wire everything up in the code-behind of the page / control:
using System;
using System.Web.UI;
namespace MyWebApplication
{
public partial class JSONTest : UserControl //or Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
ScriptManager sm = ScriptManager.GetCurrent(this.Page);
sm.Scripts.Add(new ScriptReference("/JSONTest.js"));
sm.Services.Add(new ServiceReference("/JSONTestService.asmx"));
}
}
}
}
In fact, since I've adopted this architecture, the only code-behind my pages and controls have is in the Load event, if IsPostBack is false. This separation of logic from presentation makes for a much cleaner ASPX / ASCX file, both in terms of managed code behind and HTML!
Despite the fact that the implementation of the "model" web services is still .NET code, they are called asynchronously though the AJAX web service infrastructure, not via a form submit, and therefore do not cause the Load event of your page to fire. This really does away with the page lifecycle as we know it. This way, we can move all of the business logic from the page to JavaScript, and then use JSON Web Services to either do persistence and call other services, or do any processing that is too complex for, or not supported by, JavaScript (for example, guids).
Speaking of the implementation of these web methods, there is more thing to point out. In the first post I linked to in this article, I talk about one main "reality check" of JSON Web Services: they do not share the same Session as the UI. So my workaround for this is to use the Application object, and store objects in it keyed off of guids.
This way, although all of instances of our app are using the same Application object, there will be no name collisions. And as far as the server is concerned, and object in memory is an object in memory; there shouldn't be any performance ramifications using this method verses using Session state.
But by off-loading your logic to JSON Web Services, you are making your pages themselves each act like a nice client-centric MVC application. The HTML is obviously the view, the web services act as the model, since they will be processing business objects for persistence or returning them to the UI for consumption. Finally, a JavaScript file sits in between, acting as a controller.
Model - Web Service
using System;
using System.Web.Services;
using System.Web.Script.Services;
namespace MyWebApplication
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class JSONTestService : WebService
{
[WebMethod]
public void SetNewTest(Guid id, string text)
{
this.Application.Add(id.ToString(), text);
}
[WebMethod]
public string GetNewTest(Guid id)
{
return this.Application[id.ToString()].ToString();
}
[WebMethod]
public Guid CreateNew()
{
return Guid.NewGuid();
}
}
}
But normally, these web services will be processing full business objects. What I do is actually keep a variable on the client that stores my object, manipulate its properties via client-side events, (both of which are in the JavaScript file), and then pass the whole object to a web service for server-side manipulation.
View - Page / Control
<script type="text/javascript" language="javascript">
var txtGetNewTestID = '<% =this.txtGetNewTest.ClientID %>';
var txtSetNewTestID = '<% =this.txtSetNewTest.ClientID %>';
</script>
<table>
<tr>
<td>
</td>
<td>
<asp:Button id="btnNew" runat="server" Text="New" OnClientClick="GetNew(); return false;" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtSetNewTest" runat="server" />
</td>
<td>
<asp:Button ID="btnSetNewTest" runat="server" Text="Set" OnClientClick="SetNewTest(); return false;" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtGetNewTest" runat="server" />
</td>
<td>
<asp:Button ID="btnGet" runat="server" Text="Get" OnClientClick="GetNewTest(); return false;" />
</td>
</tr>
</table>
The only embedded JavaScript here is for variable declarations. Loose JavaScript files can't use the <% ... %> construct to call into .NET code, since they are not in the context of a page or control. So I like to expose the controls I'll need to manipulate this way, and then use $get(<control unique id>) in my JavaScript file to get a reference to the control.
You can still use server controls, and take advantage of the extensions they add to HTML controls. However, we don't want to cause a post back, as that will kill the state of our client objects. So for controls that always do an AutoPostBack, (like buttons) add "return false;" to end of the "client" event; this will not call __doPostback() behind the scenes.
Controller - JavaScript file
var _guid = null;
function GetNew()
{
MyWebApplication.JSONTestService.CreateNew(GetNewDone, OnError, null);
}
function GetNewDone(result)
{
_guid = result;
}
function SetNewTest()
{
MyWebApplication.JSONTestService.SetNewTest(_guid, $get(txtSetNewTestID).value, null, OnError, null);
}
function GetNewTest()
{
MyWebApplication.JSONTestService.GetNewTest(_guid, GetNewTestDone, OnError, null);
}
function GetNewTestDone(result)
{
$get(txtGetNewTestID).value = result;
}
function OnError(ex)
{
alert('Error: ' + ex._message);
}
If any of the server code in a web method on your web service throws an exception, the OnError JavaScript function here will be called. The variable passed is a JSON serialized Exception object, providing the description of the error, as well as a full stack trace! This way, you can still catch-and-log-and-rethrow your exceptions on the server, and gracefully deal with them on the client.
Another benefit to using a loose JavaScript file as the controller is that it provides a rich debugging experience. I wrote more about that here.
I know that using a JavaScript file as a controller in the MVC architecture is a stretch, but it works. Since you can swap .js files on the fly, they are kind of a configurable broker; as long as they handle events on the client and can, in response, call services on the server, the paradigm fits. This way, you can completely replace your back end, and then merely tweak your JavaScript file to keep communication between your persistence and your UI flowing.
The only thing left to do is wire everything up in the code-behind of the page / control:
using System;
using System.Web.UI;
namespace MyWebApplication
{
public partial class JSONTest : UserControl //or Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
ScriptManager sm = ScriptManager.GetCurrent(this.Page);
sm.Scripts.Add(new ScriptReference("/JSONTest.js"));
sm.Services.Add(new ServiceReference("/JSONTestService.asmx"));
}
}
}
}
In fact, since I've adopted this architecture, the only code-behind my pages and controls have is in the Load event, if IsPostBack is false. This separation of logic from presentation makes for a much cleaner ASPX / ASCX file, both in terms of managed code behind and HTML!
Despite the fact that the implementation of the "model" web services is still .NET code, they are called asynchronously though the AJAX web service infrastructure, not via a form submit, and therefore do not cause the Load event of your page to fire. This really does away with the page lifecycle as we know it. This way, we can move all of the business logic from the page to JavaScript, and then use JSON Web Services to either do persistence and call other services, or do any processing that is too complex for, or not supported by, JavaScript (for example, guids).
Speaking of the implementation of these web methods, there is more thing to point out. In the first post I linked to in this article, I talk about one main "reality check" of JSON Web Services: they do not share the same Session as the UI. So my workaround for this is to use the Application object, and store objects in it keyed off of guids.
This way, although all of instances of our app are using the same Application object, there will be no name collisions. And as far as the server is concerned, and object in memory is an object in memory; there shouldn't be any performance ramifications using this method verses using Session state.
Instead of enabling tracing for individual pages, you can enable it for your entire application. In that case, every page in your application displays trace information. Application tracing is useful when you are developing an application because you can easily enable it and disable it without editing individual pages. When your application is complete, you can turn off tracing for all pages at once.
When you enable tracing for an application, ASP.NET collects trace information for each request to the application, up to the maximum number of requests you specify. The default number of requests is 10. You can view trace information with the trace viewer.
By default, when the trace viewer reaches its request limit, the application stops storing trace requests. However, you can configure application-level tracing to always store the most recent tracing data, discarding the oldest data when the maximum number of requests is reached. For more information.
To enable tracing for an application:
1.Open your Web site's Web.config file. If no Web.config file exists, create a new file in the root folder and copy the following into it:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.web>
</system.web>
</configuration>
2.Add a trace element as a child of the system.web element.
3.In the trace element, set the enabled attribute to true.
4.If you want trace information to appear at the end of the page that it is associated with, set the trace element's pageOutput attribute to true. If you want tracing information to be displayed only in the trace viewer, set the pageOutput attribute to false.
For example, the following application trace configuration collects trace information for up to 40 requests and allows browsers on computers other than the server of origin to display the trace viewer. Trace information is not displayed in individual pages.
<configuration>
<system.web>
<trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/>
</system.web>
</configuration>
When you enable tracing for an application, ASP.NET collects trace information for each request to the application, up to the maximum number of requests you specify. The default number of requests is 10. You can view trace information with the trace viewer.
By default, when the trace viewer reaches its request limit, the application stops storing trace requests. However, you can configure application-level tracing to always store the most recent tracing data, discarding the oldest data when the maximum number of requests is reached. For more information.
To enable tracing for an application:
1.Open your Web site's Web.config file. If no Web.config file exists, create a new file in the root folder and copy the following into it:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.web>
</system.web>
</configuration>
2.Add a trace element as a child of the system.web element.
3.In the trace element, set the enabled attribute to true.
4.If you want trace information to appear at the end of the page that it is associated with, set the trace element's pageOutput attribute to true. If you want tracing information to be displayed only in the trace viewer, set the pageOutput attribute to false.
For example, the following application trace configuration collects trace information for up to 40 requests and allows browsers on computers other than the server of origin to display the trace viewer. Trace information is not displayed in individual pages.
<configuration>
<system.web>
<trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/>
</system.web>
</configuration>
Display metadata of one of your .NET programs or libraries by the use of the ILDASM tool:C# prompt > ildasm app1.exe

We can see the assembly's metadata with all the methods and types in a tree representation. If we click on ' M A N I F E S T ' we get a window, which shows the manifest information. Even if there are a lot of non well readable lines, we are able to identify version information and all the referenced assemblies used to run the displayed executable or library.
Why does the tool we have used right now call ' Intermediate Language Disassembler ' ? Just bring back into our minds that if we compile sources, for instance with the CSharp Compiler (CSC) or any other .NET language compiler, we won't get machine code executable on a computer. Instead we get Microsoft Intermediate Language (MSIL) or shortened to Intermediate Language (IL) stored as an EXE file. To get machine code and to run the EXE we need the Common Language Runtime (CLR) part of the .NET installation somewhere on our computer.
The following default httpHandlers element is configured in the root Web.config file in the .NET Framework 2.0.
<httpHandlers>
<add... />
<remove... />
<clear/>
</httpHandlers>
add : Optional element.Specifies verb/path mapping to a handler.
clear : Optional element.Removes all handler mappings that are currently configured or inherited.
remove : Optional element.Removes a verb/path mapping to a handler. The remove directive must exactly match the verb/path combination of a previous add directive. Wildcard characters are not supported.
The <httpHandlers> settings are inherited by the application subdirectories.
The <add> directives are processed in top-down, sequential order. If two or more <add> elements specify the same verb/path combination, the final <add> overrides all others.
<httpHandlers>
<add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
<add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader"
validate="True" />
<add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
<add path="*.aspx" verb="*" type="System.Web.UI.PageHandlerFactory" validate="True" />
<add path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory" validate="True" />
<add path="*.asmx" verb="*" type="System.Web.Services.Protocols.WebServiceHandlerFactory,
System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="False" />
<add path="*.rem" verb="*" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory,
System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
validate="False" />
<add path="*.soap" verb="*" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory,
System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
validate="False" />
<add path="*.asax" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ascx" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.master" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.skin" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.browser" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.sitemap" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.dll.config" verb="GET,HEAD" type="System.Web.StaticFileHandler" validate="True" />
<add path="*.exe.config" verb="GET,HEAD" type="System.Web.StaticFileHandler" validate="True" />
<add path="*.config" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.cs" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.csproj" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.vb" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.vbproj" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.webinfo" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.licx" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.resx" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.resources" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.mdb" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.vjsproj" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.java" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.jsl" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ldb" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.dsdgm" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ssdgm" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.lsad" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ssmap" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.cd" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.dsprototype" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.lsaprototype" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.sdm" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.sdmDocument" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.mdf" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ldf" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*" verb="GET,HEAD,POST" type="System.Web.DefaultHttpHandler" validate="True" />
<add path="*" verb="*" type="System.Web.HttpMethodNotAllowedHandler" validate="True" />
</httpHandlers>
Configurable locations:
<httpHandlers>
<add... />
<remove... />
<clear/>
</httpHandlers>
add : Optional element.Specifies verb/path mapping to a handler.
clear : Optional element.Removes all handler mappings that are currently configured or inherited.
remove : Optional element.Removes a verb/path mapping to a handler. The remove directive must exactly match the verb/path combination of a previous add directive. Wildcard characters are not supported.
The <httpHandlers> settings are inherited by the application subdirectories.
The <add> directives are processed in top-down, sequential order. If two or more <add> elements specify the same verb/path combination, the final <add> overrides all others.
<httpHandlers>
<add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
<add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader"
validate="True" />
<add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
<add path="*.aspx" verb="*" type="System.Web.UI.PageHandlerFactory" validate="True" />
<add path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory" validate="True" />
<add path="*.asmx" verb="*" type="System.Web.Services.Protocols.WebServiceHandlerFactory,
System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="False" />
<add path="*.rem" verb="*" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory,
System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
validate="False" />
<add path="*.soap" verb="*" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory,
System.Runtime.Remoting, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
validate="False" />
<add path="*.asax" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ascx" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.master" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.skin" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.browser" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.sitemap" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.dll.config" verb="GET,HEAD" type="System.Web.StaticFileHandler" validate="True" />
<add path="*.exe.config" verb="GET,HEAD" type="System.Web.StaticFileHandler" validate="True" />
<add path="*.config" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.cs" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.csproj" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.vb" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.vbproj" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.webinfo" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.licx" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.resx" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.resources" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.mdb" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.vjsproj" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.java" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.jsl" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ldb" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.dsdgm" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ssdgm" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.lsad" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ssmap" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.cd" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.dsprototype" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.lsaprototype" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.sdm" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.sdmDocument" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.mdf" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*.ldf" verb="*" type="System.Web.HttpForbiddenHandler" validate="True" />
<add path="*" verb="GET,HEAD,POST" type="System.Web.DefaultHttpHandler" validate="True" />
<add path="*" verb="*" type="System.Web.HttpMethodNotAllowedHandler" validate="True" />
</httpHandlers>
Configurable locations:
- Machine.config
- Root-level Web.config
- Application-level Web.config
- Virtual or physical directory–level Web.config
The @Implements directive gets the Asp.Net page to implement a specified .NET framework interface. The only single attribute is Interface, helps to specify the .NET Framework interface. When the Asp.Net page or user control implements an interface, it has direct access to all its events, methods and properties.
@Implements Directive
<%@ Implements interface="ValidInterfaceName" %>
interface: The interface to be implemented on the page or user control.
<%@ Implements Interface=”System.Web.UI.IValidator” %>
@ Implements directive to access the six properties of the IWebPart interface.
@Implements Directive
<%@ Implements interface="ValidInterfaceName" %>
interface: The interface to be implemented on the page or user control.
<%@ Implements Interface=”System.Web.UI.IValidator” %>
@ Implements directive to access the six properties of the IWebPart interface.
The @Assembly directive is used to make your ASP.NET page aware of external components. This directive supports two attributes:
@Assembly Directive
The @ Assembly directive can be used in .aspx pages, .ascx files, .master pages and .asax files.
<%@ Assembly Name="assemblyname" %>
<%@ Assembly Src="pathname" %>
Name: A string that represents the name of the assembly to link. Here you should mention the filename without the extension.
Src: The path to a source file to dynamically compile and link against.
You must include either a Name or a Src attribute in an @ Assembly directive, but you cannot include both within the same directive. If you need to use both of these attributes, you must include multiple @ Assembly directives in the file.
@Assembly Directive
The @ Assembly directive can be used in .aspx pages, .ascx files, .master pages and .asax files.
<%@ Assembly Name="assemblyname" %>
<%@ Assembly Src="pathname" %>
Name: A string that represents the name of the assembly to link. Here you should mention the filename without the extension.
Src: The path to a source file to dynamically compile and link against.
You must include either a Name or a Src attribute in an @ Assembly directive, but you cannot include both within the same directive. If you need to use both of these attributes, you must include multiple @ Assembly directives in the file.
The @Register directive associates aliases with namespaces and class names for notation in custom server control syntax. When you drag and drop a user control onto your .aspx pages, the Visual Studio 2005 automatically creates an @Register directive at the top of the page. This register the user control on the page so that the control can be accessed on the .aspx page by a specific name.
@ Register
<%@ Register tagprefix="tagprefix"
namespace="namespace"
assembly="assembly" %>
<%@ Register tagprefix="tagprefix"
namespace="namespace" %>
<%@ Register tagprefix="tagprefix"
tagname="tagname"
src="pathname" %>
assembly:
The assembly in which the namespace associated with the tagprefix attribute resides.
namespace:
The namespace of the custom control that is being registered.
src:
The location (relative or absolute) of the declarative ASP.NET User Controls file to associate with the tagprefix:tagname pair.
tagname:
An arbitrary alias to associate with a class. This attribute is only used for user controls.
tagprefix:
An arbitrary alias that provides a shorthand reference to the namespace of the markup being used in the file that contains the directive.
@ Register
<%@ Register tagprefix="tagprefix"
namespace="namespace"
assembly="assembly" %>
<%@ Register tagprefix="tagprefix"
namespace="namespace" %>
<%@ Register tagprefix="tagprefix"
tagname="tagname"
src="pathname" %>
assembly:
The assembly in which the namespace associated with the tagprefix attribute resides.
namespace:
The namespace of the custom control that is being registered.
src:
The location (relative or absolute) of the declarative ASP.NET User Controls file to associate with the tagprefix:tagname pair.
tagname:
An arbitrary alias to associate with a class. This attribute is only used for user controls.
tagprefix:
An arbitrary alias that provides a shorthand reference to the namespace of the markup being used in the file that contains the directive.
The @Control directive is used when we build an Asp.Net user controls. The @Control directive helps us to define the properties to be inherited by the user control. These values are assigned to the user control as the page is parsed and compiled. The attributes of @Control directives are
@Control Directive
<%@ Control attribute="value" [attribute="value" ... ] %>
AutoEventWireup:
Indicates whether the control's events are autowired. true if event autowiring is enabled; otherwise, false. The default is true. For more information, see ASP.NET Web Server Control Event Model.
ClassName:
A string that specifies the class name for the control that will be dynamically compiled when the control is requested. This value can be any valid class name and can include the full namespace of a class (a fully qualified class name). If a value for this attribute is not specified, the class name for the compiled control is based on the control's file name.
Another page or control can reference the class name assigned to the control by using the @ Reference directive.
CodeBehind:
Specifies the name of the compiled file that contains the class associated with the control. This attribute is not used at run time.
CodeFile:
Specifies a path to the referenced code-behind file for the control. This attribute is used together with the Inherits attribute to associate a code-behind source file with a user control. The attribute is valid only for compiled controls.
CodeFileBaseClass:
Specifies a path to a base class for a control and its associated code-behind class. This attribute is optional, but when it is used the CodeFile attribute must also be present. Use this attribute when you want to implement a shared scenario, where you define common fields (and optionally, associated events) in a base class to reference the controls declared in a user control. Because of the ASP.NET code generation model, if you defined the fields in a base class without using the this attribute, at compile time new member definitions would be generated for the controls declared in the user control (within a separate partial class stub), and your desired scenario would not work. But if you use the CodeFileBaseClass attribute to associate the base class with the user control, and you make your partial class (its name is assigned to the Inherits attribute and its source file is referenced by the CodeFile attribute) inherit from the base class, then the fields in the base class will be able to reference the controls in the user control after code generation.
CompilationMode:
Sets whether the control should be compiled, using a string that specifies one of several enumerated options. The default value is Always, so .aspx controls are compiled by default. For details, see the CompilationMode enumeration.
CompilerOptions:
A string containing compiler options used to compile the control. In C# and Visual Basic, this is a sequence of compiler command-line switches. For more information about compiler options, see C# Compiler Options or Visual Basic Compiler.
Debug:
Indicates whether the control should be compiled with debug symbols. true if the control should be compiled with debug symbols; otherwise, false.
Description:
Provides a text description of the control. This value is ignored by the ASP.NET parser.
EnableTheming:
Indicates whether themes are used on the control. true if themes are used; otherwise, false. The default is true.
EnableViewState:
Indicates whether view state is maintained across control requests. true if view state is maintained; otherwise, false. The default is true.
Explicit:
Determines whether the control is compiled using the Visual Basic Option Explicit mode. true indicates that the Visual Basic explicit compile option is enabled and that all variables must be declared using a Dim, Private, Public, or ReDim statement; otherwise, false. The default is false.
Inherits:
Defines a code-behind class for the control to inherit. This can be any class derived from the UserControl class. Used with the CodeFile attribute, which contains the path to the source file for the code-behind class.
Language:
Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code declaration blocks within the control. Values can represent any .NET Framework-supported language, including Visual Basic, C#, or JScript. Only one language can be used and specified per control.
LinePragmas:
Determines whether the runtime should generate line pragmas in the source code. These are compiler options that are often used by debugging tools to mark specific locations in a source file. true if line pragmas should be generated; otherwise, false.
Src:
Points to the source file of the class used for the code behind of the user control.
Strict:
Indicates that the control should be compiled using the Visual Basic Option Strict mode. true if Option Strict is enabled; otherwise, false. The default is false.
TargetSchema:
Specifies the name of a schema that validates content on the control. This serves only a descriptive purpose; no actual validation is performed, and the attribute is ignored by the parser.
WarningLevel:
Indicates the compiler warning level at which you want the compiler to treat warnings as errors, thus aborting compilation of the control. Possible warning levels are 0 through 4.
For More Detail Read MSDN
@Control Directive
<%@ Control attribute="value" [attribute="value" ... ] %>
AutoEventWireup:
Indicates whether the control's events are autowired. true if event autowiring is enabled; otherwise, false. The default is true. For more information, see ASP.NET Web Server Control Event Model.
ClassName:
A string that specifies the class name for the control that will be dynamically compiled when the control is requested. This value can be any valid class name and can include the full namespace of a class (a fully qualified class name). If a value for this attribute is not specified, the class name for the compiled control is based on the control's file name.
Another page or control can reference the class name assigned to the control by using the @ Reference directive.
CodeBehind:
Specifies the name of the compiled file that contains the class associated with the control. This attribute is not used at run time.
CodeFile:
Specifies a path to the referenced code-behind file for the control. This attribute is used together with the Inherits attribute to associate a code-behind source file with a user control. The attribute is valid only for compiled controls.
CodeFileBaseClass:
Specifies a path to a base class for a control and its associated code-behind class. This attribute is optional, but when it is used the CodeFile attribute must also be present. Use this attribute when you want to implement a shared scenario, where you define common fields (and optionally, associated events) in a base class to reference the controls declared in a user control. Because of the ASP.NET code generation model, if you defined the fields in a base class without using the this attribute, at compile time new member definitions would be generated for the controls declared in the user control (within a separate partial class stub), and your desired scenario would not work. But if you use the CodeFileBaseClass attribute to associate the base class with the user control, and you make your partial class (its name is assigned to the Inherits attribute and its source file is referenced by the CodeFile attribute) inherit from the base class, then the fields in the base class will be able to reference the controls in the user control after code generation.
CompilationMode:
Sets whether the control should be compiled, using a string that specifies one of several enumerated options. The default value is Always, so .aspx controls are compiled by default. For details, see the CompilationMode enumeration.
CompilerOptions:
A string containing compiler options used to compile the control. In C# and Visual Basic, this is a sequence of compiler command-line switches. For more information about compiler options, see C# Compiler Options or Visual Basic Compiler.
Debug:
Indicates whether the control should be compiled with debug symbols. true if the control should be compiled with debug symbols; otherwise, false.
Description:
Provides a text description of the control. This value is ignored by the ASP.NET parser.
EnableTheming:
Indicates whether themes are used on the control. true if themes are used; otherwise, false. The default is true.
EnableViewState:
Indicates whether view state is maintained across control requests. true if view state is maintained; otherwise, false. The default is true.
Explicit:
Determines whether the control is compiled using the Visual Basic Option Explicit mode. true indicates that the Visual Basic explicit compile option is enabled and that all variables must be declared using a Dim, Private, Public, or ReDim statement; otherwise, false. The default is false.
Inherits:
Defines a code-behind class for the control to inherit. This can be any class derived from the UserControl class. Used with the CodeFile attribute, which contains the path to the source file for the code-behind class.
Language:
Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code declaration blocks within the control. Values can represent any .NET Framework-supported language, including Visual Basic, C#, or JScript. Only one language can be used and specified per control.
LinePragmas:
Determines whether the runtime should generate line pragmas in the source code. These are compiler options that are often used by debugging tools to mark specific locations in a source file. true if line pragmas should be generated; otherwise, false.
Src:
Points to the source file of the class used for the code behind of the user control.
Strict:
Indicates that the control should be compiled using the Visual Basic Option Strict mode. true if Option Strict is enabled; otherwise, false. The default is false.
TargetSchema:
Specifies the name of a schema that validates content on the control. This serves only a descriptive purpose; no actual validation is performed, and the attribute is ignored by the parser.
WarningLevel:
Indicates the compiler warning level at which you want the compiler to treat warnings as errors, thus aborting compilation of the control. Possible warning levels are 0 through 4.
For More Detail Read MSDN
To access members of a specific master page from a content page, you can create a strongly typed reference to the master page by creating a @MasterType directive. This directive supports of two attributes such as TypeName and VirtualPath.
@MasterType Directive
<%@ Master attribute="value" [attribute="value"...] %>
AutoEventWireup:
Indicates whether simple event handlers can be defined for specific life cycle stages using the syntax Page without any explicit hookup or event signature. true if event auto-wiring is enabled; otherwise, false. The default is true.
ClassName:
Specifies the class name for the class that is automatically generated from the markup and compiled when the master page is processed. This value can be any valid class name and can include a namespace.
CodeFile:
Specifies the name of a separate file that contains a partial class with the event handlers and other master page–specific code.
CompilationMode:
Specifies whether to compile an ASP.NET master page at run time. Options are Always to always compile the page; Auto, if ASP.NET is to avoid compiling the page, if possible; and Never, to never compile the page or control. The default is Always.
CompilerOptions:
Provides a string containing compiler options to use to compile the page. In C# and Microsoft Visual Basic.
Debug:
Indicates whether to compile the master page with debug symbols. true, to compile with debug symbols; otherwise, false.
Description:
Provides a text description of the master page. This value is ignored by the ASP.NET parser.
EnableTheming:
Indicates whether the appearance of the master page and of controls on the master page can be modified, if a theme is applied. true if a theme can be applied; otherwise, false. The default is true. Setting the EnableTheming attribute is primarily useful when a page theme is defined in the Web.config file and applies to all pages, by default.
EnableViewState:
Indicates whether view state is maintained across page requests. true to maintain view state; otherwise, false. The default is true.
Explicit:
Determines whether the page is compiled using the Visual Basic Option Explicit mode. true indicates that the Visual Basic explicit compile option is enabled and that all variables must be declared using a Dim, Private, Public, or ReDim statement; otherwise, false. The default is false.
Inherits:
Specifies a code-behind class for the page to inherit. This can be any class derived from the MasterPage class. For information about code-behind classes, see ASP.NET Page Class Overview.
Language:
Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code declaration blocks within the page. Values can represent any language that is supported by the .NET Framework, including VB (Visual Basic), C#, and JScript.
LinePragmas:
Determines whether the runtime should generate pragmas in the generated code.
MasterPageFile:
Specifies the .master file that acts as a master page for a master page. The MasterPageFile attribute is used in a master page when defining a child master page in a nested master-page scenario. For details, see Nested ASP.NET Master Pages.
Src:
Specifies the source file name of the code-behind class to dynamically compile when the page is requested. You can choose to include programming logic for your page either in a code-behind class or in a Code Declaration Blocks in the .aspx file.
Strict:
Specifies whether to compile the page using the Visual Basic Option Strict mode. true if Option Strict is enabled; otherwise, false. The default is false.
WarningLevel:
Specifies the compiler warning level at which you want the compiler to abort compilation for the page. Possible values are from 0 through 4. For more information, see WarningLevel()()().
Source: MSDN
@MasterType Directive
<%@ Master attribute="value" [attribute="value"...] %>
AutoEventWireup:
Indicates whether simple event handlers can be defined for specific life cycle stages using the syntax Page without any explicit hookup or event signature. true if event auto-wiring is enabled; otherwise, false. The default is true.
ClassName:
Specifies the class name for the class that is automatically generated from the markup and compiled when the master page is processed. This value can be any valid class name and can include a namespace.
CodeFile:
Specifies the name of a separate file that contains a partial class with the event handlers and other master page–specific code.
CompilationMode:
Specifies whether to compile an ASP.NET master page at run time. Options are Always to always compile the page; Auto, if ASP.NET is to avoid compiling the page, if possible; and Never, to never compile the page or control. The default is Always.
CompilerOptions:
Provides a string containing compiler options to use to compile the page. In C# and Microsoft Visual Basic.
Debug:
Indicates whether to compile the master page with debug symbols. true, to compile with debug symbols; otherwise, false.
Description:
Provides a text description of the master page. This value is ignored by the ASP.NET parser.
EnableTheming:
Indicates whether the appearance of the master page and of controls on the master page can be modified, if a theme is applied. true if a theme can be applied; otherwise, false. The default is true. Setting the EnableTheming attribute is primarily useful when a page theme is defined in the Web.config file and applies to all pages, by default.
EnableViewState:
Indicates whether view state is maintained across page requests. true to maintain view state; otherwise, false. The default is true.
Explicit:
Determines whether the page is compiled using the Visual Basic Option Explicit mode. true indicates that the Visual Basic explicit compile option is enabled and that all variables must be declared using a Dim, Private, Public, or ReDim statement; otherwise, false. The default is false.
Inherits:
Specifies a code-behind class for the page to inherit. This can be any class derived from the MasterPage class. For information about code-behind classes, see ASP.NET Page Class Overview.
Language:
Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code declaration blocks within the page. Values can represent any language that is supported by the .NET Framework, including VB (Visual Basic), C#, and JScript.
LinePragmas:
Determines whether the runtime should generate pragmas in the generated code.
MasterPageFile:
Specifies the .master file that acts as a master page for a master page. The MasterPageFile attribute is used in a master page when defining a child master page in a nested master-page scenario. For details, see Nested ASP.NET Master Pages.
Src:
Specifies the source file name of the code-behind class to dynamically compile when the page is requested. You can choose to include programming logic for your page either in a code-behind class or in a Code Declaration Blocks in the .aspx file.
Strict:
Specifies whether to compile the page using the Visual Basic Option Strict mode. true if Option Strict is enabled; otherwise, false. The default is false.
WarningLevel:
Specifies the compiler warning level at which you want the compiler to abort compilation for the page. Possible values are from 0 through 4. For more information, see WarningLevel()()().
Source: MSDN
Asp.Net Page directives are something that is a part of every asp.net pages. Page directives are instructions, inserted at the top of an ASP.NET page, to control the behavior of the asp.net pages. So it is type of mixed settings related to how a page should render and processed.
@Page Directive
<%@ Page attribute="value" [attribute="value"...] %>
The @Page directive enables you to specify attributes and values for an Asp.Net Page to be used when the page is parsed and compiled. Every .aspx files should include this @Page directive to execute. There are many attributes belong to this directive. We shall discuss some of the important attributes here.
Async :
Makes the page an asynchronous handler (that is, it causes the page to use an implementation of IHttpAsyncHandler to process requests).
The default is false.
AsyncTimeOut:
Defines the time-out interval (in seconds) used when processing asynchronous tasks. The default is 45 seconds.
The value must be an integer.
AspCompat:
When set to true, allows the page to be executed on a single-threaded apartment (STA) thread. This allows the page to call STA components, such as a component developed with Microsoft Visual Basic 6.0. Setting this attribute to true also allows the page to call COM+ version 1.0 components that require access to unmanaged Active Server Pages (ASP) built-in objects. These are accessible through the ObjectContext object or the OnStartPage method. The default is false.
AutoEventWireup:
Indicates whether the page's events are autowired. true if event autowiring is enabled; otherwise, false. The default is true. For more information, see ASP.NET Web Server Control Event Model.
Buffer:
Determines whether HTTP response buffering is enabled. true if page buffering is enabled; otherwise, false.
The default is true.
ClassName:
A string that specifies the name of the page class that will be dynamically compiled when the page is requested. This value can be any valid class name and can include a fully qualified class name. If a value for this attribute is not specified, the class name for the compiled page is based on the page's file name and uses the default namespace ASP. If a value for the ClassName attribute is specified without a full namespace, then the namespace ASP is used, combined with the specified class name to create a fully qualified class name.
Another page can reference the class name assigned to the first page by using the @ Reference directive.
ClientTarget:
Indicates the target user agent (typically, a Web browser such as Microsoft Internet Explorer) for which ASP.NET server controls should render content. This value can be any valid alias as defined within the <clientTarget> section of the application's configuration file.
CodeBehind:
Specifies the name of the compiled file that contains the class associated with the page. This attribute is not used at run time.
CodeFile:
Specifies a path to the referenced code-behind file for the page. This attribute is used together with the Inherits attribute to associate a code-behind source file with a Web page. The attribute is valid only for compiled pages.
CodeFileBaseClass:
Specifies the type name of a base class for a page and its associated code-behind class. This attribute is optional, but when it is used the CodeFile attribute must also be present. Use this attribute when you want to implement a shared scenario, where you define common fields (and optionally, associated events) in a base class to reference the controls declared in a Web page. Because of the ASP.NET code generation model, if you defined the fields in a base class without using this attribute, at compile time new member definitions would be generated for the controls declared in the Web page (within a separate partial class stub), and your desired scenario would not work. But if you use the CodeFileBaseClass attribute to associate the base class with the page, and you make your partial class (its name is assigned to the Inherits attribute and its source file is referenced by the CodeFile attribute) inherit from the base class, then the fields in the base class will be able to reference the controls on the age after code generation.
CodePage:
Indicates the value of the encoding scheme used for the response. The value is an integer that serves as an ID for the encoding scheme. For a list of possible CodePage IDs, see the Encoding class.
CompilationMode:
Sets whether the page should be compiled, using a string that specifies one of several enumerated options. The default value is Always, so .aspx pages are compiled by default. For details, see the CompilationMode enumeration.
CompilerOptions:
A string containing compiler options used to compile the page. In C# and Visual Basic, this is a sequence of compiler command-line switches. For more information about compiler options, see C# Compiler Options or Visual Basic Compiler.
ContentType:
Defines the HTTP content type of the response as a standard MIME type. Supports any valid HTTP content-type string. For a list of possible values.
Culture:
Indicates the culture setting for the page. The value of this attribute must be a valid culture ID. Note that the LCID and Culture attributes are mutually exclusive; if you use one of these attributes, you cannot use the other in the same page. For more information about possible culture values, see the CultureInfo class.
Debug:
Indicates whether the page should be compiled with debug symbols. true if the page should be compiled with debug symbols; otherwise, false. Because this setting affects performance, you should only set the attribute to true during development.
Description:
Provides a text description of the page. This value is ignored by the ASP.NET parser.
EnableEventValidation:
Enables validation of events in postback and callback scenarios. true if events are being validated; otherwise, false. The default is true.
Page event validation reduces the risk of unauthorized postback requests and callbacks. When the enableEventValidation property is set to true, ASP.NET allows only the events that can be raised on the control during a postback request or callback. With this model, a control registers its events during rendering and then validates the events during the post-back or callback handling. All event-driven controls in ASP.NET use this feature by default.
It is strongly recommended that you do not disable event validation. Before disabling event validation, you should be sure that no postback could be constructed that would have an unintended effect on your application.
EnableSessionState:
Defines session-state requirements for the page. true if session state is enabled; ReadOnly if session state can be read but not changed; otherwise, false. The default is true. These values are case-insensitive. For more information, see ASP.NET Session State Overview.
EnableTheming:
Indicates whether themes are used on the page. true if themes are used; otherwise, false. The default is true.
EnableViewState:
Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
EnableViewStateMac:
Indicates that ASP.NET should run a machine authentication check (MAC) on the page's view state when the page is posted back from the client. true if view state should be MAC checked; otherwise, false. The default is true.
ErrorPage:
Defines a target URL for redirection if an unhandled page exception occurs.
Explicit:
Determines whether the page is compiled using the Visual Basic Option Explicit mode. true indicates that the Visual Basic explicit compile option is enabled and that all variables must be declared using a Dim, Private, Public, or ReDim statement; otherwise, false. The default is false.
Inherits:
Defines a code-behind class for the page to inherit. This can be any class derived from the Page class. This attribute is used with the CodeFile attribute, which contains the path to the source file for the code-behind class. The Inherits attribute is case-sensitive when using C# as the page language, and case-insensitive when using Visual Basic as the page language.
If the Inherits attribute does not contain a namespace, ASP.NET checks whether the ClassName attribute contains a namespace. If so, ASP.NET attempts to load the class referenced in the Inherits attribute using the namespace of the ClassName attribute. (This assumes that the Inherits attribute and the ClassName attribute both use the same namespace.)
For more information about code-behind classes, see ASP.NET Web Page Code Model.
Language:
Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code declaration blocks within the page. Values can represent any .NET Framework-supported language, including Visual Basic, C#, or JScript. Only one language can be used and specified per page.
LCID:
Defines the locale identifier for the Web Forms page.
LinePragmas:
Determines whether the runtime should generate line pragmas in the source code. These are compiler options that are often used by debugging tools to mark specific locations in a source file. true if line pragmas should be generated; otherwise, false.
MaintainScrollPositionOnPostback:
Indicates whether to return the user to the same position in the client browser after postback. true if users should be returned to the same position; otherwise, false. The default is false.
MasterPageFile:
Sets the path to the master page for the content page or nested master page. Supports relative and absolute paths.
ResponseEncoding:
Indicates the name of the encoding scheme used for the HTTP response that contains a page's content. The value assigned to this attribute is a valid encoding name. for a list of possible encoding names, see the Encoding class. You can also call the GetEncodings()()() method for a list of possible encoding names and IDs.
SmartNavigation:
Indicates whether the page supports the smart navigation feature of Internet Explorer 5.5 or later. true if smart navigation is enabled; otherwise, false. The default is false.
You can also set the SmartNavigation property for the page in code, but in general you should set it using the attribute with the @ Page directive. For more information about how this feature improves the user experience of navigating on Web pages, see the SmartNavigation()()() property.
Src:
Specifies a path to a source file containing code that is linked to the page. In the linked source file, you can choose to include programming logic for your page either in a class or in code declaration blocks.
You can use the Src attribute to link build providers to the page. For more information, see the BuildProvider class. Also, in versions of ASP.NET prior to 2.0, the Src attribute was used as an alternative way to link a code-behind file to a page. In ASP.NET 2.0, the preferred approach to linking a code-behind source file to a page is to use the Inherits attribute to specify a class, along with the CodeFile attribute to specify the path to the source file for the class.
Strict:
Indicates that the page should be compiled using the Visual Basic Option Strict mode. true if Option Strict is enabled; otherwise, false. The default is false.
StyleSheetTheme:
Specifies a valid theme identifier to use on the page. When the StyleSheetTheme attribute is set, individual controls can override the stylistic settings contained in a theme. Thus a theme can provide an overall look for a site, while the settings contained in the StyleSheetTheme attribute enable you to customize particular settings on a page and its individual controls.
TargetSchema:
Specifies the name of a schema that validates content on the page. This serves only a descriptive purpose; no actual validation is performed, and the attribute is ignored by the parser.
Theme:
Specifies a valid theme identifier to use on the page. When the Theme attribute is set without using the StyleSheetTheme attribute, it overrides individual style settings on controls, enabling you to create a unified and consistent look on a page.
Title:
Specifies a title for the page that is rendered within the HTML <title> tags in the response. The title can also be accessed programmatically as a property of the page. For details, see the Title()()() property.
Trace:
Indicates whether tracing is enabled. true if tracing is enabled; otherwise, false. The default is false. For more information, see ASP.NET Tracing Overview.
TraceMode:
Indicates how trace messages are to be displayed for the page when tracing is enabled. Possible values are SortByTime and SortByCategory. The default, when tracing is enabled, is SortByTime. For more information about tracing, see ASP.NET Tracing Overview.
Transaction:
Indicates whether transactions are supported on the page. Possible values are Disabled, NotSupported, Supported, Required, and RequiresNew. The default is Disabled.
UICulture:
Specifies the user interface (UI) culture setting to use for the page. Supports any valid UI culture value.
ValidateRequest:
Indicates whether request validation should occur. If true, request validation checks all input data against a hard-coded list of potentially dangerous values. If a match occurs, an HttpRequestValidationException exception is thrown. The default is true.
This feature is enabled in the machine configuration file (Machine.config). You can disable it in your application configuration file (Web.config) or on the page by setting this attribute to false.
ViewStateEncryptionMode:
Determines how view state is encrypted, with three possible enumerated values: Auto, Always, or Never. The default is Auto, meaning that view state will be encrypted if an individual control requests it. For more information, see the ViewStateEncryptionMode enumeration.
WarningLevel:
Indicates the compiler warning level at which you want the compiler to treat warnings as errors, thus aborting compilation of the page. Possible warning levels are 0 through 4. For more information, see the WarningLevel()()() property.
Source: MSDN
@Page Directive
<%@ Page attribute="value" [attribute="value"...] %>
The @Page directive enables you to specify attributes and values for an Asp.Net Page to be used when the page is parsed and compiled. Every .aspx files should include this @Page directive to execute. There are many attributes belong to this directive. We shall discuss some of the important attributes here.
Async :
Makes the page an asynchronous handler (that is, it causes the page to use an implementation of IHttpAsyncHandler to process requests).
The default is false.
AsyncTimeOut:
Defines the time-out interval (in seconds) used when processing asynchronous tasks. The default is 45 seconds.
The value must be an integer.
AspCompat:
When set to true, allows the page to be executed on a single-threaded apartment (STA) thread. This allows the page to call STA components, such as a component developed with Microsoft Visual Basic 6.0. Setting this attribute to true also allows the page to call COM+ version 1.0 components that require access to unmanaged Active Server Pages (ASP) built-in objects. These are accessible through the ObjectContext object or the OnStartPage method. The default is false.
AutoEventWireup:
Indicates whether the page's events are autowired. true if event autowiring is enabled; otherwise, false. The default is true. For more information, see ASP.NET Web Server Control Event Model.
Buffer:
Determines whether HTTP response buffering is enabled. true if page buffering is enabled; otherwise, false.
The default is true.
ClassName:
A string that specifies the name of the page class that will be dynamically compiled when the page is requested. This value can be any valid class name and can include a fully qualified class name. If a value for this attribute is not specified, the class name for the compiled page is based on the page's file name and uses the default namespace ASP. If a value for the ClassName attribute is specified without a full namespace, then the namespace ASP is used, combined with the specified class name to create a fully qualified class name.
Another page can reference the class name assigned to the first page by using the @ Reference directive.
ClientTarget:
Indicates the target user agent (typically, a Web browser such as Microsoft Internet Explorer) for which ASP.NET server controls should render content. This value can be any valid alias as defined within the <clientTarget> section of the application's configuration file.
CodeBehind:
Specifies the name of the compiled file that contains the class associated with the page. This attribute is not used at run time.
CodeFile:
Specifies a path to the referenced code-behind file for the page. This attribute is used together with the Inherits attribute to associate a code-behind source file with a Web page. The attribute is valid only for compiled pages.
CodeFileBaseClass:
Specifies the type name of a base class for a page and its associated code-behind class. This attribute is optional, but when it is used the CodeFile attribute must also be present. Use this attribute when you want to implement a shared scenario, where you define common fields (and optionally, associated events) in a base class to reference the controls declared in a Web page. Because of the ASP.NET code generation model, if you defined the fields in a base class without using this attribute, at compile time new member definitions would be generated for the controls declared in the Web page (within a separate partial class stub), and your desired scenario would not work. But if you use the CodeFileBaseClass attribute to associate the base class with the page, and you make your partial class (its name is assigned to the Inherits attribute and its source file is referenced by the CodeFile attribute) inherit from the base class, then the fields in the base class will be able to reference the controls on the age after code generation.
CodePage:
Indicates the value of the encoding scheme used for the response. The value is an integer that serves as an ID for the encoding scheme. For a list of possible CodePage IDs, see the Encoding class.
CompilationMode:
Sets whether the page should be compiled, using a string that specifies one of several enumerated options. The default value is Always, so .aspx pages are compiled by default. For details, see the CompilationMode enumeration.
CompilerOptions:
A string containing compiler options used to compile the page. In C# and Visual Basic, this is a sequence of compiler command-line switches. For more information about compiler options, see C# Compiler Options or Visual Basic Compiler.
ContentType:
Defines the HTTP content type of the response as a standard MIME type. Supports any valid HTTP content-type string. For a list of possible values.
Culture:
Indicates the culture setting for the page. The value of this attribute must be a valid culture ID. Note that the LCID and Culture attributes are mutually exclusive; if you use one of these attributes, you cannot use the other in the same page. For more information about possible culture values, see the CultureInfo class.
Debug:
Indicates whether the page should be compiled with debug symbols. true if the page should be compiled with debug symbols; otherwise, false. Because this setting affects performance, you should only set the attribute to true during development.
Description:
Provides a text description of the page. This value is ignored by the ASP.NET parser.
EnableEventValidation:
Enables validation of events in postback and callback scenarios. true if events are being validated; otherwise, false. The default is true.
Page event validation reduces the risk of unauthorized postback requests and callbacks. When the enableEventValidation property is set to true, ASP.NET allows only the events that can be raised on the control during a postback request or callback. With this model, a control registers its events during rendering and then validates the events during the post-back or callback handling. All event-driven controls in ASP.NET use this feature by default.
It is strongly recommended that you do not disable event validation. Before disabling event validation, you should be sure that no postback could be constructed that would have an unintended effect on your application.
EnableSessionState:
Defines session-state requirements for the page. true if session state is enabled; ReadOnly if session state can be read but not changed; otherwise, false. The default is true. These values are case-insensitive. For more information, see ASP.NET Session State Overview.
EnableTheming:
Indicates whether themes are used on the page. true if themes are used; otherwise, false. The default is true.
EnableViewState:
Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
EnableViewStateMac:
Indicates that ASP.NET should run a machine authentication check (MAC) on the page's view state when the page is posted back from the client. true if view state should be MAC checked; otherwise, false. The default is true.
ErrorPage:
Defines a target URL for redirection if an unhandled page exception occurs.
Explicit:
Determines whether the page is compiled using the Visual Basic Option Explicit mode. true indicates that the Visual Basic explicit compile option is enabled and that all variables must be declared using a Dim, Private, Public, or ReDim statement; otherwise, false. The default is false.
Inherits:
Defines a code-behind class for the page to inherit. This can be any class derived from the Page class. This attribute is used with the CodeFile attribute, which contains the path to the source file for the code-behind class. The Inherits attribute is case-sensitive when using C# as the page language, and case-insensitive when using Visual Basic as the page language.
If the Inherits attribute does not contain a namespace, ASP.NET checks whether the ClassName attribute contains a namespace. If so, ASP.NET attempts to load the class referenced in the Inherits attribute using the namespace of the ClassName attribute. (This assumes that the Inherits attribute and the ClassName attribute both use the same namespace.)
For more information about code-behind classes, see ASP.NET Web Page Code Model.
Language:
Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code declaration blocks within the page. Values can represent any .NET Framework-supported language, including Visual Basic, C#, or JScript. Only one language can be used and specified per page.
LCID:
Defines the locale identifier for the Web Forms page.
LinePragmas:
Determines whether the runtime should generate line pragmas in the source code. These are compiler options that are often used by debugging tools to mark specific locations in a source file. true if line pragmas should be generated; otherwise, false.
MaintainScrollPositionOnPostback:
Indicates whether to return the user to the same position in the client browser after postback. true if users should be returned to the same position; otherwise, false. The default is false.
MasterPageFile:
Sets the path to the master page for the content page or nested master page. Supports relative and absolute paths.
ResponseEncoding:
Indicates the name of the encoding scheme used for the HTTP response that contains a page's content. The value assigned to this attribute is a valid encoding name. for a list of possible encoding names, see the Encoding class. You can also call the GetEncodings()()() method for a list of possible encoding names and IDs.
SmartNavigation:
Indicates whether the page supports the smart navigation feature of Internet Explorer 5.5 or later. true if smart navigation is enabled; otherwise, false. The default is false.
You can also set the SmartNavigation property for the page in code, but in general you should set it using the attribute with the @ Page directive. For more information about how this feature improves the user experience of navigating on Web pages, see the SmartNavigation()()() property.
Src:
Specifies a path to a source file containing code that is linked to the page. In the linked source file, you can choose to include programming logic for your page either in a class or in code declaration blocks.
You can use the Src attribute to link build providers to the page. For more information, see the BuildProvider class. Also, in versions of ASP.NET prior to 2.0, the Src attribute was used as an alternative way to link a code-behind file to a page. In ASP.NET 2.0, the preferred approach to linking a code-behind source file to a page is to use the Inherits attribute to specify a class, along with the CodeFile attribute to specify the path to the source file for the class.
Strict:
Indicates that the page should be compiled using the Visual Basic Option Strict mode. true if Option Strict is enabled; otherwise, false. The default is false.
StyleSheetTheme:
Specifies a valid theme identifier to use on the page. When the StyleSheetTheme attribute is set, individual controls can override the stylistic settings contained in a theme. Thus a theme can provide an overall look for a site, while the settings contained in the StyleSheetTheme attribute enable you to customize particular settings on a page and its individual controls.
TargetSchema:
Specifies the name of a schema that validates content on the page. This serves only a descriptive purpose; no actual validation is performed, and the attribute is ignored by the parser.
Theme:
Specifies a valid theme identifier to use on the page. When the Theme attribute is set without using the StyleSheetTheme attribute, it overrides individual style settings on controls, enabling you to create a unified and consistent look on a page.
Title:
Specifies a title for the page that is rendered within the HTML <title> tags in the response. The title can also be accessed programmatically as a property of the page. For details, see the Title()()() property.
Trace:
Indicates whether tracing is enabled. true if tracing is enabled; otherwise, false. The default is false. For more information, see ASP.NET Tracing Overview.
TraceMode:
Indicates how trace messages are to be displayed for the page when tracing is enabled. Possible values are SortByTime and SortByCategory. The default, when tracing is enabled, is SortByTime. For more information about tracing, see ASP.NET Tracing Overview.
Transaction:
Indicates whether transactions are supported on the page. Possible values are Disabled, NotSupported, Supported, Required, and RequiresNew. The default is Disabled.
UICulture:
Specifies the user interface (UI) culture setting to use for the page. Supports any valid UI culture value.
ValidateRequest:
Indicates whether request validation should occur. If true, request validation checks all input data against a hard-coded list of potentially dangerous values. If a match occurs, an HttpRequestValidationException exception is thrown. The default is true.
This feature is enabled in the machine configuration file (Machine.config). You can disable it in your application configuration file (Web.config) or on the page by setting this attribute to false.
ViewStateEncryptionMode:
Determines how view state is encrypted, with three possible enumerated values: Auto, Always, or Never. The default is Auto, meaning that view state will be encrypted if an individual control requests it. For more information, see the ViewStateEncryptionMode enumeration.
WarningLevel:
Indicates the compiler warning level at which you want the compiler to treat warnings as errors, thus aborting compilation of the page. Possible warning levels are 0 through 4. For more information, see the WarningLevel()()() property.
Source: MSDN
| Related Topic: |
JQuery is another javascript library which eases javascript developemt - and it also includes some Ajax functionality.
jQuery is a fast, lightweight JavaScript library that is CSS3 compliant and supports many browsers. The jQuery framework is extensible and very nicely handles DOM manipulations, CSS, AJAX, Events and Animations.
It is totally different from JavaScript because it is a language whereas jQuery is a library written using JavaScript.
You can download the source code & plugins and read some excellent tutorials at the JQuery website. jQuery was created by John Resig.
Display an alert on asp:Button click using jQuery:
Add a Button element to the page as shown below:
<asp:Button ID="Button1" runat="server" Text="Button" />
Now in order to tell the browser to perform some action using jQuery as soon as the document is ready or loaded, use this block:
<script type="text/javascript">
$(document).ready(function() {
// add code here
});
</script>
Add your code in the function block
<script type="text/javascript">
$(document).ready(function() {
$("#Button1").click(function() {
alert("Hello world!");
});
});
</script>
jQuery is a fast, lightweight JavaScript library that is CSS3 compliant and supports many browsers. The jQuery framework is extensible and very nicely handles DOM manipulations, CSS, AJAX, Events and Animations.
It is totally different from JavaScript because it is a language whereas jQuery is a library written using JavaScript.
You can download the source code & plugins and read some excellent tutorials at the JQuery website. jQuery was created by John Resig.
Display an alert on asp:Button click using jQuery:
Add a Button element to the page as shown below:
<asp:Button ID="Button1" runat="server" Text="Button" />
Now in order to tell the browser to perform some action using jQuery as soon as the document is ready or loaded, use this block:
<script type="text/javascript">
$(document).ready(function() {
// add code here
});
</script>
Add your code in the function block
<script type="text/javascript">
$(document).ready(function() {
$("#Button1").click(function() {
alert("Hello world!");
});
});
</script>
A handler is responsible for fulfilling requests from a browser. Requests that a browser manages are either handled by file extension or by calling the handler directly.The low level Request and Response API to service incoming Http requests are Http Handlers in Asp.Net. All handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.
You implement the IHttpHandler interface to create a synchronous handler and the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest method and the IsReusable property. The ProcessRequest method handles the actual processing for requests made, while the Boolean IsReusable property specifies whether your handler can be pooled for reuse to increase performance or whether a new handler is required for each request.
The .ashx file extension is reserved for custom handlers. If you create a custom handler with a file name extension of .ashx, it will automatically be registered within IIS and ASP.NET. If you choose to use an alternate file extension, you will have to register the extension within IIS and ASP.NET. The advantage of using an extension other than .ashx is that you can assign multiple file extensions to one handler.
Configuring HTTP Handlers
The <httpHandlers> configuration section handler is responsible for mapping incoming URLs to the IHttpHandler or IHttpHandlerFactory class. It can be declared at the computer, site, or application level. Subdirectories inherit these settings.
Administrators use the <add> tag directive to configure the <httpHandlers> section. <Add> directives are interpreted and processed in a top-down sequential order. Use the following syntax for the <httpHandler> section handler:
<httpHandlers><add verb="[verb list]" path="[path/wildcard]" type="[COM+ Class], [Assembly]" validate="[true/false]" /><remove verb="[verb list]" path="[path/wildcard]" /><clear /></httpHandlers>
Creating HTTP Handlers
To create an HTTP handler, you must implement the IHttpHandler interface. The IHttpHandler interface has one method and one property with the following signatures:
void ProcessRequest(HttpContext);
bool IsReusable {get;}
You implement the IHttpHandler interface to create a synchronous handler and the IHttpAsyncHandler interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest method and the IsReusable property. The ProcessRequest method handles the actual processing for requests made, while the Boolean IsReusable property specifies whether your handler can be pooled for reuse to increase performance or whether a new handler is required for each request.
The .ashx file extension is reserved for custom handlers. If you create a custom handler with a file name extension of .ashx, it will automatically be registered within IIS and ASP.NET. If you choose to use an alternate file extension, you will have to register the extension within IIS and ASP.NET. The advantage of using an extension other than .ashx is that you can assign multiple file extensions to one handler.
Configuring HTTP Handlers
The <httpHandlers> configuration section handler is responsible for mapping incoming URLs to the IHttpHandler or IHttpHandlerFactory class. It can be declared at the computer, site, or application level. Subdirectories inherit these settings.
Administrators use the <add> tag directive to configure the <httpHandlers> section. <Add> directives are interpreted and processed in a top-down sequential order. Use the following syntax for the <httpHandler> section handler:
<httpHandlers><add verb="[verb list]" path="[path/wildcard]" type="[COM+ Class], [Assembly]" validate="[true/false]" /><remove verb="[verb list]" path="[path/wildcard]" /><clear /></httpHandlers>
Creating HTTP Handlers
To create an HTTP handler, you must implement the IHttpHandler interface. The IHttpHandler interface has one method and one property with the following signatures:
void ProcessRequest(HttpContext);
bool IsReusable {get;}
Using Cache dependency we can set the dependency of the catch with some data or entity to changed. So we can set the depedency of cache by which we can update, remove cache. There are three types of dependencies supported in ASP.NET.
Using cache dependency we can force ASP.NET to expire the cached data item from the cache when the dependency file changes. We can set Dependency to multiple file also . on such case dependency should be built from an array of files or directories.
It's Uses : File based dependency is very use full when need to update some data that displaing to the user based on some changed on file. As for Example, a New Sites always shows data from a file , now if some breaking news come, they just update the file and cached should expire and during the expire time we can reload the cache with updated data using OnRemoveCallBack.
Key Based Dependency : Key-based dependency invalidates a particular cache item when another cache item changes.
It's Uses : This is use full when we have multiple interrelated object are in cache and if one of the object changed we need to updated or expire all of them, Key Based Dependency will be best option.
Time Based Dependency : Time-based dependency causes an item to expire at a defined time. Cache.Insert() method of the Cache class is used to create a time-based dependency. Two Types of Time based Dependency are available.
Sliding: Resets the time for the item in the Cache to expire on each request. This is useful when an item in the cache is to be kept alive so long as requests for that item are coming in from various clients.
With those dependency ASP.NET also support
In addition to the dependencies, ASP.NET allows the following:
Automatic expiration: The cache items that are underused and have no dependencies are automatically expired.
Support for callback: The Cache object can be configured to call a given piece of code that will be executed when an item is removed from the cache. This gives you an opportunity to update the cache. We can use OnRemoveCallback().
- File based Dependency
- Key Based Dependency
- Time Based Dependency
Using cache dependency we can force ASP.NET to expire the cached data item from the cache when the dependency file changes. We can set Dependency to multiple file also . on such case dependency should be built from an array of files or directories.
It's Uses : File based dependency is very use full when need to update some data that displaing to the user based on some changed on file. As for Example, a New Sites always shows data from a file , now if some breaking news come, they just update the file and cached should expire and during the expire time we can reload the cache with updated data using OnRemoveCallBack.
Key Based Dependency : Key-based dependency invalidates a particular cache item when another cache item changes.
It's Uses : This is use full when we have multiple interrelated object are in cache and if one of the object changed we need to updated or expire all of them, Key Based Dependency will be best option.
Time Based Dependency : Time-based dependency causes an item to expire at a defined time. Cache.Insert() method of the Cache class is used to create a time-based dependency. Two Types of Time based Dependency are available.
- Absolute
- Sliding
Sliding: Resets the time for the item in the Cache to expire on each request. This is useful when an item in the cache is to be kept alive so long as requests for that item are coming in from various clients.
With those dependency ASP.NET also support
In addition to the dependencies, ASP.NET allows the following:
Automatic expiration: The cache items that are underused and have no dependencies are automatically expired.
Support for callback: The Cache object can be configured to call a given piece of code that will be executed when an item is removed from the cache. This gives you an opportunity to update the cache. We can use OnRemoveCallback().