Month: November 2013

Validation Groups:

Posted on

Validation Groups:

Complex pages have different groups of information provided in different panels. In such a situation a need for performing validation separately for separate group, might arise. This kind of situation is handled using validation groups. To create a validation group, you should put the input controls and the validation controls into the same logical group by setting their ValidationGroup property.

Example:
The following example describes a form to be filled up by all the students of a school, divided into four houses, for electing the school president. We will be using the validation controls to validate the user input.

The content file code:

Candidate:

Please Choose a Candidate
M H Kabir
Steve Taylor
John Abraham
Venus Williams

House:

Red
Blue
Yellow
Green

Class:
Email:

The code behind the submit button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{ lblmsg.Text = “Thank You”; }
else
{ lblmsg.Text = “Fill up all the fields”; }}

Advertisements

The Validation Control Classes

Posted on

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.
ValidationGroup The logical group of multiple validators, where this control belongs.
Validate() This method revalidates the control and updates the IsValid property.

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.
The syntax for the control:

The 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

The syntax for the control:

The CompareValidator:
The CompareValidator control compares a value in one control with a fixed value, or, a value in another control.
It 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

The basic syntax for the control:

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 meta characters.
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 control:

VALIDATION CONTROL

Posted on

VALIDATION CONTROL: INTRODUCTION
 ASP.NET provides six validations controls that can be used to validate the data on a web form and validate the user input data to ensure that useless, unauthenticated or contradictory data does not get stored.
 This validation controls can be used with HTML and Web Server controls. Six validation controls are available with ASP.NET as of now, they are as follows –
The RequiredFieldValidator Control – Ensures that the user does not skip a mandatory entry field.
The CompareValidator Control – Compares one controls value with another controls value, constants and data type using a comparison operator (equals, greater than, less than, and so on).
The RangeValidator Control – Checks the user’s input is in a given range (eg: numbers or characters).
The RegularExpressionValidator Control – Checks that the user’s entry matches a pattern defined by a regular expression.
The CustomValidator Control – Checks the user’s entry using custom-coded validation logic.
The ValidationSummary Control – Displays a summary of all validation errors inline on a web page, in a message box, or both.

CSS

Posted on

¾    CSS stands for Cascading Style Sheets

¾    Styles define how to display HTML elements

¾    Styles were added to HTML 4.0 to solve a problem

¾    External Style Sheets can save a lot of work

¾    External Style Sheets are stored in CSS files

 

 

Inline Styles

An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method sparingly!

To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left margin of a paragraph:

<p style=”color:sienna;margin-left:20px”>This is a paragraph.</p>

 

Internal or Embedded Style Sheet

An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section of an HTML page, by using the <style> tag, like this:

<head> <style> hr {color:sienna;} p {margin-left:20px;} body {background-image:url(“images/back40.gif”);} </style> </head>

GLOBAL. ASAX FILES

Posted on

GLOBAL. ASAX FILES

Global.asax is a class file that is used to specify the session and application event handlers for a web application. The Global.asax file resides in the root directory of an asp.net web application and is also called the ASP.NET application file. This file contains the code that is executed when certain events, such as start of an application or error in an application, are raised by an ASP.NET web application.

Events and states, such as session state and application state, which are specified in the Global.asax file, are applied to all the resources of the web application. For example, if an application state variable is defined in the Global.asax file, then all the .aspx files with the root directory can access the variable.

The code in the Global.asax file is written in the same way as in web forms; the only difference is that the code written in the Global.asax file does not contain HTML or ASP.NET tags. Instead, the code in this file contains methods with predefined names.

¾    The Global.asax file added to the ASP.NET web application contains empty event handlers for the commonly used application events, such as the start and end of an application. The code for the event handlers is inserted in the appropriate method of the Global.asax file. The name of the method for which an event hadler is created should be similar to the name of the event occurring in the web application. For example, the Application_start() method is called when the Application_Start event occurs in the ASP.NET web application.

The Global.asax file can be used either for initializing the application and session state variables or clearing out the memory by destroying all such variables. The Global.asax file consists of following events that can be handled using it:

  • Application_Init: Fires when the application initializes for the first time.
  • Application_Start: Fires the first time an application starts.
  • Session_Start: Fires the first time when a user’s session is started.
  • Application_BeginRequest: Fires each time a new request comes in.
  • Application_EndRequest: Fires when the request ends.
  • Application_AuthenticateRequest: Indicates that a request is ready to be authenticated.
  • Application_Error: Fires when an unhandled error occurs within the application.
  • Session_End: Fires whenever a single user Session ends or times out.
  • Application_End: Fires when the application ends or times out (Typically used for application cleanup logic).

