ASP.NET – UNIT-2

 

SYLLABUS :

UNIT II : Form validation: Client side validation, Server side validation, Validation Controls: Required Field Comparison Range, Calendar Control, Ad rotator Control, Internet Explorer Control. State Management: View State, Control State, Hidden Fields, Cookies, Query Strings, Application State, Session State.  

2.1 SERVER SIDE VALIDATION :          

In Server-side validation, the validation is performed on the server that is the code for validation is executed in the server. In Server Side Validation, the end user clicks the Submit button after filling out the form, and the code for validation is executed in the server. In ASP.NET this form is packaged in a request and sent to the server where the application resides.

Advantages :

Server-side validation means that the validation checks are performed on the server.

Server-side validation is more secure because the code is executed in the server.

It is more secure because these checks cannot be easily bypassed.

The form data values are checked using code written using C# or VB and the code is executed on the server.

Disdvantages :     Although it is more secure, server-side validation can be slow. It is sluggish simply because the page has to be posted to a remote location(server)  and checked.

 

2.2 CLIENT SIDE VALIDATION:

In Client side validation, the validation is done in the Client. It is possible to supply a script (usually in the form of JavaScript/VBScript) in the page that is posted to the end user’s browser to perform validations on the data entered in the form before the form is posted back to the originating server.

Advantages :

·       Client-side validation is quick and responsive for the end user. If something is wrong with the form, using client-side validation ensures that the end user knows immediately.

·       Client-side validation also pushes the processing power required of validation to the client meaning that it reduces the processing time.

Disadvantages :

·       Client-side validation is the more insecure form of validation. When a page is generated in an end user’s browser, this end user can look at the code of the page easily.  In addition to seeing the HTML code hackers can see the JavaScript that is associated with the page.

·       When clients have simply disabled the client-scripting capabilities in their browsers, validations becomes useless.

The best approach is always to perform client-side validation first and then, after the form passes and is posted to the server, to perform the validation checks again using server-side validation This approach provides the best of both worlds. It is secure because hackers can’t simply bypass the validation. They may bypass the client-side validation, but they quickly find that their form data is checked once again on the server after it is posted. This validation technique is also highly effective—giving both the quickness and snappiness of client-side validation.

 

2.3 ASP.NET - Validation Controls

ASP.Net validation controls validate the user input data to ensure that useless, unauthenticated or contradictory data don’t get stored. Validation controls are used to:

·       To validate user input data.

·       Data format, data type and data range is used for validation.

ASP.Net provides the following validation controls:

1.     RequiredFieldValidator      : Ensures that the user does not skip a form entry field.

2.     CompareValidator               : Compares the value of input control to the value of another input control or to a fixed value using a comparison operator (equals, greater than, less than, and so on).

3.     RangeValidator : Checks that the user enters a value that falls between a range of values.

4.     RegularExpressionValidator : Ensures that the value of an input control matches a specified pattern.

5.     CustomValidator : Checks the user’s entry using custom-coded validation logic.

6.     ValidationSummary : Displays summary of all validation errors from the validators in one specific spot on the page.

2.3.1 The BaseValidator Class:

The validation control classes inherit from the BaseValidator class and inherit its properties and methods. Therefore, it would help to take a look at the properties and the methods of this base class, which are common for all the validation controls:

Members

Description

ControlToValidate

Indicates the input control to validate.

Display

Indicates how the error message is shown.

EnableClientScript

Indicates whether client side validation will take.

Enabled

Enables or disables the validator.

ErrorMessage

Error string.

Text

Error text to be shown if validation fails.

IsValid

Indicates whether the value of the control is valid.

SetFocusOnError

It indicates whether in case of an invalid control, the focus should switch to the related input control.

 

 

2.3.2 The RequiredFieldValidator:

The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a text box to force input into the text box.

Syntax for the RequiredFieldValidator  control:

<asp:RequiredFieldValidator ID="rfvcandidate"
             runat="server" ControlToValidate ="ddlcandidate"
             ErrorMessage="Please choose a candidate"
             InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>

2.3.3 The RangeValidator:

The syntax for the RangeValidator control:

<asp:RangeValidator ID="rvclass" 
       runat="server" 
       ControlToValidate="txtclass" 
       ErrorMessage="Enter your class (6 - 12)" 
       MaximumValue="12" 
       MinimumValue="6" Type="Integer">
</asp:RangeValidator>

 

The RangeValidator control verifies that the input value falls within a predetermined range. It has three specific properties:

Properties

Description

Type

it defines the type of the data; the available values are: Currency, Date, Double, Integer and String

MinimumValue

it specifies the minimum value of the range

MaximumValue

it specifies the maximum value of the range

 

2.3.4 The CompareValidator:

The CompareValidator control compares a value in one control with a fixed value, or, a value in another control.

The basic syntax for the CompareValidator control:

<asp:CompareValidator ID="CompareValidator1" 
        runat="server" 
        ErrorMessage="CompareValidator">
</asp:CompareValidator>

 

 

 

CompareValidator has the following specific properties:

Properties

Description

Type

it specifies the data type

ControlToCompare

it specifies the value of the input control to compare with

ValueToCompare

it specifies the constant value to compare with

Operator

it specifies the comparison operator, the available values are: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual and DataTypeCheck

 

2.3.5 The RegularExpressionValidator

The RegularExpressionValidator allows validating the input text by matching against a pattern against a regular expression. The regular expression is set in the ValidationExpression property.

The following table summarizes the commonly used syntax constructs for regular expressions:

Character Escapes

Description

\b

Matches a backspace

\t

Matches a tab

\r

Matches a carriage return

\v

Matches a vertical tab

\f

Matches a form feed

\n

Matches a new line

\

Escape character

Apart from single character match, a class of characters could be specified that can be matched, called the metacharacters.

Metacharacters

Description

.

Matches any character except \n

[abcd]

Matches any character in the set

[^abcd]

Excludes any character in the set

[2-7a-mA-M]

Matches any character specified in the range

\w

Matches any alphanumeric character and underscore

\W

Matches any non-word character

\s

Matches whitespace characters like, space, tab, new line etc.

\S

Matches any non-whitespace character

\d

Matches any decimal character

\D

Matches any non-decimal character

Quantifiers could be added to specify number of times a character could appear

Quantifier

Description

*

Zero or more matches

+

One or more matches

?

Zero or one matches

{N}

N matches

{N,}

N or more matches

{N,M}

Between N and M matches

 

The syntax for the RegularExpressionValidator  control:

<asp:RegularExpressionValidator ID="string"
        runat="server"
        ErrorMessage="string"
        ValidationExpression="string"
        ValidationGroup="string">
</asp:RegularExpressionValidator>

2.3.6 The CustomValidator:

The CustomValidator control allows writing application specific custom validation routines for both the client side and the server side validation.

The client side validation is accomplished through the ClientValidationFunction property. The client side validation routine should be written in a scripting language, like JavaScript or VBScript, which the browser can understand.

The server side validation routine must be called from the control’s ServerValidate event handler. The server side validation routine should be written in any .Net language, like C# or VB.Net.

 

The basic syntax for the control

<asp:CustomValidator ID="CustomValidator1"   runat="server" 
       ClientValidationFunction=.cvf_func.
       ErrorMessage="CustomValidator">
</asp:CustomValidator>

 

2.3.7 The ValidationSummary Control

The ValidationSummary control does not perform any validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls that failed validation.

The following two mutually inclusive properties list out the error message:

·        ShowSummary: shows the error messages in specified format.

·        ShowMessageBox: shows the error messages in a separate window.

·         

The syntax for the control:

<asp:ValidationSummary ID="ValidationSummary1" 
       runat="server" 
       DisplayMode = "BulletList" 
       ShowSummary = "true"
       HeaderText="Errors:" />

 


