Visit the blog for .Net FAQ,.Net interview questions,ASP .Net FAQ, C# .Net FAQ,ASP .Net interview questions, interview question on .Net, interview questions on C#.
A session is defined as the period of time that a unique user interacts with a Web application.
Session provides the facility to store information on server memory.
Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session. For example, a user selects stocks to track and the Web application can store these values in the user's ASP session instance:
On subsequent pages these values are read and the Web application has access to these values without the user re-entering them:
Advantages and Disadvantages of Session ?
Following are the basic advantages and disadvantages of using session. Advantages :
It helps to maintain user states and data to all over the application.
It can easily be implemented and we can store any kind of object.
Stores every client data separately.
Session is secure and transparent from user.
Disadvantages :
Performance overhead in case of large volume of user, because of session data stored in server memory.
Overhead involved in serializing and De-Serializing session Data. because In case of StateServer and SQLServer session mode we need to serialize the object before store.
Session ID
Asp.Net use 120 bit identifier to track each session. This is secure enough and can't be reverse engineered. When client communicate with server, only session id is transmitted, between them. When client request for data, ASP.NET looks on to session ID and retrieves corresponding data. This is done in following steps,
Client hits web site and some information is stored in session.
Server creates a unique session ID for that clients and stored in Session State Provider .
Again client request For some information with that unique session ID from Server.
Server,looks on Session Providers, and retrieve the serialized data from state server and type cast the object .
Session Event
There are two types of session events available in asp.net.
Session_Start
Session_End
you can handle both this event in global.asax file of your web application. When a new session initiate session_start event raised and Session_End event raised when a session is abandoned or expired.
Session configuration
Below is a sample config.web file used to configure the session state settings for an ASP.NET application:
The settings above are used to configure ASP.NET session state. Let's look at each in more detail and cover the various uses afterward.
Mode. The mode setting supports three options: inproc, sqlserver, and stateserver. As stated earlier, ASP.NET supports two modes: in process and out of process. There are also two options for out-of-process state management: memory based (stateserver), and SQL Server based (sqlserver). We'll discuss implementing these options shortly.Inpoc mode is by default and time duration is 30 minutes by default.
Cookieless. The cookieless option for ASP.NET is configured with this simple Boolean setting.
Timeout. This option controls the length of time a session is considered valid. The session timeout is a sliding value; for each request the timeout period is set to the current time plus the timeout value
Sqlconnectionstring. The sqlconnectionstring identifies the database connection string that names the database used for mode sqlserver.
Server. In the out-of-process mode stateserver, it names the server that is running the required Windows NT service: ASPState.
Port. The port setting, which accompanies the server setting, identifies the port number that corresponds to the server setting for mode stateserver.
Session Mode and State Provider.
In ASP.NET there are following session mode available.
InProc
Out-of-Process
Out of Process can categorized in three parts StateServer SQLServer Custom
For every session State, there is Session Provider. Following diagram will show you how they are related.
we can choose the session State Provider based on which session state we are selecting. When ASP.NET request for any information based on session ID, session state and its corresponding provider are responsible for sending the proper information based on user. Following tables show, the session mode along with there provider Name.
Session State Mode
State Provider
InProc
In-Memory Object
StateServer
Aspnet_state.exe
SQLServer
DataBase
Custom
CustomProvider
apart from that, there is another mode, "Off". If we select this option the session will be disabled for the application.
Advantages and Disadvantages of In-Process
Advantages :
It store Session data in memory object of current application domain. So accessing data is very fast and data is easily available.
There is not requirements of serialization to store data in InProc Session Mode.
Implementation is very easy,just similar to using View State.
Disadvantages :
Although InProc Session is fastest, common and default mechanism, It has lots of limitation.
If the worker Process or application domain recycles all session data will be lost.
Though its fastest, but more session data and more users can affects performance, because of memory.
We can't use it in web Garden scenarios.
This session mode is not suitable for web farm scenarios also.
StateServer Session Mode
Overview of StateServer Session Mode :
This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Services, which is Independent to IIS and can also run on a separate server. This session state is totally managed by aspnet_state.exe. This server may runs on the same system, but it's out side of that main application domain where your web application is running. This allow if you restart your asp.net process restarted your session data will be alive. This approaches has several disadvantages due to the overhead of serialization and de-serialization, its also increases the cost of data access because of every time when user retrieves session data, our application hits a different process.
In StateServer the Session data is stored in a separate Server which is Independent to IIS and it handled by aspnet_state.exe. This process is run as windows Services.You can start this service from windows MMC or from command prompt. From command from just typing "net start aspnet_state".
This session mode provide us more secure and reliable Session management in asp.net.In this session mode,the Session data is serialized and stored in the SQL Server database.Main disadvantages of this session storage methods is overhead related with Data Serialization and De-Serialization.It is the best option for using in the web farms.
To setup SQL Server we need to take help of two sql Script.
For Installing: InstallSqlState.sql
For Un-Installing:UninstallSQLState.sql
The most easiest way to configure SQL Server, is using aspnet_regsql command.
I have explained the detailed use of these file in configuration section. This is the most useful state management in the web farm scenario.
SQL Server Session mode is more reliable and secure session state management.
Its keeps data in a centralized location (database).
We should use SQL server session mode when we need to implement Session with some more security.
If there happens to be frequent server Restart we can implement SQL server.
This is perfect mode that fits in web farm and web garden scenarios.
We can use SQL server Session mode when we need to share session between two different application.
Configuration for SQL Server Session Mode
In SQL Server Session mode, we are storing session data in a SQL Server, so we need to first provide the database connection string in web.config . sqlConnectionString attribute is used to provide the connection string in web.config.
After setup the connection string we need to configure the SQL Server. I am explaining how to configure your your SQL server using aspnet_regsql command. Step 1: From Command prompt, Go to your Framework Version Directory
Generally we use either of InProc, StateServer or SQL Server Session mode for our application, but we also need to know the fundamental of Custom Session mode. This session mode is quite interesting, because Custom session gives full control to us to create every thing even session ID.You can write your own algorithm to generate session ID.
You can implement custom providers that store session data in other storage mechanisms simply by deriving from SessionStateStoreProviderBase Class. You can also Generate New Session Id by Implementing ISessionIDManager.
This are the following methods are called during implementation of Custom Session
In Initialize methods we can set the Custom Provider. This will initialize the connection with that specified provider.SetItemExpireCallback used to set SessionTimeOut, we can register any methods that will call at the time of session expire. InitializeRequest is called on every request and CreateNewStoreData used to create a new instance of SessionStateStoreData .
Once Moosa asked Go I wanna meet your friend. God said, go on that mountain you will find my friend. Moosa went there and saw a man in very bad condition. He has sore wounds all over his body. Smell was coming from there. Moosa saw him and turned away. He called Moosa, "You have come with so enthuse, you drawn in horn so soon, what is the matter?" Moosa aghast you are friend of God ! He answered yes. I am the lover of God. I am happy in every condition in which God wants.
Moosa asked anything that I can do for you. He said I had two wishes first is I wanted to meed you, that is completed and second is I wanna chilled water please get me that. As soon as Moosa turned for water A lion appeared and attacked on that man and killed him. Moosa said to God, He was your friend. God said he has done two mistakes. First is he had wished to meet other person rather than me. And second is if need water he must say to us. We produce fountain of chilled water.
I asked my friend's little daughter what she wanted to be when she grows up.
She said she wanted to be Prime Minister some day.
Both her parents, Labour supporters, were standing there, so I asked her, "If you were the Prime Minister what would be the first thing you would do?" She replied, " I'd give food and houses to all those poor people on benefits."
Her Parents Beamed and said, "Welcome to the Labour Party!"
"That is a worthy goal!" I told her , and continued, "But you don't have to wait until you are Prime Minister to do that. You can come over to my house, mow the lawn, pull weeds, swipe my drive and I'll pay you 25. Then I'll take you over to that homeless chap who hangs out in front of the store. You can give give him 25 to use toward food."
She thought that over for a few seconds, then she looked me straight in the eye and asked, "Why doesn't the homeless man come over and do the work himself and you can just pay him the 25?"
I smiled and said, "Welcome to the Conservative Party."
I Love the view of Lotus Pond. Look at the Raising Sober
Rain.(Init,Load View State,Load Postback Data,Load,Raise Postback
Event,Save View State,Render)
Web Pages developed in ASP.Net are HTTP based and HTTP protocol is a stateless protocol. It means that web server does not have any idea about the requests from where they coming i.e from same client or new clients. On each request web pages are created and destroyed.
State(Cache) management is the process by which you maintain state and page information over multiple requests for the same or different pages.
There are two ways to maintain the state(Cache) of web form.
1.Client-Side State Management
2.Server-Side State Management
1. Client-Side State Mangement :- In client side state management we store the information in the page or in client computer, no information is stored on the server between round trips.
There are four ways for Client Side State Management
A. View State
B. Cookies
C. Hidden Field
D. Query String
A. View State :- When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState.
Each control on a Web Forms page, including the page itself, has a EnableViewState property, it is a built-in structure for automatic retention of page and control state. By default it is true for every control.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
The hidden field name is __ViewState and id is __ViewState.
The ViewState property is defined in the System.Web.UI.Control class, meaning that all ASP.NET server controls have this property available.
What manages the view state is the StateBag class. This class is like a dictionary—you may store key/value pairs in it.
View State can be use as dictionary object and user can save custom values there on code behind.
ViewState["ViewStateVariable"]=1;
By default value of EnableViewState is true for each control.
Session State
View State
Holds server resources?
Yes
No
Times out?
Yes – after 20 minutes (default)
No
Stores any .NET type?
Yes
No, limited support for: strings, integers, Booleans, arrays, ArrayList, hashtable, PairS, TripletS, custom TypeConverters
Increases "HTML payload"?
No
Yes
Storing Objects in View State
--> You can store your own objects in view state just as easily as you store numeric and string types. However, to store an item in view state, ASP.NET must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is called serialization. If your objects aren't serializable (and by default they aren't), you'll receive an error message when you attempt to place them in view state.
To make your objects serializable, all you need to do is to add the 'Serializable' attribute before your class declaration. For example, here's an exceedingly simple Student class:
Because the Student class is marked as serializable, it can be stored in view state:
// Storing a student in view state.
Student stud = new Student("John", "Doe");
ViewState["CurrentStudent"] = stud;
Remember, when using custom objects, you'll need to cast your data when you retrieve it from view state.
// Retrieve a student from view state.
Student stud = (Student) ViewState["CurrentCustomer"];
To be serializable, your classes you must meet these requirements:
• Your class must have the Serializable attribute.
• Any classes it derives from must have the Serializable attribute.
• All the private variables of the class must be serializable data types. Any nonserializable data type must be decorated with the NonSerialized attribute (which means it is simply ignored during the serialization process.
Can I Get Rid Of View State Completely?
No. You will always have a relatively short string representing the page itself even if you turn off the view state on each and every control.
When ViewState Load and Save
Before we can dive into our examination of Loading stage of ViewState it is important that we take a quick moment to discuss the ASP .Net page life cycle in short.
Stage 1 - Initialization
After the control hierarchy has been built, the Page, along with all of the controls in its control hierarchy, enter the initialization stage. This stage is marked by having the Page and controls fire their Init events. At this point in the page life cycle, the control hierarchy has been constructed, and the Web control properties that are specified in the declarative syntax have been assigned.
With regards to view state it is important for two reasons; first, server controls don't begin tracking view state changes until right at the end of the initialization stage. Second, when adding dynamic controls that need to utilize view state, these controls will need to be added during the Page's Init event as opposed to the Load event, as we'll see shortly.
Stage 2 - Load View State
The load view state stage only happens when the page has been posted back. During this stage, the view state data that had been saved from the previous page visit is loaded and recursively populated into the control hierarchyof the Page. It is during this stage that the view state is validated.
Stage 3 - Load Postback Data
The load postback data stage also only happens when the page has been posted back. A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data.
To help clarify things, let's look at a simple example. One nice thing about ASP.NET is that the Web controls in a Web Form remember their values across postback. That is, if you have a TextBox Web control on a page and the user enters some value into the TextBox and posts back the page, the TextBox's Text property is automatically updated to the user's entered value. This happens because the TextBox Web control implements the IPostBackDataHandler interface, and the Page class hands off the appropriate value to the TextBox class, which then updates its Text property.
To concretize things, imagine that we have an ASP.NET Web page with a TextBox whose ID property is set to txtName. When the page is first visited, the following HTML will be rendered for the TextBox: . When the user enters a value into this TextBox (such as, "Hello, World!") and submits the form, the browser will make a request to the same ASP.NET Web page, passing the form field values back in the HTTP POST headers. These include the hidden form field values (such as __VIEWSTATE), along with the value from the txtName TextBox.
When the ASP.NET Web page is posted back in the load postback data stage, the Page class sees that one of the posted back form fields corresponds to the IPostBackDataHandler interface. There is such a control in the hierarchy, so the TextBox's LoadPostData() method is invoked, passing in the value the user entered into the TextBox ("Hello, World!"). The TextBox's LoadPostData() method simply assigns this passed in value to its Text property.
Notice that in our discussion on the load postback data stage, there was no mention of view state. You might naturally be wondering, therefore, why I bothered to mention the load postback data stage in an article about view state. The reason is to note the absence of view state in this stage. It is a common misconception among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. This is not the case, as the values are identified via posted back form field values, and assigned in the LoadPostData() method for those controls that implement IPostBackDataHandler.
Stage 4 - Load
This is the stage with which all ASP.NET developers are familiar, as we've all created an event handler for a page's Load event (Page_Load). When the Load event fires, the view state has been loaded (from stage 2, Load View State), along with the postback data (from stage 3, Load Postback Data). If the page has been posted back, when the Load event fires we know that the page has been restored to its state from the previous page visit.
Stage 5 - Raise Postback Event
Certain server controls raise events with respect to changes that occurred between postbacks. For example, the DropDownList Web control has a SelectedIndexChanged event, which fires if the DropDownList's SelectedIndex has changed from the SelectedIndex value in the previous page load. Another example: if the Web Form was posted back due to a Button Web control being clicked, the Button's Click event is fired during this stage.
There are two flavors of postback events. The first is a changed event. This event fires when some piece of data is changed between postbacks. An example is the DropDownLists SelectedIndexChanged event, or the TextBox's TextChanged event. Server controls that provide changed events must implement the IPostBackDataHandler interface. The other flavor of postback events is the raised event. These are events that are raised by the server control for whatever reason the control sees fit. For example, the Button Web control raises the Click event when it is clicked, and the Calendar control raises the VisibleMonthChanged event when the user moves to another month. Controls that fire raised events must implement the IPostBackEventHandler interface.
Since this stage inspects postback data to determine if any events need to be raised, the stage only occurs when the page has been posted back. As with the load postback data stage, the raise postback event stage does not use view state information at all. Whether or not an event is raised depends on the data posted back in the form fields.
Stage 6 - Save View State
In the save view state stage, the Page class constructs the page's view state, which represents the state that must persist across postbacks. The page accomplishes this by recursively calling the SaveViewState() method of the controls in its control hierarchy. This combined, saved state is then serialized into a base-64 encoded string. In stage 7, when the page's Web Form is rendered, the view state is persisted in the page as a hidden form field.
Stage 7 - Render
In the render stage the HTML that is emitted to the client requesting the page is generated. The Page class accomplishes this by recursively invoking the RenderControl() method of each of the controls in its hierarchy.
The Role of View State
View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state.
For example, imagine we have a Label Web control in the HTML portion with the following declarative syntax:
<asp:label name="Verdana" runat="server" text="Hello, World!"></asp:label>
When the control hierarchy is built in the instantiation stage, the Label's Text property will be set to "Hello, World!" and its Font property will have its Name property set to Verdana. Since these properties will be set each and every page visit during the instantiation stage, there's no need to persist this information in the view state.
What needs to be stored in the view state is any programmatic changes to the page's state. For example, suppose that in addition to this Label Web control, the page also contained two Button Web controls, a Change Message Button and an Empty Postback button. The Change Message Button has a Click event handler that assigns the Label's Text property to "Goodbye, Everyone!"; the Empty Postback Button just causes a postback, but doesn't execute any code. The change to the Label's Text property in the Change Message Button would need to be saved in the view state. To see how and when this change would be made, let's walk through a quick example. Assuming that the HTML portion of the page contains the following markup:
And the code-behind class contains the following event handler for the Button's Click event:
Figure 4 illustrates the sequence of events that transpire, highlighting why the change to the Label's Text property needs to be stored in the view state.
To understand why saving the Label's changed Text property in the view state is vital, consider what would happen if this information were not persisted in view state. That is, imagine that in step 2's save view state stage, no view state information was persisted. If this were the case, then in step 3 the Label's Text property would be assigned to "Hello, World!" in the instantiation stage, but would not be reassigned to "Goodbye, Everyone!" in the load view state stage. Therefore, from the end user's perspective, the Label's Text property would be "Goodbye, Everyone!" in step 2, but would seemingly be reset to its original value ("Hello, World!") in step 3, after clicking the Empty Postback button.
The Cost of View State
Nothing comes for free, and view state is no exception. It imposes two performance hits whenever an ASP .Net page requested.
1. On all page visits, during the save view state stage the page class generate the collective view state for all the controls in control hierarchy and serialize the state to a base 64 encoding string. Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.
2. The__ViewState field adds extra size to web page that the client must download. For some view state-heavy pages this can be tens of kilobytes of data, __ ViewState form field must be sent back to the Web server in the HTTP post header, thereby increasing the postback request time
If ViewState size is too much than it can create the problem for SEO, Search Engine Optimization will not get your actual data so your site will never be in Google list or any other search engine list. You can solve this problem by moving view state tag to below of the page. you can do it on render event of the page.
A predicate delegate is a delegate with the following signature:
Return type - bool
Argument type - generic
Example :
using System;
class Program
{
static void Main()
{
//
// This Predicate instance returns true if the argument is one.
//
Predicate isOne =
x => x == 1;
//
// This Predicate returns true if the argument is greater than 4.
//
Predicate isGreaterEqualFive =
(int x) => x >= 5;
//
// Test the Predicate instances with various parameters.
//
Console.WriteLine(isOne.Invoke(1));
Console.WriteLine(isOne.Invoke(2));
Console.WriteLine(isGreaterEqualFive.Invoke(3));
Console.WriteLine(isGreaterEqualFive.Invoke(10));
}
}
Output
True
False
False
True
=========================
Tera hath mere kandhe per tha Mere Panv angaro pe chalte rahe.