What is the difference between ViewState,Application and Session of a Page? - asp.net

Please anyone explain me the difference between ViewState,Application and Session of a Page ?

Quick one liners - if you want more detail, just ask
ViewState is the variable that holds the current state of the page, which is held in a hidden field in the page (used frequently)
ApplicationState is a variable you can store values in during the life off the application (may get cycled periodically, and without your knowledge) (used less-frequently)
Session is the variable you can write to that will persist from the moment they hit your site until they close the browser. (barring any timeouts). (used frequently)

A great article :
How to Choose From Viewstate, Session, Application, Cache, and Cookies
Some good discussion about the difference between Session and Viewstate : Session Vs ViewState

Session state is saved on the server.
Session state is usually cleared after a period of inactivity from the user.
Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
Can be persisted in a Database, useful for Web Farms / Web Gardens.
Is Cleared when the session dies - usually after 20min of inactivity.
ViewState is saved in the page.
The view state is posted on subsequent post back in a hidden field.
Is sent back and forth between the server and client, taking up bandwidth.
Has no expiration date.
Is useful in a Web Farm / Web Garden

SESSION Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.
VIEWSTATE Variables are stored in the browser (not as cookies) but in a hidden field in the browser. Also Viewstate can hold only string data or serializable objects.

When we use view state to design a web application it retains it's state consistently, in it's current position. If we use session then it does not retain it's state, so when we refresh the browser it starts from the initial page.

Related

why ViewStates instead of Sessions

why we use to store data in ViewState? even we have Sessions to do the same job?
Session["Data"]
vs.
ViewState["Data"]
What's the difference?
ViewState applies on the page you are currently in and is stored on the client machine as a hidden field __ViewState, and is encrypted with Base64
While Session is stored on the server and in the scope of the whole user session, it is removed when the user leaves your site and the session expires (by default 20 minutes of inactivity) or you explicitly call Session.Abandon() on logout for example
You have to be careful when using session that it does not contain big objects, as when there are more active sessions, the memoru will be filled up.
And be careful when using big objects with ViewState, as its stored on the clients and goes back and forth with post backs.
**Session**
Session state is maintained in session level.
Session state value is available in all pages within a user session.
-
Session state information stored in server.
-
Session state persist the data of particular user in the server.
This data available till user close the browser or session time
Completes.
-
Session state used to persist the user-specific data on the server
Side
View state
View state is maintained in page level only.
View state of one page is not visible in another page.
View state information stored in client only.
View state persist the values of particular page in the client
(browser) when post back operation done.
Session data is valid only when the current session is active. Usually the server deletes the session after half an hour or so. The ViewState is available, even when the session is expired and you still have the page on screen. That content is serialized in the view, and it is send over the network every time you open the page, or send a form back.
Another thing is this: When you have multiple instances of one page where you want to keep a name for example, you don't want two open instances of the form share the same variables. Instead, you save it in the View, where you have it available for that page, and that page only.

How does ASP.NET server know when a session is terminated?