2.4 CALENDAR CONTROL

 

The calendar control is a functionally rich web control, which provides the following capabilities:

 

The basic syntax of a calendar control is:

<asp:Calender ID = "Calendar1" runat = "server">

</asp:Calender>

 

Notable properties of the Calendar control are:

Caption                       Gets or sets the caption for the calendar control.

DayHeaderStyle        Gets the style properties for the section that displays the day of the week.

DayNameFormat       Gets or sets format of days of the week.

DayStyle                     Gets the style properties for the days in the displayed month.

FirstDayOfWeek       Gets or sets the day of week to display in the first column.

NextMonthText         Gets or sets text for next month navigation control. Default value is >.

NextPrevFormat        Gets or sets the format of the next/ previous month navigation control.

PrevMonthText         Gets or sets text for previous month navigation control. Default value <.

SelectedDate             Gets or sets the selected date.

ShowGridLines          Gets or sets the value indicating whether the gridlines would be shown.

ShowTitle                   Gets or sets a value indicating whether the title section is displayed.

WeekendDayStyle     Gets the style properties for the weekend dates on the Calendar control.

 

The Calendar control has the following three most important events :

SelectionChanged      It is raised when a day, a week or an entire month is selected.

DayRender     It is raised when each data cell of the calendar control is rendered.

VisibleMonthChanged           It is raised when user changes a month.

 

The syntax for selecting days:

<asp:Calender ID = "Calendar1" runat = "server" SelectionMode="DayWeekMonth">

</asp:Calender>

Calendar2

 

 

 

 

 

 

 

2.5 ADROTATOR CONTROL

The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML schedule file. The external XML file is called the advertisement file.

Syntax of AdRotator is:

<asp:AdRotator  runat = "server" AdvertisementFile = "adfile.xml"  Target =  "_blank" />

Properties of the AdRotator :

AdvertisementFile

The path to the advertisement file.

AlternateTextField

The element name of the field where alternate text is provided. The default value is AlternateText.

DataSource   

Control from where it would retrieve data.

Font

Specifies font properties associated with advertisement banner control.

ImageUrlField

Location where the URL for the image is provided.

NavigateUrlField

Target Place to be Navigated

Target

The browser window or frame that displays the content of the page linked.

 

Example Tag for AdRotator :

<form id="form1" runat="server">

   <div>

      <asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile  ="~/advt.xml" />

   </div>

</form>

 

Advertisement File : The advertisement file is an XML file, which contains the information about the advertisements to be displayed.

The Advertisement File(XML) consists of the following Elements :

Advertisements            Encloses the advertisement file.

ImageUrl         The path of image that will be displayed.

NavigateUrl     The link that will be followed when the user clicks the ad.

AlternateText  The text that will be displayed instead of the picture if it cannot be displayed.

Keyword          Keyword identifying a group of advertisements. This is used for filtering.

Impressions     The number indicating how often an advertisement will appear.

Height              Height of the image to be displayed.

Width              Width of the image to be displayed.

Example Advertisement File

<?xml version="1.0" encoding="utf-8" ?>

<Advertisements>

  <Ad>

    <ImageUrl>~/IMG/1.jpg</ImageUrl>

    <NavigateUrl>~/1.aspx</NavigateUrl>

    <AlternateText>First Picture</AlternateText>

  </Ad>

  <Ad>

    <ImageUrl>~/IMG/2.jpg</ImageUrl>

    <NavigateUrl>~/2.aspx</NavigateUrl>

    <AlternateText>Second Picture</AlternateText>

  </Ad>

</Advertisements>


2.6 STATE MANAGEMENT

State management is a important part of any application. ASP.NET manages four types of states:

 

2.6.1 APPLICATION STATE

The ASP.NET application is the collection of all web pages, code and other files within a single virtual directory on a web server. When information is stored in application state, it is available to all the users. ASP.NET creates an application state object for each application from the HTTPApplicationState class and stores this object in server memory. This object is represented by class file global.asax.

