You are on page 1of 11

Explain the page life cycle in ASP.NET 2.

ASP

.NET 2.0 Page Life Cycle - The lifetime of an ASP.NET page is filled with events. A
.NET technical interview might begin with this question. A series of processing steps
takes place during this page life cycle. Following tasks are performed:

* Initialization
* Instantiation of controls
* Restoration & Maintainance of State
* Running Event Handlers
* Rendering of data to the browser

The life cycle may be broken down into Stages and Events. The stages reflect the broad
spectrum of tasks performed. The following stages take place

1) Page Request - This is the first stage, before the page life cycle starts. Whenever a
page is requested, ASP.NET detects whether the page is to be requested, parsed and
compiled or whether the page can be cached from the system
.
2) Start - In this stage, properties such as Request and Response are set. Its also
determined at this stage whether the request is a new request or old, and thus it sets the
IsPostBack property in the Start stage of the page life cycle.
3) Page Initialization - Each control of the page is assigned a unique identification ID. If
there are themes, they are applied. Note that during the Page Initialization stage, neither
postback data is loaded, nor any viewstate data is retrieved.
4) Load - If current request is a postback, then control values are retrieved from their
viewstate.
5) Validation - The validate method of the validation controls is invoked. This sets the
IsValid property of the validation control.
6) PostBack Event Handling - Event handlers are invoked, in case the request is a
postback.
7) Rendering - Viewstate for the page is saved. Then render method for each control is
called. A textwriter writes the output of the rendering stage to the output stream of the
page's Response property.
8) Unload - This is the last stage in the page life cycle stages. It is invoked when the page
is completely rendered. Page properties like Respone and Request are unloaded.

Note that each stage has its own events within it. These events may be used by
developers to handle their code. Listed below are page events that are used more
frequently.

PreInit - Checks the IsPostBack property. To create or recreate dynamic controls. To set
master pages dynamically. Gets and Sets profile propety values.
Init - Raised after all controls are initialized, and skin properties are set.
InitComplete - This event may be used, when we need to be sure that all initialization
tasks are complete.
PreLoad - If processing on a control or a page is required before the Load event.
Load - invokes the OnLoad event on the page. The same is done for each child control on
the page. May set properties of controls, create database connections.
Control Events - These are the control specific events, such as button clicks, listbox item
selects etc.
LoadComplete - To execute tasks that require that the complete page has been loaded.
PreRender - Some methods are called before the PreRenderEvent takes place, like
EnsureChildControls, data bound controls that have a dataSourceId set also call the
DataBind method.
Each control of the page has a PreRender event. Developers may use the prerender event
to make final changes to the controls before it is rendered to the page.
SaveStateComplete - ViewState is saved before this event occurs. However, if any
changes to the viewstate of a control is made, then this is the event to be used. It cannot
be used to make changes to other properties of a control.
Render - This is a stage, not an event. The page object invokes this stage on each control
of the page. This actually means that the ASP.NET server control's HTML markup is sent
to the browser.
Unload - This event occurs for each control. It takes care of cleanup activities like wiping
the database connectivities.

What is the role of the ASP.NET worker process? What is aspnet_wp.exe?

This question is hot in every interview. For faster execution of ASP.NET applications, that
are primarily based to be hosted on IIS servers, the aspnet_wp.exe comes into picture.
This file (aspnet_wp.exe) is actually the ASP.NET worker process. The worker process is
introduced to actually share the load on the IIS, so that application domains and other
services may be maintained by a single worker process.

The aspnet_wp.exe worker process is a part of the Microsoft ASP.NET framework, and it
is responsible for most of the technical processes in the ASP.NET framework. There may
be multiple instances of ASP.NET worker process running on IIS 6 (a process running as
inetinfo.exe), depending on multiple application pools. The worker process handles all
the requests passed to the ASP.NET framework, so we may say that its actually the main
engine that handles all requests pertaining to ASPNET. For example, when a request for
an .aspx page is recieved by the IIS server, the dll called aspnet_isapi.dll passes this
request to the aspnet_wp.exe worker process.