ASP.NET state management

Posted on Updated on

ASP.NET state management

·   Web pages rarely be stand alone. Web applications almost always need to track users who visit multiple pages, whether to provide personalization, store information about a user or to track usage for reporting purposes.

·   State management is the process by which you maintain state and page information over multiple requests for the same or different pages. 

·   Whenever any request is sent, the interaction between the client and server can be either stateless or stateful.

Types of State Management 
1) Client – Side State Management –view state, cookies, hidden fields, query string

2)  Server – Side State Management –session state, application state

 

Client side State management Options:
i) Cookie: A cookie is a small piece of text stored on user’s computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.
Let’s see an example which makes use of cookies to customize web page.
if (Request.Cookies[“UserId”] != null)
lbMessage.text = “Dear” + Request.Cookies[“UserId”].Value + “, Welcome to our website!”;
else
lbMessage.text = “Guest,welcome to our website!”;

If you want to store client’s information use the below code

Response.Cookies[“UserId”].Value=username;

Advantages:

  • Simplicity

Disadvantages:

  • Cookies can be disabled on user browsers
  • Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
  • Inappropriate for sensitive data

 

ii) Hidden fields:Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It’s just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax

protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

 //to assign a value to Hidden field

Hidden1.Value=”Create hidden fields”;

//to retrieve a value

string str=Hidden1.Value;

Advantages:

  • Simple to implement for a page specific data
  • Can store small amount of data so they take less size.

Disadvantages:

  • Inappropriate for sensitive data
  • Hidden field values can be intercepted(clearly visible) when passed over a network

iii)View State:View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don’t need state. (Data grid usually doesn’t need to maintain state). You can also disable View State for the entire page by addingEnableViewState=false to @page directive. View state data is encoded as binary Base64 – encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.

// Add item to ViewState

ViewState[“myviewstate”]  = myValue;

 //Reading items from ViewState
Response.Write(ViewState[“myviewstate”]);
Advantages:

  • Simple for page level data
  • Encrypted 
  • Can be set at the control level

Disadvantages:

  • Overhead in encoding View State values
  • Makes a page heavy

iv)Query strings:Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.Let’s assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for, productdetails.aspx?productid=4).

When product details page is being requested, the product information can be obtained by using the following codes:

string productid;
productid=Request.Params[“productid”];            

Advantages:

  • Simple to Implement

Disadvantages:

  • Human Readable 
  • Client browser limit on URL length
  • Cross paging functionality makes it redundant 
  • Easily modified by end user

 

Server Side State management:

As name implies, state information will be maintained on the server.

i)Application: Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted. 

Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:
a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.
b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.
c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging. 

 

·   Variables and objects added to the application state are global to an Asp.net application. For example, we can create a variable called appvar with the value Hello and store it in the application state. To create  appvar, we need to use the following statement:

Application [“appvar”]=”Hello”;

·   After the application in which you declared app var is executed, any page contained in the application can retrieve the value of the appvar. To read the value of the MyVariable, we need to use the following-

Response.Write(Application[“appvar”]);

Advantages:

·   Applications state is easy to use and is consistent with other .net framework classes.

·   Storing information in application state involves maintaining only a single copy of the information.

Disadvantages:

·   The data stored in application state is lost when the web server containing the application state fails due to server crash, upgrade or shut down.

·   It requires server memory and can affect the performance of the server and the scalability of the web application.

 

ii) Session: Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session’s data on web server in different ways. Session state can be configured using the <session State> section in the application’s web.config file. 

Configuration information:
<sessionState mode = <“inproc” | “sqlserver” | “stateserver”>
cookieless = <“true” | “false”>
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>      

Mode:This setting supports three options. They are InProc, SQLServer, and State Server
Cookie less:This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.

Timeout:This indicates the Session timeout vale in minutes.  This is the duration for which a user’s session is active.  Note that the session timeout is a sliding value; Default session timeout value is 20 minutes
SqlConnectionString:This identifies the database connection string that names the database used for mode SQLServer.
Server:In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
Port:This identifies the port number that corresponds to the server setting for mode State Server.  Note that a port is an unsigned integer that uniquely identifies a process running over a network.You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.

Configuration information:

<sessionState mode=”Inproc”

 sqlConnectionString=”data source=server;user id=freelance;password=freelance”

 cookieless=”false” timeout=”20″ />

Advantages:

  • Fastest mode 
  • Simple configuration

Disadvantages:

  • Session data will be lost if the worker process or application domain recycles
  • Not ideal for web gardens and web farms