Application State is mostly used to store hit counters and other statistical data and to keep the track of users visiting the site.

The HttpApplicationState class has the following properties:

Item(name)    The value of the application state item with the specified name. This is the default property of the HttpApplicationState class.

Count             The number of items in the application state collection.

 

The HttpApplicationState class has the following methods:

Add(name, value)       Adds an item to the application state collection.

Clear                           Removes all the items from the application state collection.

Remove(name)          Removes the specified item from the application state collection.

Lock()                         Locks the application state, so only the current user can access it. Unlock()                  Unlocks the application state collection so all the users can access it.

 

Application state data is generally maintained by writing handlers for the events:


·     Application_Start      

·     Application_End

·     Application_Error

·     Session_Start

·     Session_End


 

2.6.2 SESSION STATE

Session state is a period of time to visit a website for a particular user. Session can store the client data on a server. Session is a best state management features to store the client data on server separately for each user. Session value can be accessible from all pages from website. It is possible to store some information in session in one page and can access same information on rest of all page.

·       Session stores data on whole website pages

·       Session is a server side state management technique

·       Data stored in the SesionState will be cleared when the session expired after a time limit.

·       SesionState is used to save the user specific data like UserID, User Role, etc.

·       Syntax of session

Session[“session_name”] = “session value”;

·       Session.Abandon() method used to destroy the current session and clears occupied memory location.

·       Session.Clear()- used to just clears all values of session without destroying it.

2.6.3 VIEWSTATE

·       ViewState stores data on single page

·       ViewState is client side state management technique, the data is store in the page.

·       Data stored in the ViewState will send back to the server when postback action is performed.

·       ViewState is used primarily by Server controls to retain state only on pages that post data back to themselves. For Saving pagelevel ViewState can be used.

·       Store the value in viewstate

ViewState[“name”]=”College Results”;

·       Retrieve information from viewstate

string value=ViewState[“name”].ToString();

2.6.4 CONTROL STATE

Inorder to make a control to work properly, control-state data is stored. For example, if  a custom control is written that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. The ViewStateproperty can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking the control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.

The ControlState property allows to persist property information that is specific to a control and cannot be turned off like the ViewState property.

 

2.7 COOKIES

A cookie is a small amount of data that server creates on the client. When a web server creates a cookie, an additional HTTP header is sent to the browser when a page is served to the browser.

 

There are two types of cookies:

Session cookies A session cookie exists only in memory. If a user closes the web browser, the session cookie delete permanently.

Persistent cookies. A persistent cookie is available for months or even years. When a persistent cookie is created, the cookie is stored permanently by the user’s browser on the user’s computer.

 

Set-Cookie: message=Hello. After a cookie has been created on a browser, whenever the browser requests a page from the same application in the future, the browser sends a header that looks like this:

Cookie: message=Hello

Cookie is little bit of text information. Only string values can be stored when using a cookie.

 

Creating cookie:

protected void btnAdd_Click(object sender, EventArgs e)

{    Response.Cookies[“message”].Value = txtMsgCookie.Text;

}

// Here txtMsgCookie is the ID of TextBox.

 

Cookie names are case sensitive. Cookie named message is different from setting a cookie named Message.

The above example creates a session cookie. The cookie disappears when the web browser is closed. For creating a persistent cookie, it is needed to specify an expiration date for the cookie.

Response.Cookies[“message”].Expires = DateTime.Now.AddYears(1);

 

Reading Cookies

void Page_Load()

{

    if (Request.Cookies[“message”] != null)

    lblCookieValue.Text = Request.Cookies[“message”].Value;

}

// Here lblCookieValue is the ID of Label Control.

2.8 QUERY STRINGS

A query string is information that is appended to the end of a page URL. Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed.

A typical query string might look like the following example:

http://www.univresults.com/listwidgets.aspx?category=stud&rollno=17CS10

In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price."