How to redirect a page to another page?

A common question asked in interviews. The Response object has a famous Redirect
method that is used most widely to transfer a web page

visitor from one page to another page.


Syntax of Response.Redirect ...

Response.Redirect("DestinationPage.aspx")

There is another famous method called Transfer method of the Server object.

Syntax of Server.Transfer ...

Server.Transfer("DestinationPage.aspx")

To know more on the difference between Response.Redirect and Server.Transfer, Click


Here

How to pass values between pages?

Every interviewer will expect this from you. There are several methods to pass values
from one page to another page. Described below are few methods to pass values between
pages:

QueryString - The QueryString method of passing values between web pages is one of
the oldest methods of passing values between pages. A variable value is properly encoded
before it is placed on a querystring. This is to make sure that characters that cause
problems (like symbols and spaces) are encoded correctly. See the code below to see how
QueryString functionality works.

//Code in InitialPage.aspx
String sString;
sString = Server.UrlEncode("string in InitialPage.aspx");
Response.Redirect("DestinationPage.aspx?Value=" & sString);

//Code in DestinationPage.aspx reads the QueryString


String sString;
sString = Request.QueryString("Value");
Response.Write("Your name is " & sString);

The data in the DestinationPage.aspx in the URL looks like this...

http://www.dotnetuncle.com/DestinationPage.aspx?Value=dotnetUncle

Context - The context object is used to send values between pages. Its similar to the
session object, the difference being that, the Context object goes out of scope when the
page is sent to a browser

. Example code below shows how to use Context object.


'InitialPage.aspx stores value in context before sending it
Context.Items("MyData") = "dotnetuncle";
Server.Transfer("DestinationPage.aspx");

'DestinationPage.aspx retrieves the value from InitialPage.aspx's context


String sString;
sString = Context.Items("MyDate").ToString;
Response.Write("The data is as follows: " & sString);

Session - The session object is used to persist data across a user session during the user's
visit to a website. It is almost same as the Context object. When we use
Response.Redirect, it causes the Context object to go away, so rather the Session object is
used in such a scenario. Session object uses more of server memory than a context object.
Example code below shows how to use Session object.

'InitialPage.aspx stores value in session before sending it


Session.Items("MyData") = "dotnetuncle";
Response.Redirect("DestinationPage.aspx");

'DestinationPage.aspx retrieves the value from InitialPage.aspx's session


String sString;
sString = Session.Items("MyDate").ToString;
Response.Write("The data is as follows: " & sString);

You may notice above, I have used Response.Redirect with session object, and
server.transfer with a context object.

Application,Cache, Session - objects are used to store global variables. To know more
about them, Click Here

Get Vs Post Method

Get Vs Post Method to send data to the server

Get and Post are methods used to send data to the server:
With the Get method, the browser appends the data onto
the URL. With the Post method, the data is sent
as "standard input."

Use GET:
- during development for debugging purposes (although in ASP.NET it's
also easy to see what has been sent through POST).
- if you want your visitors to be able to bookmark the submitted pages
- if you want to refer to submitted pages using hyperlinks

Use POST:
- for forms with password fields
- for large forms or forms with large text fields

Please note that web forms in ASP.NET use POST by default.

It can be changed into GET, but only for small forms. Web forms can post a lot
of data, especially when ViewState is involved.

If there is master page attached to the aspx page then which page
load event will fire first?

Content page

What is the Default Expiration Period For Session and Cookies?


Session
The default Expiration Period for Session is 20 minutes

Cookies
The default Expiration Period for Cookie is 30 minutes

What is the use of Global.asax File in ASP.NET Application ?


