what will happen after browser closing - asp.net

We know that when we closed the browser, session gets destroy.
Please help me with below query.
Lets say i have clicked on submit button on my registration page and internally it get called SQL store procedure, which takes more time to execute..
on same time if i closed the browse what will happen?
Does my sql connection still available ? if yes then after closing browser still my store procedure is in execute mode?
when exactly the session get destroy?
Would like to know more about this life cycle , Thanks

First have this in mind.
The session is connected with a cookie on the users browser.
The session have a time out.
If anything of this two gone, the session is gone, so let see them analytically.
Cookie
If the cookie is a session cookie (temporary), then is gone when the user close the browser, if its not temporary then is gone when it expires, or of course if the user clears it, or if the user is in private mode is not even saved.
So when the cookie that is connected with the session is gone, you lose the session
The session can be lost even if the browser is not been able to read the session cookie for other reasons.
Session Data on server
The session that is connected with the cookie, is a Dictionary of data that lives on server.
The session have a timeout, so if the user did not update the call to the server inside this time, the server kills the session data on server.
Also, note that the session can be served on the SQL Server, or in a service that runs on background and keeps that data in memory.
If you save the session data on the memory, then they can be lost even before the session times out, from IIS recycle, from the service itself that clears it for their reasons.
Server Side Time Out
If you call a long time function, and the users ends their connection, then the procedure will be continue to runs until either ends either gets a time out. This is not so safe if your process takes 10 minute to execute, you probably gets timeout and never ends correct, even if the user is still connected. If you talk for few seconds, then its relative ok, the procedure will executed even if the users close his browser side.
Check the time out of the page and the time out of the sql server side. If you end well with the user connected, you will end the same and if the user close their connection in the middle.
Have in mind that in a heavy multi user call situation you may have a problem from the session locks, read this q/a ASP.NET Server does not process pages asynchronously
So take care the procedure to not take more than few seconds.
Last words
The most "secure way" to not lost your session in a time period is to use well setup cookie, that is not temporary and keep their life for some months (google keeps their cookie for two years), and use SQL Server to saves your session data.
More details to read at:
ASP.NET State Management Recommendations
Session would not retain values and always return null
Keeping a related ASP.NET application's session alive from another ASP.NET application
ASP.NET Session State Overview

Related

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.

How do I keep TCP/IP socket open in IIS?

