Sunday, January 25, 2009

Client-Side vs. Server-Side Validation

If the browser supports DHTML, ASP.NET validation controls can perform validation by using client script . The advantage of using client script is that a feedback can be provided without a response from the server . The validation controls automatically detect whether the browser supports DHTML and perform the validation accordingly.

The error display mechanism for client side is same as server-side validation. Validation is performed on the server even if it was already performed on the client. This enables you to determine the validation status in the server code and ensure security against users bypassing client-side validation.

If validation is performed on the client, validation controls include some additional features:
  • If you are summarizing validation error messages, you can display them in a message box that appears when the user submits the page.
  • Validation controls present the same object model on the client as on the server. For example, you can test validation by reading a validation control's IsValid property the same way, on both the client and the server. However, there are differences in the validation information exposed at the page level. On the server, the page supports properties; on the client, it contains global variables.
  1. Client : Page_IsValid
    Server : IsValid
  2. Client : Page_Validators (array). Contains references to all validation controls on te page. Server: Validators (collection). Contains references to all validation controls.
  3. Client : Page_ValidationActive. A Boolean value that indicates whether validation should take place. Set this variable to false to turn off client-side validation programmatically.
    Server : Not applicable


Note : If client-side validation is enabled, the page includes references to script libraries that are used to perform the client-side validation.When you use a RegularExpressionValidator control, the expressions can be checked on the client if an ECMAScript-compatible language, such as Microsoft JScript is available. Client-side regular expressions differ in small details from the regular expression checking done on the server by using the Regex class.The page includes a client-side method to intercept and handle the Click event before the page is submitted.

Source of Reference : MSDN

Validation controls

Validation controls contain 5 controls that make comparisons and 1 control that summarizes any errors that appear. All validation controls need to be placed within a Form or a Panel control, or inside a control's template on a mobile Web page. A validation control can be dragged onto a mobile user control page.

  • RequiredFieldValidator : Used to validate user entered data into a SelectionList or TextBox control. With a SelectionList control, the user needs to select an item in the list. With a TextBox control, the user needs to enter a value.
  • CompareValidator: Used to compare the data value entered by the user to a value in another control. Set the ControlToCompare property to the string in the id property of the SelectionList or TextBox control that contains the comparison value and the ValueToCompare property to the comparison value .
  • RangeValidator : Used to validate whether user input falls within a specified range. Use the MinimumValue and MaximumValue properties.
  • RegularExpressionValidator : to test whether the user input in a TextBox or SelectionList control matches a regular expression. The regular expression pattern is specified in its ValidationExpression property. You can specify regular expressions or select from a list of predefined expressions.
  • CustomValidator : Use this to create a control that performs customized validation. It also validates input from the TextBox or SelectionList control. Set its ControlToValidate property to the ID of the control, to validate. When a form that contains a CustomValidator control is posted to the server, the CustomValidator control raises a ServerValidate event. In this event, you can write the custom validation code you want. Eventually, you can set the IsValid property of the validation eventArgs to true or false, depending on the outcome of the validation.
  • ValidationSummary: Use to to present the user with a list of validation errors that occurred when a form was posted on the server. The mobile version of the ValidationSummary control displays a back-link for the user to return to the form and correct the data entered.

Each validation control can display an error message at the position of the validation control on the form. Validation errors can be collected in a validation summary control and can be displayed at a single place, such as at the top of the page.

Set the Display property to None, Static , or Dynamic , to check whether the validation control displays error messages. You can select Dynamic to display the results of the validation, and None, if you do not want to display the results. In the current version of the ASP.NET mobile controls, Dynamic and Static have similar meaning.

You can use the mobile version of the ValidationSummary control to display a list of validation errors that occurred when a form was submitted. This control lists all the error messages generated by the other validation controls on the form. The ValidationSummary control obtains the error message strings from the ErrorMessage properties of the validation controls.

Saturday, January 24, 2009

Server Controls

On receiving a request, ASP.Net examines the request, by using a User Agent retrieved from the header of HTTP Request, to find out the brower type and version for outputting the HTML specific to that browser.