The Global.asax file is an optional file and can be stored
in root directory. This File is in accesible for web-sites.
This Global.asax file contained in HttpApplicationClass.
In Global.asax file we can declare global variables like for
example the variables used in master pages because same
variables can be used for different pages right.It provides
more security than others.
The Global.asax file is used to handle application-level
and session-level events.
we donot worry about configuring Global.asax because it is
itself configured. Accessing the Global.asax file can not be possible.
while one request is in processing it is impossible to
send another request, we can not get response for other
request and even we can not start a new session.
while adding this Global.asax file to our application bydefault it contains five methods,
Those methods are:
1.Application_Start.
2.Application_End.
3.Session_Start.
4.Session_End.
5.Application_Error.

Difference between DropDownList and ListBox in ASP.NET


The basic difference between DropDownList and ListBox in ASP.NET are following

1. Only one items of DropDownList is visible when it renders on the page. More than one
item of the ListBox is visible when it renders on the page.
2. Only one item can be selected in DropDownList. More than one item can be selected
in Listbox provided SelectionMode is Multiple as in the below code snippets.

Both controls are rendered as "<select>" html tag in the HTML.

DROPDOWNLIST
<asp:DropDownList ID="drop1" runat="server">

<asp:ListItem Text="One" Value="1" />

<asp:ListItem Text="Two" Value="2" />

</asp:DropDownList>

LIST BOX
<asp:ListBox ID="list1" runat="server" SelectionMode="Multiple">

<asp:ListItem Text="One" Value="1" />

<asp:ListItem Text="Two" Value="2" />

</asp:ListBox>

What is Authentication and Authorization.


An authentication system is how you identify yourself to the computer. The goal behind
an authentication system is to verify that the user is actually who they say they are.
Once the system knows who the user is through authentication, authorization is how the
system decides what the user can do.
What are different types of directives in .NET?
@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler.
Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>
@Control:Defines control-specific attributes used by the ASP.NET page parser and
compiler. Can be included only in .ascx files. <%@ Control Language="VB"
EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import
directive cannot have more than one namespace attribute. To import multiple
namespaces, use multiple @Import directives. <% @ Import Namespace="System.web"
%>
@Implements: Indicates that the current page or user control implements the specified
.NET framework interface.<%@ Implements
Interface="System.Web.UI.IPostBackEventHandler" %>
@Register: Associates aliases with namespaces and class names for concise notation in
custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator"
Src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all the
assembly's classes and interfaces available for use on the page. <%@ Assembly
Name="MyAssembly" %><%@ Assembly Src="MySource.vb" %>
@OutputCache: Declaratively controls the output caching policies of an ASP.NET page
or a user control contained in a page<%@ OutputCache Duration="#ofseconds"
Location="Any | Client | Downstream | Server | None" Shared="True | False"
VaryByControl="controlname" VaryByCustom="browser | customstring"
VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file should
be dynamically compiled and linked against the page in which this directive is declared.

What is different b/w webconfig.xml & Machineconfig.xml

Web.config & machine.config both are configuration files.Web.config contains settings


specific to an application where as machine.config contains settings to a computer. The
Configuration system first searches settings in machine.config file & then looks in
application configuration files, Web.config, can appear in multiple directories on an
ASP.NET Web application server. Each Web.config file applies configuration settings to
its own directory and all child directories below it. There is only Machine.config file on a
web server.

Which two properties are on every validation control?


We have two common properties for every validation controls
1. Control to Validate,
2. Error Message.
Which method do you use to redirect the user to another page without
performing a round trip to the client?
Server.transfer

Can you have multiple form tags in a page?

Answer:
YES.
Page can have multiple form tags but only one of them can contain runat=”server”
atrribute at a time.

Can we use multiple ScriptManager in a single page?

Yes

What is the difference between Session.Abandon() and Session.Clear()?


Session.Abandon() will end current session by firing Session_End and in the next
request, Session_Start will be fire.