I have the following use scenario: User logs in to ASP.NET application; and at some point makes a connection to remote TCP/IP server. The server's response may come after significant delay (say, a few hours). Imagine that the user submits a batch job, and the job may be running for a long time. So, the user may close the browser, get some coffee and come back to see the results later.
However, if client closes the connection, the server will never return the results. So, keeping Socket info in Application object won't work - once user closes the browser, it goes away.
Is there any other way to persist this open socket while IIS is up? Also, if the second user logs in, I would prefer to use the same connection. Finally, I realize that the solution is brittle, and it may occasionally break. It's OK.
Remote server is 20-year old mainframe application; so no chance for changes there. And as long as the user doesn't log out - everything is working fine now. Everything is on the LAN, so there are no routing issues to complicate the situation.
The contents of the application dictionary are not lost when a user logs out. Your scheme will work (in a brittle way, but you say that's ok).
Note, that worker processes can exit for many reasons, so expect to be killed at arbitrary points in time.
you have several options for persisting session-state: MSDN - Session-State Modes
inproc mode: you disconnect, state is lost. if you use cookies, and
store info/data somewhere on the backend, then you can map the GUID
to the data, regardless of session. or use application-state.
stateserver: persisted across disconnects and application restarts,
but not across iis/pool/server restarts, unless you use another
server, or cookie/auth. can be problematic sometimes.
sqlserver: as the name implies, uses a specially formatted db/table structure to persist state data across all sorts of scenarios.
custom/off: allows you to build your own provider, or turns it off completely.
here's the cookie method, by far the simplest (you have to generate a GUID, then store it in the cookie and application state or a backend DB): MSDN - Maintaining Session State with Cookies
you can persist cookies on the user's client. then, on server
reboot/client disconnect/any other scenario just pull the GUID from
app/session state or from a backend DB, which will also store the data
for the reports/output.
also, as a caution: even though cookies can be used to auth a user to an account/db record via GUID, it is considered insecure for all other purposes except unindentifiable information, such as: view shopping cart, simple reports, status, etc...
oh, and the stuff on IIS session timeouts (20 mins by default): MSDN - Configure Session Time-out (IIS 7) and MSDN - Configure Idle Time-out Settings for an Application Pool (IIS 7)
completely forgot to add the links on: ASP.NET Application State Overview, ASP.NET Session State Overview, but storing large amounts of data on a busy server in application state is not recommended. oh yea, and MSDN - Caching Application Data

Finding time until timeout fires in asp.net

First of all, let me ask this:
Let's say that a web application has its timeout set to 10 minutes. For some reason, the user is idle. If he/she returns and press any key or moves the mouse, it resets the timeout? Or it is based on the last time it went to the server?
And now the second question: is there a way to find the time until the user gets logged off due to innactivity?
From MSDN:
The Timeout property specifies the time-out period assigned to the
Session object for the application, in minutes. If the user does not
refresh or request a page within the time-out period, the session
ends.
So in answer to your question, the timeout is reset if the user sends a request to the server by either navigating to another page or refreshing the current page (or possibly by using some form of AJAX keep-alive method (See this question)).
This article on Code Project provides a pretty good overview of Sessions within ASP.net
For your second question, this gets a little complex as the session timeouts are managed by IIS so your page has no idea how much longer the session will be valid for. I have seen examples where another timer is placed with in the page itself and when this reaches a certain low value the user is warned that their session is about to expire. The page could then refresh (resetting the session timeout value in IIS) and the user wouldn't be logged out / lose their session.
However, this will require the session timeout value that is configured is kept in sync with the value configured in the JavaScript function.

How does an ASP.NET session expire when the browser is closed?

As in the title, I wonder how a session expires when the client's browser is closed?
The session lives on the server. It expires when the browser is closed long enough or isn't used long enough or when a new request arrives that either doesn't contain the cookie, or the cookie refers to a sessionid that's too far in the past (default timeout is 20 minutes).
When there's no connection, the session is removed from memory at an undetermined moment in time, or when you programmatically call .Abandon on the session.
When a session is not available or a session has been cleared because it had timed out, a new session object will be created. When this is the result of a browser request, the Session_End event will trigger in the global.asax file.
Note: the actual way a session is timed out and cleared depends. I.e., inproc sessions will be destroyed and trigger a Session_Timeout. Out-of-proc sessions do not, and will be destroyed in a state server or an SQL server. In the latter case, a stored procedure is called regularly to clean up. The stored procedure is only called when there's activity on the server, which means that sessions can live longer than 20 minutes in (database) memory, but will be destroyed on next access.
As defined on the web server (e.g. IIS). The typical default is around 20 mins after the last access (i.e. web request for that session). At this point the session is cleared, so apps need to use either cookies or some server-side state to work out who someone is for return visits to make the experience seamless.
The browsers temporary cookies are deleted and the server kills the session data after a predetermined amount of time since last access.
It does and doesn't. It lives on on the server until it times out (usually 20 minutes). But since it's kept alive in the browser using a session cookie, that expires as the browser is closed, the user will not be able to reconnect to that session again.

Basic: How is the session id created?

Does IIS create the session id when a request is received and where is that saved (client or server)?
How does server recognize that the request is coming from the same user/session?
The answer to your first question is Yes -- if sessions are used, and Both.
A cookie is a short bit of text passed back and forth between client and server with every request/response.
IIS generates a session id, saves it, and any associated data, and passes the in a cookie to the client (browser).
When the client makes another request, it sends the cookie, containing the sessionID back to the server. The server can then look at the cookie and find the session (and the associated data) which is saved on the server.
In ASP.net, there are multiple places for the session to be saved, but it's always within the server infrastructure.
The default is the memory of the IIS Process. This means: if you reset IIS (or the whole PC) or even just the application pool within IIS, all sessions are deleted, and the session data is lost forever. Also, if you have a LOT of sessions and store a lot of data in each session, the process will require a lot of memory, which can be a problem. This is called "In-Proc" Sessions.
The main alternative is a SQL Server Database. That way, sessions are kept even after a restart and it does not really matter how large each session is. The main downside is the added latency: Fetching data from a database is slower that the In-Proc solution of course.
There are also some other methods how to store sessions (including the option to write a completely new session provider), but the two common ones are "The Memory of the Server" and "A MS SQL Database".

Resources