When you are using server controls, you do not need to specify the HTML that is to be the output from the server-side code. You can specify the functionality you want to see in the browser, and ASP.NET decides the output to be sent to the browser.


Label

TextBox : It can be mapped to the following HTML elements used in your forms:

Standard TextBox
Multiline TextBox
Password Field

Button: Use the button to submit forms. You can also manage the items on your forms by using the Button control’s OnClick event.

DropDownList: With this, you can place an HTML select box on your Web page and set it against the select box. You can use this control when you want the user to select a single item from a list of multiple items. The select box generated by the DropDownList control displays a single item and allows the user to select one item from the list.

ListBox: displays a collection of items. The ListBox control displays more of the collection to the user and allows the user to make multiple selections from the collection.

CheckBox or CheckBoxList: By using check boxes on a Web Form, users can either select from a collection of items or specify the value of an item to be yes/no, on/off, or true/false. You can use multiple CheckBox controls on your ASP.NET pages, treating each check box as its own element with associated events. The CheckBoxList control allows you to put multiple check boxes on the form and create specific events for the entire group.

RadioButton or RadioButtonList: Radio buttons are form elements that require at least two options. The RadioButtonList server control allows you to display a collection of radio buttons on a Web page. The RadioButtonList control allows you to iterate through to see what the user selected, to make counts, or to perform other actions.

Source of Reference : MSDN


Tuesday, January 20, 2009

HTTP Handler in detail

The process that runs in response to a request made to an ASP.NET Web application is the HTTP handler ( or endpoint). When users request an .aspx, .asmx, or .ashx file, the page processes the request through the page handler.

Uses:

  • It can be created to render custom utput to the browser.
  • It add new functionalities to the Web server.
  • It can be created to generate RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site in a format that ends in .rss, the Web application sends the request to the HTTP handler to process the request.
  • Image server. HTTP handlers can be used to resize the images in a Web application. When you want a Web application to resize the images, you can write a custom handler to resize the images, and then send them to the user as the handler's response.

ASP.NET maps HTTP requests to HTTP handlers, based on a file name extension. Each HTTP handler can process individual HTTP URLs or groups of URL extensions in an application. ASP.NET includes the following built-in HTTP handlers:
ASP.NET page handler (*.aspx) : default HTTP handler for all ASP.NET pages.
Web service handler (*.asmx): default HTTP handler for Web service pages created as .asmx files in ASP.NET.
Generic Web handler (*.ashx): default HTTP handler for all Web handlers that do not have a user interface (UI) and that include the @WebHandler directive.
Trace handler (trace.axd): displays current page trace information.

A Http Handler for performing synchronous processing of requests:

public class HelloWorldHandler : IHttpHandler
{
public HelloWorldHandler()
{
}

//The ProcessRequest method is responsible for processing individual
//HTTP requests. You can write the code that produces the
//output for the handler by using the ProcessRequest method.
public void ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
// This handler is called whenever a file ending in .sample is
//requested. A file with that extension does not need to exist.
Response.Write(".HTML.");
Response.Write(".body.");
Response.Write(" .h1.Hello from a synchronous custom HTTP handler./h1");
Response.Write("./body.");
Response.Write("./html.");
}

// This property specifies whether the IHttpHandlerFactory object can put the handler in a pool and reuse it. If the handler cannot be pooled, the factory should create a new instance of the handler

public bool IsReusable
{
// To enable pooling, return true here. This keeps the handler in memory.
get { return false; }
}
}


To register the handler :

.configuration.
.system.web.
.httpHandlers.
.add verb="*" path="*.sample" type="HelloWorldHandler"/.
.httpHandlers.
.system.web.
.configuration.

Note : "*" means all of the http verbs, eg. GET,POST

To register the handler in IIS 7.0 running in Integrated mode

.configuration.
.system.webServer.
.handlers.
.add verb="*" path="*.sample" name="HelloWorldHandler" type="HelloWorldHandler".
./handlers.
./system.webServer.
./configuration.

