we can write code by which we can kill session when user click on log out button or click on close button of browser but some time user may go to another site from my site or suddenly browser crash and close and some time power cut so machine close. how to handle this kind of situation and kill session for that particular user. what would be the best strategy for session management for big portal.i will be glad if any experience developer gude me how to kill unused session and also guide me for best strategy & session management for big portal. thanks
Personally I wouldn't worry about these situations and rather let IIS handle the session and when it times out.
You can alter this in your Web.Config file and change the <sessionState> timeout property.
<sessionState timeout="10">
http://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.90).aspx
http://technet.microsoft.com/en-us/library/cc725820(v=ws.10).aspx
You can use Session.Abandon() method to kill session, but it is very hard way to catch when user leave you site. One of the best way is send client request on document.unload event.
Related
I am trying to "log" forcefully when a user has been inactive and or the session has ended (either by inactivity or more importantly, when the browser has closed).
I dont want to use any silly AJAX solution to perform a post every few minutes for "im alive" or call when the browser is closed.
I was under the impression that if you store an object in Session, and you reach the Session_End event, then you will not be able to gain access to anything stored in Session as its ended.
But from some testing I have done, it appears that this is probably the last chance you can obtain access to the object.
Could this be true? is it reliable?
using ASP.NET 4.0 here.
Typically there are two things done.
The first is that a javascript timer is added to the client, not as a heartbeat, but rather as a reminder. If they are close to the session ending, then it simply says "session is about to end. Are you still there?" If so, then it does the "silly" post to ensure the server keeps the session going. This is purely to be nice to your users.
The second (and point of your question) is that you put something in session_end in order to clean up the session. Reliable? well.. most of the time.
Session_End won't run if the app pool is recycled. However, assuming the app pool is ok then yes it will execute when the session expires. The app pool can be recycled for a LOT of reasons ranging from the app crashing to exceeded memory usage to simply because it's been a while since the last reset. This is configurable in IIS.
Would I trust session_end? No. Not 100%. Of course, I wouldn't put anything inside of a session object that would require me to trust it 100% anyway.
For logging the timeout You can use the Global events to log at timeout. See this link for order of events http://www.techrepublic.com/article/working-with-the-aspnet-globalasax-file/5771721
Is there a way to do a Session.Abandon() when the user just kills the session by X'ing out with the little red X box in the upper right corner? I am seeing situations where after an "X out", the user comes back in and it seems like session variables are still present? I guess explorer keeps them intact? (I am unsure of this).
You can try doing an AJAX type callback in the OnUnload event - however, as someone else mentioned you'd have to be aware of other tabs being open (not easy), and it still won't guarantee you get that event.
There's a combination of things to do to get a similar type of effect.
Session Cookie should have a null/empty expiry time. This ensures the browser deletes the session from it's end after the browser is closed.
The ASP Session can be set with a short SessionState timeout value. This means if there's no client activity within that period, the Session will expire.
The side effect of this is that if a user is just looking at the site, and not performing activity (regardless of whether the browser is still open) - the session can expire.
This can be worked-around by having a Javascript timer periodically ping back to the server with an AJAX call or similar. The side effect of THIS is that it generates more site traffic.
The server is typically not aware of such events on the client. The only way the server can be notified about anything is if there is a request sent back to it. I guess you could create such a notification in a JavaScript, but then you should also keep in mind that the session in mind that the session is not per-page but (usually) per user, which means that you would need to keep track of how many tabs/windows the user has opened so that you don't kill the session when you should not.
Personally, I usually try to design the web apps so that they live well with the default handling of sessions, either providing a specific "Logout" command that will kill the session, or simply let it hit the timeout and die.
I have a problem of the session not expiring. Here is my case
I have a application in asp.net1.1. i am able to handle session when user click logout button. Session is active for 35 minutes. the application is also check if same user is trying to login using multiple machine and blocks it.
Now this application is deployed in city where there is power outage. When user is loggd in and light goes off, the session remain open. Due to this, the user is not able to log in again for next 35 minutes from alternate machine.
Can you tell solution of how to handle issue of session remained open the right way?
Did you write the code that if a session already exists, refuse another login? If so, you will probably have to change it. It is more common to kill the old session and start a new one if necessary. I prefer to allow multiple sessions for a single user unless there is some specific security requirement not too.
Lookup the SessionState timeout field in Web.config.
Best solution is to add UPS to the client workstations so they don't lose the connection if the power goes out. The only other option I can think of in this situation is to add something to the login code which, instead of blocking an alternate location login, instead forces the other session to be expired on a successful login.
We solved some similar issue this way:
in the body of the asp.net page, we attach on the onload event an ajax call. In this ajax call, the session timeout is set to 35 mins.
Also an ajax call is attached to the onunload, where we set the session timeout to 1 min.
This way the user has 35 min timeout when using the application, yet has 1 minute timeout when closing the application.
I have a web page where the user select a Company and with that I keep the Company name in memory though a Session but when I go to the next page the Session only last like 5 minutes?
Any reason why and how I can fix this, I did extend the Session state in the Web.config but that did not work.
Example: Session("CompanyName") = "Bytes Technology"
In my web.config I have:
timeout="40" />
I move from Default.aspx to CompanyDetail.aspx with my Session("CompanyName")
But if I let the program idle in CompanyDetail.aspx I lose the Session State.
Any ideas?
Regards
Etienne
from your comment I see that you think your site is in a load-balancing server farm.
in this case you need to store your session in db or avoid using it: you cannot be sure that the same server will serve the same user each time he does a postback, and if the user goes from server "A" to server "B" in two different posts... your session variables are lost.
try a google search for "sessionstate database", you'll find tons of stuff on this.
hope this helps
andrea
some questions:
the timeout time is always the same? 5 minutes?
is your site running in a load-balancing server farm? with more than one front-end server?
what are you telling in your web.confing regarding sessions and sessionstate?
I'd wager your not using a load-balanced farm, and are actually using shared hosting.
In a load balanced farm, your code is deployed to multiple servers, and if you have sticky sessions disabled, the user will utilize the server with the least load on each request.
Since you are using 3rd party hosting, I heavily doubt you are doing that.
Session timeout can be hardset in IIS by the host provider, and the most likely culprit is that they have set this to 5 minutes.
Call your host provider, ask them what their IIS session settings are, and go from there.
In IIS, go into the properties of your website, click to the Home Directory tab and then click the Configuration button. Here, click the options tab and check the Session timeout there. I'm pretty sure this only effects classic ASP, but I'm not 100% sure.
If this happens always at 5 minutes then check web.config for session settings, and check IIS: website/Properties/ASP.NET, click on Edit Configuration, select State Management tab, and check session settings.
could there be some antivirus on the server that's causing the web app to reset itself every 5 minutes, with the ASP.NET runtime thinking either the binaries or the web.config has changed? that is also possible.
Another idea is to put the machine name into a comment on a page and see if that is changing from page to page just to confirm that there is a changing of the server handling the request.
thank you everyone for all the information. The company hosting my site just extended the time of the application pool and that worked!
Thanks
Etienne
http://www.erate.co.za
I decided to scrap using Session Variables and went with Query Strings!! Much better!!
By default the session expiry seems to be 20 minutes.
Update: I do not want the session to expire until the browser is closed.
Update2: This is my scenario. User logs into site. Plays around the site. Leaves computer to go for a shower (>20 mins ;)). Comes back to computer and should be able to play around. He closes browser, which deletes session cookie. The next time he comes to the site from a new browser instance, he would need to login again.
In PHP I can set session.cookie_lifetime in php.ini to zero to achieve this.
If you want to extend the session beyond 20 minutes, you change the default using the IIS admin or you can set it in the web.config file. For example, to set the timeout to 60 minutes in web.config:
<configuration>
<system.web>
<sessionState timeout="60" />
... other elements omitted ...
</system.web>
... other elements omitted ....
</configuration>
You can do the same for a particular user in code with:
Session.Timeout = 60
Whichever method you choose, you can change the timeout to whatever value you think is reasonable to allow your users to do other things and still maintain their session.
There are downsides of course: for the user, there is the possible security issue of leaving their browser unattended and having it still logged in when someone else starts to use it. For you there is the issue of memory usage on the server - the longer sessions last, the more memory you'll be using at any one time. Whether or not that matters depends on the load on your server.
If you don't want to guesstimate a reasonable extended timeout, you'll need to use one of the other techniques already suggested, requiring some JavaScript running in the browser to ping the server periodically and/or abandon the session when a page is unloaded (provided the user isn't going to another page on your site, of course).
You could set a short session timeout (eg 5 mins) and then get the page to poll the server periodically, either by using Javascript to fire an XmlHttpRequest every 2 minutes, or by having a hidden iframe which points to a page which refreshes itself every 2 minutes.
Once the browser closes, the session would timeout pretty quickly afterwards as there would be nothing to keep it alive.
This is not a new problem, there are several scenarios that must be handled if you want to catch all the ways a session can end, here are general examples of some of them:
The browser instance or tab is closed.
User navigates away from your website using the same browser instance or tab.
The users loses their connection to the internet (this could include power loss to user's computer or any other means).
User walks away from the computer (or in some other way stops interacting with your site).
The server loses power/reboots.
The first two items must be handled by the client sending information to the server, generally you would use javascript to navigate to a logout page that quickly expires the session.
The third and fourth items are normally handled by setting the session state timeout (it can be any amount of time). The amount of time you use is based on finding a value that allows the users to use your site without overwhelming the server. A very rough rule of thumb could be 30 minutes plus or minus 10 minutes. However the appropriate value would probably have to be the subject of another post.
The fifth item is handled based on how you are storing your sessions. Sessions stored in-state will not survive a reboot since they are in the computer's ram. Sessions stored in a db or cookie would survive the reboot. You could handle this as you see fit.
In my limited experience when this issue has come up before, it's been determined that just setting the session timeout to an acceptable value is all that's needed. However it can be done.
This is default. When you have a session, it stores the session in a "Session Cookie", which is automatically deleted when the browser is closed.
If you want to have the session between 2 browser session, you have to set the Cookie.Expired to a date in the feature.
Because the session you talk about is stored by the server, and not the client you can't do what you want.
But consider not using ASP.NET server side session, and instead only rely on cookies.
Unfortunately due to the explicit nature of the web and the fact there is no permanent link between a website server and a users browser it is impossible to tell when a user has closed their browser. There are events and JavaScript which you can implement (e.g. onunload) which you can use to place calls back to the server which in turn could 'kill' a session - Session.Abandon();
You can set the timeout length of a session within the web.config, remember this timeout is based on the time since the last call to the server was placed by the users browser.
Browser timedout did not added.
There's no way to explicitly clear the session if you don't communicate in some way between the client and the server at the point of window closing, so I would expect sending a special URI request to clear the session at the point of receiving a window close message.
My Javascript is not good enough to give you the actual instructions to do that; sorry :(
You cant, as you can't control how the html client response.
Actually why you need to do so? As long as no one can pick up the session to use again, it would expire after that 20 minutes. If resources does matter, set a more aggressive session expiry (most hosting companies did that, which is horribly annoying) or use less objects in session. Try to avoid any kind of object, instead just store the keys for retrieving them, that is a very important design as it helps you to scale your session to a state server when you get big.
Correct me if I am misreading the intent of your question, but the underlying question seems to be less about how to force the session to end when a user closes the browser and more about how to prevent a session from ending until the browser is closed.
I think the real answer to this is to re-evaluate what you are using sessions to do. If you are using them to maintain state, I agree with the other responses that you may be out of luck.
However, a preferred approach is to use a persistent state mechanism with the same scope as the browser session such as a cookie that expires when the browser is closed. That cookie could contain just enough information to re-initiate the session on the server if it has expired since the last request. Combined with a relatively short (5-10 min) session timeout, I think this gives you the best balance between server resource usage and not making the user continually "re-boot" the site.
Oh you have rewritten the question.
That one is absolutely feasible, as long as javascript is alive. Use any timed ajax will do. Check with prototype library http://www.prototypejs.org PeriodicalExecutor or jQuery with the ajax + timer plugin. Setup a dummy page which your executor will call from time to time, so your session is always alive unless if he logouts (kill the ajax timer in the same time) or close browser (which means the executor is killed anyway)