Posted on

 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.



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>


Posted on


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 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!”;
lbMessage.text = “Guest,welcome to our website!”;

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



  • Simplicity


  • 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;


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


  • 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

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


  • 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 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;


  • Simple to Implement


  • 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 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-



·   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.


·   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″ />


  • Fastest mode 
  • Simple configuration


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

Events in ASP.NET page life cycle

Posted on Updated on

Events in ASP.NET page life cycle


Events/ Method

Page Initialization


View State Loading

Load View state

Post back data processing

Load post Data

Page loading

Page _ Load

Post back change Notification

Raise Post Data Changed Event

Post back Event Handling

Raise Post Back Event

View state Saving

Save View State

Page Rendering

Page _ Render

Page pre rendering phase

Page_ pre render

Pager unloading

Page unload

Stage 1: page initialization:
• The first stage in the page life cycle is initialization and the associated event is page _ Init that is triggered in the page life cycle.
• It initializes all the controls that are statically declared in the .aspx file with the default values.
• Controls can use the page_ Init event to initialize some of the settings that can be used throughout the lifetime of the incoming web request.
• It also initializes all the server controls of the web page with their default values
• Viewstate information for the page will not be available at stage.
Stage 2: View state loading:
• Next, the load View state method is called. This stage only happens when the page has been posted back.
• Viewstate is a collection of name/ value pairs, where control’s and page itself store information that is persistent among web requests.
• At this stage, the view state data saved from the previous page visit is loaded and recursively populated into the page’s control
• This method restores the view state information of a web page that was last saved using the save view state method.
• By overriding the load view state () method, component developer can understand how view state is restored.
Stage 3: Post back data processing:
Once the Viewstate is restored, control will be update with the client side posted data values. This is done by Load post Data event.
Stage 4 & 5: Page loading & post Back change notification:
And then, at the end of the posted data changes event, controls will be reflected with changes done on the client. At this point, Page Load event and Raise post Data Changed Event are fired.
Stage 6: Post Back event handling:
Key event in the ASP.NET page life cycle is when the server – side code associated with an event is triggered on the client – when the user click on button, the page posts back. Page framework calls the Raise post Back event the loop up for the event handler and runs the associated delegate.
Step 7: page pre rendering phase:
Then, page prepares for rendering due to page-preRender event. In this stage, user does the update operation before the Viewstate is stored & output is rendered.
Step 8: View state saving:
Then the save Viewstate event is called where all the values of the control will be saved to their Viewstate collection. The resultant Viewstate is serialized, hashed, base24 encoded & associated with the_ Viewstate hidden field.
Step 9: Page rendering :
• Next the page_ Render method is called which takes the Html/Writer object so as to collect all HTML text to be generated for the control.
• For each control, the web page calls the render method & caches the HTML output. The rendering mechanism can be altered by overriding this render method.
Step 10: Page unloading:
• This is the final stage of the ASP.NET Page life cycle which calls the page_ unload to do the final cleanup of the page objects or resources.
• This event releases the complex resources such as database connection, files, graphical objects etc,


Posted on

Various types of web resources can be created with ASP.NET application. Few of these web file types are described in the below table:
ASP.NET file types
File Type Description
.asp : located in Application root or a subdirectory. Web Forms lets you to reuse the controls & incorporate
Data into your website.
.asmx : located in Application root or a subdirectory Web services are ASP.NET Web pages that contain publicly exposed code so that application can interact with them.
• Web services also provide a means to expose .NET functionality on the web via xml and SOAP.
• Web devices are used to create business to business application using a public registry known as UDDI contain registered public Web Services.
.ascx: located in Application root or a subdirectory. User controls are very similar to web pages, except that they must be hosted inside aspx file. User controls allow you to develop an important piece of user interface and reuse it in as many web forms, as you want without repetitive code.
Web.config: Located in Application root directory. Xml based configuration file that includes settings for customizing security, state management, memory management and many more.
Global.asax : located in Application root directory. Global application file defines global variables and reacts to global variables.
.disco or .vsdisco : located in App_ Web references subdirectory Special discovery file used to help clients find web services.
.vbor .cs : located in App_ Code subdirectory and if it is a code behind file for ASP.NET then it is located in the same directory as the web page. Code behind file created in visual basic or c#. they allow you to separate the code from the user interface.
.resx: located in App_ Global Resources or App_ Local Resources subdirectory Resource files may exist if you are using. NET. They are used to store information that you add at design time.
.sln, .suo, . vbproj, . csproj : located in Visual studio project directory. Project files used by .NET to group together the projects and solution (a collection of projects that you are developing and testing together). These files store a list of related files and some options for the IDE. These file are only used during design time and not deployed on a web server. However, even if they are the default, ASP.NET security settings will prevent a user from viewing them.
.skim : located in App_ Themes subdirectory. Skin file containing property settings to apply to web controls for consistent formatting throughout the web application.
.css : located in Application root or a subdirectory, or App_ Themes subdirectory Cascading style sheets used for formatting html elements.
.html, .htm : located in Application root or a subdirectory Static web file written in HTML code.
.master : located in Application root or a subdirectory Master page that defines the layout for other web pages in the application