Note : When a HTTP Handler class is created, the handler can respond to any file name extension that is not already mapped in IIS and in ASP.NET. For ASP.NET to know which handler to use for your custom file name extension, you must map the extension in IIS to ASP.NET. Then, in the application, you must map the extension to the custom handler.
By default, ASP.NET maps the file name extension, .ashx, to an HTTP handler. If you create an HTTP handler class that has the file name extension, .ashx, the handler is automatically registered with IIS and ASP.NET. The advantage of not using the .ashx file name extension is that the handler is then reusable for different extension mappings. If you want to create a custom file name extension for a handler, you must explicitly register the extension with IIS and ASP.NET. After you create the custom HTTP handler class, you must register it in the application's web.config file

source of reference : MSDN

Thursday, January 15, 2009

HTTP Modules in detail

HTTP modules, part of ASP.Net request pipeline, are called on every request made to an application and can access life cycle events through out the request. They are like ISAPI filters as they are invoked for all requests. Once the request passes through all of the HTTP modules, it is eventually served by an HTTP handler. The HTTP handler performs some processing on it, and the result again passes through the HTTP modules in the pipeline.

Features like form authentication, caching, sessionstate, client script services are implemented using modules. As part of a request, the module is called to perform tasks that a single page request cannot perform. They use application events, raise events that can be handled in the Global.asax file.

To receive notifications from the request pipeline, you need to register HTTP modules in the application's web.config file. When ASP.NET creates an instance of the HttpApplication class that represents your application, instances of any modules that have been registered are created.

When you create a module, its Init method is called, and then the module initializes itself.
In the module's Init method, you can subscribe to various application events such as BeginRequest or EndRequest by binding the events to methods in the module. When application events are raised, you need to call the appropriate method in your module to perform the required logic, such as checking authentication or logging request information. During event handling, the module can access the Context property of the current request to redirect the request to an alternative page, modify the request, or perform any other request manipulation. Otherwise, when the module's event handler has finished running, ASP.NET calls the next process in the pipeline.


public class MyFirstModule : IHttpModule
{
public MyFirstModule ()
{
}

public String ModuleName
{
get { return "MyModule"; }
}
}

To register in web.config

.configuration.
.system.web.
.httpModules.
.add name="MyFirstModule" type="MyFirstModule"/.
.httpModules.
./system.web.
./configuration.

Note: Replace the "." with opening and closing tags.



To write a handler for the Init method.
// In the Init function, register for HttpApplication events by adding
your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
application.EndRequest += (new EventHandler(this.Application_EndRequest));
}

Note : During the processing of an http request, only one HTTP handler will be called, whereas more than one HTTP modules can be called
Source of Reference: MSDN

Tuesday, January 13, 2009

Intrinsic Server Objects

Response - An instance of HttpResponse class, this object provides access to the output stream for the current page. Used for writing text into the page or for creating cookies.

Request - An instance of HttpRequest, this object provides access to the current page request, including request headers, cookies, client certificates, and a query string.

Context - An instance of HttpContext, this object provides access to the entire current context, which includes the Request object. You can use the HttpContext class to share information between Web pages.

Server- An instance of HttpServerUtility, it provides utility methods that you can use to transfer control between pages, get information about the most recent error, and encode and decode HTML text.

Application - An instance of HttpApplicationState , it provides access to application-wide methods and events for all sessions.


Soure of Reference- MSDN

Processing of PageRequests

When the first request comes, the top-level items even the application code ,if required, residing in App_code folder is compiled and an instance of Application Manager ,i.e Application domain is created . By virtue of this application domain , the isolation is provided between global variables of different applications. Asp.Net also creates an instance of Hosting environment class in the application domain. After this the application objects such as HttpContext, HttpRequest, and HttpResponse are created and initialized.

The HttpContext class contains objects that are particular to the current application request,i.e. HttpRequest and HttpResponse.

The HttpRequest object contains information about the current request, i.e. cookies and browser information.

The HttpResponse object contains the response that is sent to the client, which includes all the rendered output and cookies.

The request is then processed by the HttpApplication pipeline and after the processing the ASP.NET page life cycle is run.
 
Google