.

Saturday, July 12, 2008

ASP.NET Interview Question Answer - 2

What is global.asax in ASP.NET? Application_start, Session_start?

The global.asax file is used to add application level logic & processing. Note that the global.asax does not handle any UI related processing, nor does it process individual page level requests. It basically controls the following events...
Application_Start
Application_End
Session_Start
Session_End

Note that in Visual Studio 2003 automatically creates this file for every web application, but in Visual Studio 2005, this file has to be added to the web project specifically.

Code in the global.asax is compiled when the web appication is built for the first time. The application level code and variables may be declared in Application_Start. Similarly, session level code & variables may be declared in Session_Start event. Application level events are for the entire application, and may be used for any user, while Session level events are user specific for a length of a session.


How to pass values between pages?

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


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

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.


Explain the page life cycle in ASP.NET 2.0

ASP.NET 2.0 Page Life Cycle - The lifetime of an ASP.NET page is filled with events. 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.

How to store global variables?

Global variables should always be used with caution. They are the best means of storing data that has to be accessed anywhere. The most common ways of accessing global variables in ASP.NET are by using Application, Cache, and Session objects.

Application - Application objects are application level global variables, that need to be shared for all user sessions. Thus, data specific to a user should'nt be saved in application objects. While using application objects, the objects are locked so that multiple page requests cannot access a specific application object. Below is a code example for usage of application object...

Application.Lock();
Application("UserData") = "dotnetuncle";
Application.UnLock();
Response.Redirect("DestinationPage.aspx");

//DestinationPage.aspx gets the value from the Application State
String sString = Application("UserData").ToString();

Cache - The cache object is similar to the application object in scope, however, it does not need any explicit locking and unlocking. Code below shows usage of Cache object...

Cache("Userdata") = "dotnetuncle";
Response.Redirect("DestinationPage.aspx");

//Destination.aspx retrieves the value from Cache object
String sString = Cache("Userdate").ToString();

The cache object also shares data across all user sessions. The cache object has features like it can automatically expire cached content after specified time periods or once memory consumption has reached a maximum.

Session - The session object is used to store the data specific to a user for the entire length of a user's visit to a website. Below is a code that shows usage of the session object in ASP.NET ...

//InitialPage.aspx stores the user’s credentials in Session state
Session("UserName") = txtUserName.Text;
Server.Transfer("DestinationPage.aspx");

//DestinationPage.aspx gets the user’s name from Session state
String sString = Session("UserName").ToString();

ASP.NET stores session values in the server memory. If there are plenty of active user's of a website, then the memory consumption on the server increases by leaps. Because of this reason, large websites use very less Session Variables. Session state can be configured to be automatically stored in a SQL Server database, or it can be configured to be stored centrally in a state server within a server farm. By default, a user’s session ends 20 minutes after their last page request and their data goes out of scope, freeing it from memory. In case user information is to be tracked by a large website, then a oookie is preferred.

Cookie - A cookie is a piece of data that is stored on a user's browser. Thus, a cookie does not use any server memory. For more details on cookie, Click Here

How to store values between postbacks in ASP.NET? What is viewstate in ASP.NET?

When a postback happens (i.e. when a form is submitted to a server), the variable values that are set in the code-behind page are erased from the memory of the client system. This concept would be different from what happens in Windows-based applications, where the variable variables persist in memory until they are freed from the memory either by the garbage collector, or by specific codes like dispose or finalize.

In web applications, variable values simply get erased. But it is very simple to persist these values. They may be persisted using the Viewstate object. Before the postback is invoked, the variable's value is saved in a viewstate object. In the recieving page, the viewstate's value may be retrieved back. See example code below...

//Save the value in ViewState object before the PostBack
ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack
String strFirstName = ViewState("SomeVar").ToString();

Note that the viewstate value is saved and then passed to the next page by ASP.NET in the form of a hidden variable. Ideally, big values like datasets should not be saved in viewstate as they may tend to slow down the performance of the web page.

Apart from the viewstate object, values may also be sent across postbacks between pages using Application, Session and Cache objects.

What is a server control in ASP.NET?

A server control in ASP.NET is a control that has the runat="server" attribute. The component is processed on the server, and its HTML equivalent stream is passed to the browser. Note that all server controls inherit from the System.Web.UI.Control class. The server side controls may be dragged to a web page from the standard toolbox. Note that HTML controls are not server side controls, but they may behave so if the runat="server" attribute is added to their source.

What is viewstate in ASP.NET?

Viewstate object is used to persist data of variables across postbacks. It even existed in classic ASP. In ASP.NET, a variable's value is assigned to a a viewstate object and then this is passed as a hidden variable and then may be retrieved by a page after a postback. See the example below...

//Save the value in ViewState object before the PostBack
ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack
String strFirstName = ViewState("SomeVar").ToString();

Note that Viewstate object's value is accessible only at page level. This means that if a viewstate is created at page1.aspx, then it may be used only within page1.aspx after the postback, and cannot be used by any other page. To know how to pass values from one page to another, Click Here.


No comments:

.