Session.Clear( ) just clears the session data without killing it. With session.clear variable
is not removed from memory it just like giving value null to this session.

Session ID will remain same in both cases, as long as the browser is not closed.

Difference between Eval() and Bind()?


Eval(): -Eval() method proviedes only for displaying data from a datasource in a control.

Bind(): Bind() methods provides for two-way binding which means that it cannot be used
to dispaly as well update data from a datasource

what is single tire, 2tire 3 tire and so on upto


ntire ?
can ny one explain me about this in detail.

In one tier application the UI/Server(business


logic)/Database resides on one node.

The most basic type of client-server architecture employs


only two types of nodes: clients and servers. This type of
architecture is sometimes referred to as two-tier.

The 3-Tier architecture has the following three tiers.

1. Presentation Tier
2. Logic Tier / Business Logic Tier / Transaction Tier
3. Data Tier

Where N-Tier Architecture contains each modules resides in


different node, which are as follows
1. Presentation GUI.
(HTML, Windows Forms etc.)
2. Presentation Logic Tier.
- The Web(VB Script,VB.Net,Java Script etc.)
- Proxy Tier(SOAP,COM,DCOM etc.)
- Client interface
3. Business Tier.
(Business Objects and Rules)
4. Data Access Tier.
(Interfaces that handles all the Data I/O)
5. Data Tier.
(Storage,Query)

Single Tire:
------------
In single tire architecture all there layers of the
Enterprise application (1.Presentaion layer, 2.Business
layer, 3.Data Storage & Data Access layer) are tightly
coupled and it's most sutable for Standed alone
applications only.

Disadvantage of Single Tire:


----------------------------
1)Due to this tight coupling if we want to change the
presentation then the change might be effect on remaining
layers too.
2)Only one client can able to access the resources at a time

Two Tire:
----------
In Two tire architecture we are separating the the
Presentation layer from the Business layer and Data access
and Data Storage layes so that we can provide the
sharability of the Business logic to all the presentation
logic.

Here we are coupling only Business layer and Data Storage &
Data Access layer only.

Example of Two Tire is : Client Server architecture

Advantages of Two Tire architecture:


------------------------------------
1) More than one client can interact at a time
2) Data access centric
3) While comparing with the Singel tire architecture it os
not that much of tight coupling.

Three Tire Architecure:


------------------------
In Three tire architecture we are separating all the three
layers(Presentation layer, Business layer and Data access
and Data Storage layes) on different different nodes so
that we can maintain application very esily.

It's a loosly coupling architecure.

Example of Two Tire is : MVC-I and MVC-II

According to Gang Of Four, there are three types of Design Pattern (Visit
http://dofactory.com/Patterns/Patterns.aspx for more details)

1. Creational
2. Structural
3. Behavioral

Creational Design Pattern

Abstract Factory - Creates an instance of several families of classes


Builder - Separates object construction from its representation
Factory Method - Creates an instance of several derived classes
Prototype - A fully initialized instance to be copied or cloned
Singleton - A class of which only a single instance can exist

Structural Design Pattern

Adapter - Match interfaces of different classes


Bridge - Separates an object’s interface from its implementation
Composite - A tree structure of simple and composite objects
Decorator - Add responsibilities to objects dynamically
Facade - A single class that represents an entire subsystem
Flyweight - A fine-grained instance used for efficient sharing
Proxy - An object representing another object

Behavioral Design Pattern


Chain of Resp. - A way of passing a request between a chain of objects
Command - Encapsulate a command request as an object
Interpreter - A way to include language elements in a program
Iterator - Sequentially access the elements of a collection
Mediator - Defines simplified communication between classes
Memento - Capture and restore an object's internal state
Observer - A way of notifying change to a number of classes
State - Alter an object's behavior when its state changes
Strategy - Encapsulates an algorithm inside a class
Template Method - Defer the exact steps of an algorithm to a subclass
Visitor - Defines a new operation to a class without change

You might also like