What is the use of Session in web application/ASP.Net? - asp.net

I am new to web technology, I am wondering about the use of Session.
What is the basic use of Session, is it only used for saving soma data or it has something else ?

Session is all about storing data across page requests. One of the downsides of HTTP (the core protocol of web applications) is that it doesn't store anything from one page request to another; you have to build all that in yourself. There are generally two places to store data: the browser or the server, and sessions are server based.
A session starts when you first log into a system and continues for as long as you stay on the site. When you close your browser (or perhaps log off, depending upon how it's configured) your session ends (there's usually a delay, so it ends after X minutes without activity). If you, as a web site developer, need to store some information about the user (name, address, shopping cart, etc), then session is often used as a place for that storage.Generally the reason for storing data in the session is for performance; reading from a database is relatively slow (compared to other actions a web page performs), so if you read the data once then store it in the session, you can make your site faster. The downside is that the more data you store in the session, the more memory you use on the server, so it's a trade-off between performance and memory usage.
In the above code, the session is being used to store some user details (name, email, etc). If those don't exist in the session when read, an empty string is returned.

Session is for storing user-specific data for a limited period of time - namely, a single session of activity:
[A] communication session is a semi-permanent interactive information exchange between communicating devices that is established at a certain time and torn down at a later time.
This is deliberately vague, since the details of what makes a "session" can be somewhat different from application to application depending on how it is used. For a typical web application, a user's session begins the first time they visit the site, and ends some time after the user has no longer made any requests, and is presumed to have left the site. Things like a shopping cart, which are user-specific, might go in the session object, since it follows the same user across requests. In ASP.NET, the Session is described:
ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session.

Session is use for storing some data for limited priod of time is have use to send some information one page to other page without data base connectivity
like:
1st page:
Session["valiable name"] = textbox1.Text;
2nd page:
Lable.Text = Session["valiable name"].ToString();

Related

Disadvantage of using session[""] in asp.net

In my project I use session to store user information ( username, password, personal image, and gender ) to be used in all pages of my project. I also use two other session to store small strings. Is there any disadvantage of using session ? also is there any risk of using session to store user password ?
Some things to take into account:
Don't store passwords. You should hash the incoming password, validate against the hash in your DB, and not hold on to it afterwards.
You should try to avoid using a write-access Session throughout the application, since you'll end up forcing asp.net to serialize incoming requests from the same session. Use read-only Session to avoid that. This could become apparent if you initiate multiple ajax calls simultaneously. More info here: https://connect.microsoft.com/VisualStudio/feedback/details/610820/session-based-asp-net-requests-are-serialized-and-processed-in-a-seemingly-inverse-order
Storing too much data in the Session could cause scalability issues, since all that information is held in memory on the server. If you switch over to SQL storage for sessions (common in webfarm/cloud deployments), then if the session is large every request on the server will have that Session data going back and forth between the server and the DB.
Content that goes into the session should be Serializable, just in case you decide to move over to a different persistent storage (such as sql server)
Using Sessions to retain information may not go well with stateless REST/WebApi endpoints (if you need to create any in the future)
Excessive use of Session for storage could make unit testing slightly more difficult (you will have to mock the Session)
By "personal image" I assume you are storing a url or such, and not an actual binary image. Avoid storing binary content. Only return the binary image file when the browser requests it, and don't store it in memory, the browser can cache that content easily.
You might also find the references linked in this answer to be useful in providing additional information: https://stackoverflow.com/a/15878291/1373170
The main problem with using Session and any machine depending properties is the scalability of the web site, so if you wanted to deploy your web site to a farm of servers then you can see the problem with depending on a machine state property since the request may be processed on different machines.
Hope that helps.

what are the alternatives of SESSION VARIABLES? [duplicate]