I understand that Session object is used to store data per session. I did the following experiment:
Open browser and visit an aspx page A, which saves some data to Session object.
Keep the browser open and open another tab to visit an aspx page B which display the session data. And it displayed just as I stored in step 1.
I close the browser and re-visit the page B, the stored data is gone.
From 3, it seems server side somehow detect that I (the client side) has terminated a session. But as I checked with Fiddler, there's no bits sent to the server when I close the browser in step 3.
So how could the ASP.NET application possibly know my step 3 request is for a new Session?
And how is session defined? Do different tabs always belong to the same session?
ADD 1
Although the session data can be displayed in page A and page B, the session IDs displayed in them are different. Why?
Correct
The session id in page A and page B are the same. I am not using InPrivate browsing.
ADD 2
There's indeed a Cookie for session ID:
ASP.NET_SessionId=lmswljirqdjxdfq3mvmbwroy; path=/; domain=localhost; HttpOnly
It was set when a POST request is responded.
So I did another experiment, I close the browser (Fire Fox) and as expected, the Cookie no longer exist. I manually create the cookie in hope of "the faked Cookie could bring back the old session." But Fiddler indicates that the manual cookie didn't get sent at all.
Fiddler says:
This request did not send any cookie data.
So is it possible to fake a cookie and restore an previous session?
And how long does a session live on server?
When the server starts a new session, it generates a new identifier for the session. The session data is stored under this identifier / key in your session provider (can be in-memory, in SQL Server or something else entirely, depending on your configuration - this is usually configured in web.config).
At the same time, the server sends a cookie to your browser (at least in the default setup). This cookie contains the identifier for your session. That is how the server can correlate your requests to your particular session: in every request, your browser will send the session cookie along. The server retrieves the identifier from the cookie and looks up your session data using the identifier.
The session cookie is non-persistent, which means that the cookie will be deleted when the browser is closed. That is why it looks like the session was deleted: the session data still exists on the server, but because the session cookie has been deleted, the browser won't send along a session cookie, so the server will consider this to be the beginning of a new session, create a new session identifier etc. Thus, the server doesn't really know when a session ends, it just knows when a session begins. That is why, in the default SQL Server-backed setup, a scheduled job will purge inactive sessions - otherwise the session data would linger in the database forever.
For more on sessions, using sessions without cookies, session configuration, providers etc., see MSDN.
As to whether sessions are shared between browser tabs: this really comes down to whether cookies are shared between tabs. I think cookies are shared across tabs in all major browsers and I would assume it would be rather confusing if they weren't, but there is nothing preventing someone from creating a browser where cookies aren't shared across tabs.
EDIT 1
If you delete the session cookie, you could in theory recreate your session by recreating the cookie. This is not a security issue per se, because you are recreating data you already have access to. However, if someone else were to recreate your session cookie, that would be a security issue. You can google "ASP.NET session hijacking" if you want to look into this.
EDIT 2
The session basically lives on the server until something purges it. Thus, the lifetime of the session depends on where you store it. If you store it in memory, the session will be deleted when the application is recycled (could be because you recycle the app in IIS or because the server is restarted). If you store it in SQL Server, the session data will live until a job deletes it because it hasn't been accessed for a while (sorry, I don't remember the details, but you can probably google them). If you store your session data in Azure table storage, they will likely never be purged.
Note
Two important details of ASP.NET session state are often overlooked:
When the session is stored outside the process (say, in SQL Server), the data you want to store must be serializable.
To prevent race conditions when accessing the session data, requests accessing the session will be serialized, that is, they will not execute concurrently.
Further details may be found in the MSDN article "Underpinnings of the Session State Implementation in ASP.NET"
This article provides more details about ASP.NET Session (http://msdn.microsoft.com/en-us/library/vstudio/ms178581(v=vs.100).aspx)
The idea is simple.
When you visit a page, a session ID is generated and set as a cookie. A timer is started for that session ID too.
As you keep coming back, the timer is reset. If you wait long enough before requesting another page, the timer will expire and your session will not be valid. At that point a new session will be generated.
To Answer your questions:
If you open multiple tabs, they will "share" the session. Because your browser is sending the session cookie from all those tabs.
However, if you open Firefox and Chrome. These two browsers will not share the session. Since, they don't share cookies.
When you close your browser, your session is still valid. And if you visit a page on the site before the session has expired, you will not get a new session. That is why, it is suggested to always log out. This way the site knows that you're leaving and it will destroy the session on your behalf.
Q: Although the session data can be displayed in page A and page B, the session IDs displayed in them are different.
A: Are you sure? The session ID should be the same for all pages. It will be different if you access page A from one browser and Page B from another browser.
ADD2
It is possible your browser's setting is to destroy cookies on windows close. Please double check that in options it's set to remember history.
Cookies can be forged. If an attacker can get the session ID, they can forge a cookie at their end. I'm not sure if Fiddler allows you to create a cookie manually. You will need to dig through the docs. Or maybe someone else here can answer this questions.

ASP.NET "Re-establish Session" Performance Hit

After a user has initially established session with ASP.NET, with each subsequent HTTP request how much of StateServer session objects are immediately and automatically fetched and deserialized? For example:
Are ALL session objects fetched the moment the request is received and session re-established, or...
After session is re-established are session objects fetched and deserialized individually as each request to HttpContext.Session["..."] is made?
The answer has a HUGE impact on how I can use session. For example, if I have pre-fetched a significant amount of user data into session, and the StateServer session is completely deserialized upon each HTTP request, then I will experience a noticeable performance hit. If however the pre-fetched user data is only deserialized when I request specific session keys, then for me there is no worry.
UPDATE
After marking an answer to this question, I discovered that ASP.NET with AppFabric Server 1.1 has an option to have session restored on-demand rather than all-at-once. This is controlled by useBlobMode in your web.config.
Session loads all of the user Session information when the page is first loaded. It then persists the users Session information back to the store after the page is done processing.
You can get a better understanding via MSDN on custom state store implementations.
This is a major reason that you're supposed to use Session as rarely as possible because it is expensive to deal with (both in the transporting to and from the data store and the holding of the data in memory for the lifetime of the page request).

Does viewstate expire?

Let's say you have a aspx page that does not rely on session, but does rely on viewstate for persistance between postbacks.
If a user is accessing this page, and leaves for a long lunch, will viewstate still be valid when he returns?
Viewstate itself does not expire. Since it's posted back in a form, it can be reconstituted any time.
According to MSDN: "...it is possible for view state to expire if a page is not posted back within the session expiration time". So, in a round about sort of way, it can expire if your session does, but viewstate does not directly expire. Since you're not using session state anyway, you don't have to worry about implicit expiration.
Note that I wouldn't have said it expired. That was MS who I quoted in their own article entitled Controlling ViewState
No ViewState is kept as part of the PostBack process. You can, however, override the Page class's SavePageStateToPersistenceMedium() and LoadPageStateFromPersistenceMedium(), to implement that behavior if desired. For more information read Understanding the ASP.NET ViewState.
Note that Page ViewState is stored in the Session so if your Session expires, the ViewState will be lost. I wouldn't say this is ViewState expiring, but yes, it will be destroyed after Session timeout.
Also, as a gotcha, by default ASP.NET encrypts ViewState with an autogenerated key. This can be overridden with the MachineKey element in the web.congif file. Even though ViewState won't expire, it can become invalid if a different autogenerated key is used to decrypt ViewState, such as after an IIS Reset, redeploying an application, or hitting a different server in a web farm. If you're planning on storing viewstate for long periods of time, watch out for how it's encrypted/decrypted.
http://msdn.microsoft.com/en-us/library/ms998288.aspx
Viewstate does not expire.
All viewstate data is stored on the client and is submitted back to the server when the user executes a postback.
This has some very interesting implications, and is explained very thoroughly here.
Yes, ViewState expires in certain conditions. For example when you are using iframe:s, or when you are upkeeping "live" connection to the server with regular postbacks. Then you might want to investigate this option: <sessionPageState historySize="9"/>, which actually hard-codes how many "postback results" are stored in the Session (if SessionPageStatePerster is used). Each postback stores it's ViewState to the end of the Queue in Session["__VIEWSTATEQUEUE"], and deletes ViewStates that are "too old". And how do you think SessionPageStatePerster decides which ViewStates are too old.. by configuring some arbitrary historySize-constant in web.config.. Omg! It too me forever to find this problem... My hatred toward asp.net programming is undescribable now.. grrr...
Viewstate does not expire, as long as they are still on the page, it will still be there and functional.
The ViewState will persist from POST to POST. It's actually stored inside a hidden field on your form so that it gets POSTed back to your server all the time.
As long as you aren't relying on the Session you shouldn't have any problems rebuilding page state. It's easy to test your Page's state code if you want though: just set your session to expire after 60 seconds in your web.config then load your page, wait a little more than a minute (surf over to Stack Overflow and answer some questions) and then click a button on your page.
Sorry to relive this old thread, but new information is available now:
Yes, ViewStates expire. I come from 19 hours researching about a problem of ViewStates losing its values between long time interval postbacks. It took me a while reading MSDN documents and Stackoverflow answers saying it was basically impossible to happen unless a custom ViewState storage implementation was employed, which, now I know, it's not true.
My problem was taking place in a SharePoint 2013 environment. The service known as Distributed Cache (a.k.a. AppFabric) does the caching of the ViewState and has a Time to Live associated to it. You can find more information here:
http://blogs.msdn.com/b/besidethepoint/archive/2013/03/27/appfabric-caching-and-sharepoint-1.aspx
The interesting bit of information can be found in this phrase:
"To improve page performance, beginning in SharePoint 2013 SharePoint caches ViewState data server-side rather than transferring it back and forth to clients."
I hope this information helps somebody so desperate as I was 19 hours ago.
ViewState is kept in a hidden field on the page itself. So as long as the user has the page, he'll have the ViewState. But if your app automatically logs the user out after a certain period of time, still having the ViewState may not do him any good.
By default, Viewstate is included with the html content as a hidden input. That means it won't expire, but that everything in viewstate must be uploaded from the user's browser. Since that's typically the slowest part of the connection in a public site, putting a lot of stuff in viewstate can quickly make your site seem very slow.
The short answer is: no.
The longer answer is: it depends on implementation of ViewState storage. You can provide custom implementation of ViewState which could expire after given amount of time. For example, you could store ViewState in database or on disk and send only some reference to the stored value in a hidden field. Then you can use batch processing to remove outdated ViewState data or perform expiration upon request.
No Viewstate doesnot expires.After redirecting to other page then value of view state lost or expire viewstate.
for more detail http://www.c-sharpcorner.com/UploadFile/78d182/Asp-Net-state-management-techniques/

ASP.Net Session

I am wanting to store the "state" of some actions the user is performing in a series of different ASP.Net webforms. What are my choices for persisting state, and what are the pros/cons of each solution?
I have been using Session objects, and using some helper methods to strongly type the objects:
public static Account GetCurrentAccount(HttpSessionState session)
{
return (Account)session[ACCOUNT];
}
public static void SetCurrentAccount(Account obj, HttpSessionState session)
{
session[ACCOUNT] = obj;
}
I have been told by numerous sources that "Session is evil", so that is really the root cause of this question. I want to know what you think "best practice", and why.
There is nothing inherently evil with session state.
There are a couple of things to keep in mind that might bite you though:
If the user presses the browser back button you go back to the previous page but your session state is not reverted. So your CurrentAccount might not be what it originally was on the page.
ASP.NET processes can get recycled by IIS. When that happens you next request will start a new process. If you are using in process session state, the default, it will be gone :-(
Session can also timeout with the same result if the user isn't active for some time. This defaults to 20 minutes so a nice lunch will do it.
Using out of process session state requires all objects stored in session state to be serializable.
If the user opens a second browser window he will expect to have a second and distinct application but the session state is most likely going to be shared between to two. So changing the CurrentAccount in one browser window will do the same in the other.
Your two choices for temporarily storing form data are, first, to store each form's information in session state variable(s) and, second, to pass the form information along using URL parameters. Using Cookies as a potential third option is simply not workable for the simple reason that many of your visitors are likely to have cookies turned off (this doesn't affect session cookies, however). Also, I am assuming by the nature of your question that you do not want to store this information in a database table until it is fully committed.
Using Session variable(s) is the classic solution to this problem but it does suffer from a few drawbacks. Among these are (1) large amounts of data can use up server RAM if you are using inproc session management, (2) sharing session variables across multiple servers in a server farm requires additional considerations, and (3) a professionally-designed app must guard against session expiration (don't just cast a session variable and use it - if the session has expired the cast will throw an error). However, for the vast majority of applications, session variables are unquestionably the way to go.
The alternative is to pass each form's information along in the URL. The primary problem with this approach is that you'll have to be extremely careful about "passing along" information. For example, if you are collecting information in four pages, you would need to collect information in the first, pass it in the URL to the second page where you must store it in that page's viewstate. Then, when calling the third page, you'll collect form data from the second page plus the viewstate variables and encode both in the URL, etc. If you have five or more pages or if the visitor will be jumping around the site, you'll have a real mess on your hands. Keep in mind also that all information will need to A) be serialized to a URL-safe string and B) encoded in such a manner as to prevent simple URL-based hacks (e.g. if you put the price in clear-text and pass it along, someone could change the price). Note that you can reduce some of these problems by creating a kind of "session manager" and have it manage the URL strings for you but you would still have to be extremely sensitive to the possibility that any given link could blow away someone's entire session if it isn't managed properly.
In the end, I use URL variables only for passing along very limited data from one page to the next (e.g. an item's ID as encoded in a link to that item).
Let us assume, then, that you would indeed manage a user's data using the built-in Sessions capability. Why would someone tell you that "Session is evil"? Well, in addition to the memory load, server-farm, and expiration considerations presented above, the primary critique of Session variables that they are, effectively, untyped variables.
Fortunately, prudent use of Session variables can avoid memory problems (big items should be kept in the database anyhow) and if you are running a site large enough to need a server farm, there are plenty of mechanisms available for sharing state built in to ASP.NET (hint: you will not use inproc storage).
To avoid essentially all of the rest of Session's drawbacks, I recommend that implement an object to hold your session data as well as some simple Session object management capabilities. Then build these into a descendent of the Page class and use this descendent Page class for all of your pages. It is then a simple matter to access your Session data via the page class as a set of strongly-typed values. Note that your Object's fields will give you a way to access each of your "session variables" in a strongly typed manner (e.g. one field per variable).
Let me know if this is a straightforward task for you or if you'd like some sample code!
As far as I know, Session is the intended way of storing this information. Please keep in mind that session state generally is stored in the process by default. If you have multiple web servers, or if there is an IIS reboot, you lose session state. This can be fixed by using a ASP.NET State Service, or even an SQL database to store sessions. This ensures people get their session back, even if they are rerouted to a different web server, or in case of a recycle of the worker process.
One of the reasons for its sinister reputation is that hurried developers overuse it with string literals in UI code (rather than a helper class like yours) as the item keys, and end up with a big bag of untestable promiscuous state. Some sort of wrapper is an entry-level requirement for non-evil session use.
As for "Session being evil" ... if you were developing in classic ASP I would have to agree, but ASP.NET/IIS does a much better job.
The real question is what is the best way to maintain state. In our case, when it comes to the current logged in user, we store that object in Session, as we are constantly referring to it for their name, email address, authorization and so forth.
Other little tidbits of information that doesn't need any long-term persistence we use a combination of cookies and viewstate.
When you want to store information that can be accessed globally in your web application, a way of doing this is the ThreadStatic attribute. This turns a static member of a Class into a member that is shared by the current thread, but not other threads. The advantage of ThreadStatic is that you don't have to have a web context available. For instance, if you have a back end that does not reference System.Web, but want to share information there as well, you can set the user's id at the beginning of every request in the ThreadStatic property, and reference it in your dependency without the need of having access to the Session object.
Because it is static but only to a single thread, we ensure that other simultaneous visitors don't get our session. This works, as long as you ensure that the property is reset for every request. This makes it an ideal companion to cookies.
I think using Session object is OK in this case, but you should remember Session can expire if there is no browser activity for long time (HttpSessionState.Timeout property determines in how many minutes session-state provider terminates the session), so it's better to check for value existence before return:
public static Account GetCurrentAccount(HttpSessionState session)
{
if (Session[ACCOUNT]!=null)
return (Account)Session[ACCOUNT];
else
throw new Exception("Can't get current account. Session expired.");
}
http://www.tigraine.at/2008/07/17/session-handling-in-aspnet/
hope this helps.
Short term information, that only needs to live until the next request, can also be stored in the ViewState. This means that objects are serialized and stored in the page sent to the browser, which is then posted back to the server on a click event or similar. Then the ViewState is decoded and turned into objects again, ready to be retrieved.
Sessions are not evil, they serve an important function in ASP.NET application, serving data that must be shared between multiple pages during a user's "session". There are some suggestions, I would say to use SQL Session management when ever possible, and make certain that the objects you are using in your session collection are "serializable". The best practices would be to use the session object when you absolutely need to share state information across pages, and don't use it when you don't need to. The information is not going to be available client side, A session key is kept either in a cookie, or through the query string, or using other methods depending on how it is configured, and then the session objects are available in the database table (unless you use InProc, in which case your sessions will have the chance of being blown away during a reload of the site, or will be rendered almost useless in most clustered environments).
I think the "evil" comes from over-using the session. If you just stick anything and everything in it (like using global variables for everything) you will end up having poor performance and just a mess.
Anything you put in the session object stays there for the duration of the session unless it is cleaned up. Poor management of memory stored using inproc and stateserver will force you to scale out earlier than necessary. Store only an ID for the session/user in the session and load what is needed into the cache object on demand using a helper class. That way you can fine tune it's lifetime according to how often that data us used. The next version of asp.net may have a distributed cache(rumor).
Session as evil: Not in ASP.NET, properly configured. Yes, it's ideal to be as stateless as possible, but the reality is that you can't get there from here. You can, however, make Session behave in ways that lessen its impact -- Notably StateServer or database sessions.

Resources