This question already has answers here:
ASP.NET Masters: What are the advantages / disadvantages of using Session variables?
(8 answers)
Closed 9 years ago.
What are the limitations of the session variable in developing large web application.
Also what are the best alternatives of the session variables.
Please provide me the alternatives of SESSION VARIABLES
To understand the advantages of not using sessions, you have to understand how sessions work.
In the default setup,
sessions are identified by a cookie set in the user's browser and
the session data is stored in-memory on the webserver
When the user sends a request to the server, the session cookie is sent along. It contains an identifier which the server uses to locate that particular user's session data.
You can configure ASP.NET to
use query parameters instead of cookies to store the session identifier
store the session data in a database (having a central data store for session data is particularly important if you have multiple servers serving your site)
Now for the advantages of disabling session state:
ASP.NET makes access to the session data thread-safe by serialising requests. This means that, when session state is enabled, ASP.NET refuses to serve concurrent requests from the same user. This is particularly an issue when the user's browser makes a lot of ajax requests. This problem can be mitigated by marking session state read-only for requests where you don't need to update it.
When the request comes in, ASP.NET has to fetch the session data, and it has to write data back when the request ends. This may not be a big issue if session state is stored in-memory, but if data is stored in a central database, this can cause serious performance problems.
Needless to say, these issues are exacerbated by storing large amounts of data for a large number of users.
For more information see
ASP.NET Session State Overview
Fast, Scalable, and Secure Session State Management for Your Web Applications
(that last article is a bit dated, but still a good read).
Alternatives
If you can, avoid session state altogether.
If you absolutely must associate data with the user, use the mechanisms of HTTP and make the browser carry the data in a cookie or perhaps a query parameter (this is partly what the whole REST-movement is about).
Hope this helps.
It depends upon the business logic of your application in some cases session may be the best choice , however there are lot of alternatives ,Session should be used if you are having different data for each request to your application ,you can post your data in hidden fields with your forms , but again ur question is a little bit of the track, You have to analyze your requirement than according to it you have to decide whether to use sessions or some other alternate solution , If I have to store id's of users than definitely I will go for sessions cause it will be different for each users , I would not keep very big data in session like keeping a dataset in session which few developers do . Then also questions comes if ur using session where u want to keep it in process or in server , if ur saving session in server it is very costly but in ssome scenarios its very useful .
Pros and Cons of Session Variables See Here
Since data in session state is stored in server memory, it is not advisable to use session state when working with large sum of data. Session state variable stays in memory until you destroy it, so too many variables in the memory effect performance.
Session variables and cookies are synonymous. So if a user has set his browser not to accept any cookies, your Session variables won't work for that particular web surfer!
An instance of each session variable is created when a user visits the page, and these variables persist for 20 minutes AFTER the user leaves the page! (Actually, these variables persist until they "timeout". This timeout length is set by the web server administrator. I have seen sites that the variables will collapse in as little as 3 minutes, and others that persist for 10, and still others that persist for the default 20 minutes. ) So, if you put any large objects in the Session (such as ADO recordsets, connections, etc.), you are asking for serious trouble! As the number of visitors increase, your server will experience dramatic performance woes by placing large objects in the Session!

Session State v ViewState

In our application, we have a "BasePage" that declares a number of properties to be used by more or less every page in the app.
Inside these properties, they write to ViewState. These are all typically an int or small string value, nothing huge. Typical use is call a web service and hold an id for use within the page, for example.
I've used viewstate since I'm wary of the loss of session variables should IIS recycle for example. Also, I figured, very small values would not add hugely to the page size.
Am I being overly paranoid about session though and would it have been a better option.
Our environment is a 2 server cluster with SSL termination on each server, sticky sessions maintained by the load balancer - so using In Proc is not a problem per say, I'm just very wary of it.
Never trust your user sent data.
Even all data you receive is not sensitive, if you send it to your user browser, you should to check it again before use it. Maybe most users are legitimate, but just one can break your application.
What are your options to store data?
Hidden field; can ve easily tampered at client side
Cookie; ancient method to keep user specific data, but very size limited.
ViewState; your data go to client and come back, using bandwidth and could be tampered.
Session, InProc; your never have problems, until a application pool get recycled
Session, State server; you keep your session data in another server process.
Session, database; can work with almost (if not all) load balance scenarios, as you dont need stick sessions, nor to worry with app pools recycling. All your data are belong to us your SQL Server.
Reading your scenario, you probably need to deal with out-of-process session storage.
I think it's best to avoid using Session state where possible, especially on a server cluster even if you are using sticky sessions. Sessions can expire, or disappear when IIS recycles (like you said).
I'd go with keeping the values in ViewState or a cookie.
If it is not sensitive data, I would also prefer to store it in the HTML rather than the session.

What to put in a session variable

I recently came across a ASP 1.1 web application that put a whole heap of stuff in the session variable - including all the DB data objects and even the DB connection object. It ends up being huge. When the web session times out (four hours after the user has finished using the application) sometimes their database transactions get rolled back. I'm assuming this is because the DB connection is not being closed properly when IIS kills the session.
Anyway, my question is what should be in the session variable? Clearly some things need to be in there. The user selects which plan they want to edit on the main screen, so the plan id goes into the session variable. Is it better to try and reduce the load on the DB by storing all the details about the user (and their manager etc.) and the plan they are editing in the session variable or should I try to minimise the stuff in the session variable and query the DB for everything I need in the Page_Load event?
This is pretty hard to answer because it's so application-specific, but here are a few guidelines I use:
Put as little as possible in the session.
User-specific selections that should only last during a given visit are a good choice
often, variables that need to be accessible to multiple pages throughout the user's visit to your site (to avoid passing them from page to page) are also good to put in the session.
From what little you've said about your application, I'd probably select your data from the db and try to find ways to minimize the impact of those queries instead of loading down the session.
Do not put database connection information in the session.
As far as caching, I'd avoid using the session for caching if possible -- you'll run into issues where someone else changes the data a user is using, plus you can't share the cached data between users. Use the ASP.NET Cache, or some other caching utility (like Memcached or Velocity).
As far as what should go in the session, anything that applies to all browser windows a user has open to your site (login, security settings, etc.) should be in the session. Things like what object is being viewed/edited should really be GET/POST variables passed around between the screens so a user can use multiple browser windows to work with your application (unless you'd like to prevent that).
DO NOT put UI objects in session.
beyond that, i'd say it varies. too much in session can slow you down if you aren't using the in process session because you are going to be serializing a lot + the speed of the provider. Cache and Session should be used sparingly and carefully. Don't just put in session because you can or is convenient. Sit down and analyze if it makes sense.
Ideally, the session in ASP should store the least amount of data that you can get away with. Storing a reference to any object that is holding system resources open (particularly a database connection) is a definite scalability killer. Also, storing uncommitted data in a session variable is just a bad idea in most cases. Overall it sounds like the current implementation is abusively using session objects to try and simulate a stateful application in a supposedly stateless environment.
Although it is much maligned, the ASP.NET model of managing state automatically through hidden fields should really eliminate the majority of the need to keep anything in session variables.
My rule of thumb is that the more scalable (in terms of users/hits) that the app needs to be, the less you can get away with using session state. There is, however, a trade-off. For web applications where the user is repeatedly accessing the same data and typically has a fairly long session per use of the site, some caching (if necessary in session objects) can actually help scalability by reducing the load on the DB server. The idea here is that it is much cheaper and less complex to farm the presentation layer than the back-end DB. Of course, with all things, this advice should be taken in moderation and doesn't apply in all situations, but for a fairly simple in-house CRUD app, it should serve you well.
A very similar question was asked regarding PHP sessions earlier. Basically, Sessions are a great place to store user-specific data that you need to access across several page loads. Sessions are NOT a great place to store database connection references; you'd be better to use some sort of connection pooling software or open/close your connection on each page load. As far as caching data in the session, this depends on how session data is being stored, how much security you need, and whether or not the data is specific to the user. A better bet would be to use something else for caching data.
storing navigation cues in sessions is tricky. The same user can have multiple windows open and then changes get propagated in a confusing manner. DB connections should definitely not be stored. ASP.NET maintains the connection pool for you, no need to resort to your own sorcery. If you need to cache stuff for short periods and the data set size is relatively small, look into ViewState as a possible option (at the cost of loading more bulk onto the page size)
A: Data that is only relative to one user. IE: a username, a user ID. At most an object representing a user. Sometimes URL-relative data (like where to take somebody) or an error message stack are useful to push into the session.
If you want to share stuff potentially between different users, use the Application store or the Cache. They're far superior.
Stephen,
Do you work for a company that starts with "I", that has a website that starts with "BC"? That sounds exactly like what I did when I first started developing in .net (and was young and stupid) -- I crammed everything I could think of in session and application. Needless to say, that was double-plus ungood.
In general, eschew session as much as possible. Certainly, non-serializable objects shouldn't be stored there (database connections and such), but even big, serializable objects shouldn't be either. You just don't want the overhead.
I would always keep very little information in session. Sessions use server memory resources which is expensive. Saving too many values in session increases the load on server and eventualy the performance of the site will go down. When you use load balance servers, usage of session can run into problems. So what I do is use minimal or no sessions, use cookies if the information is not very critical, use hidden fields more and database sessions.

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