What is the difference between Session.Abandon() and Session.Clear() - asp.net

What is the difference between destroying a session and removing its values? Can you please provide an example demonstrating this?
I searched for this question, but don't grasp total answer. Some answers are:
Session.Abandon() destroys the session
Session.Clear() just removes all values
A friend told me this:
Clearing the session will not unset
the session, it still exists with the
same ID for the user but with the
values simply cleared.
Abandon will destroy the session
completely, meaning that you need to
begin a new session before you can
store any more values in the session
for that user.
The below code works and doesn't throw any exceptions.
Session.Abandon();
Session["tempKey1"] = "tempValue1";
When you Abandon() a Session, you (or
rather the user) will get a new
SessionId
When I test Session, it doesn't makes any change when I Abandon the session.
I just find one difference:
session.Abandon() raises Session_End event

Clear - Removes all keys and values from the session-state collection.
Abandon - removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out.
It also raises events like Session_End.
Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.
You say:
When I test Session, it doesn't makes any change when I Abandon the session.
This is correct while you are doing it within one request only.
On the next request the session will be different. But the session ID can be reused so that the id will remain the same.
If you will use Session.Clear you will have the same session in many requests.
Generally, in most cases you need to use Session.Clear.
You can use Session.Abandon if you are sure the user is going to leave your site.
So back to the differences:
Abandon raises Session_End request.
Clear removes items immidiately, Abandon does not.
Abandon releases the SessionState object and its items so it can ba garbage collected to free the resources. Clear keeps SessionState and resources associated with it.

When you Abandon() a Session, you (or rather the user) will get a new SessionId (on the next request).
When you Clear() a Session, all stored values are removed, but the SessionId stays intact.

This is sort of covered by the various responses above, but the first time I read this article I missed an important fact, which led to a minor bug in my code...
Session.Clear() will CLEAR the values of all the keys but will NOT cause the session end event to fire.
Session.Abandon() will NOT clear the values on the current request. IF another page is requested, the values will be gone for that one. However, abandon WILL throw the event.
So, in my case (and perhaps in yours?), I needed Clear() followed by Abandon().

this code works and dont throw any exception:
Session.Abandon();
Session["tempKey1"] = "tempValue1";
It's because when the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.
<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>
If you access the variable MyName on a subsequent Web page, it is empty. This is because MyName was destroyed with the previous Session object when the page containing the previous example finished processing.
from MSDN Session.Abandon

Session.Abandon()
will destroy/kill the entire session.
Session.Clear()
removes/clears the session data (i.e. the keys and values from the current session) but the session will be alive.
Compare to Session.Abandon() method, Session.Clear() doesn't create the new session, it just make all variables in the session to NULL.
Session ID will remain same in both the cases, as long as the browser is not closed.
Session.RemoveAll()
It removes all keys and values from the session-state collection.
Session.Remove()
It deletes an item from the session-state collection.
Session.RemoveAt()
It deletes an item at a specified index from the session-state collection.
Session.TimeOut()
This property specifies the time-out period assigned to the Session object for the application. (the time will be specified in minutes).
If the user does not refresh or request a page within the time-out period, then the session ends.

Clearing a session removes the values that were stored there, but you still can add new ones there. After destroying the session you cannot add new values there.

clear-its remove key or values from session state collection..
abandon-its remove or deleted session objects from session..

Existence of sessionid can cause the session fixation attack that is one of the point in PCI compliance. To remove the sessionid and overcome the session fixation attack, read this solution - How to avoid the Session fixation vulnerability in ASP.NET?.

I think it would be handy to use Session.Clear() rather than using Session.Abandon().
Because the values still exist in session after calling later but are removed after calling the former.

this code works and dont throw any exception:
Session.Abandon();
Session["tempKey1"] = "tempValue1";
One thing to note here that Session.Clear remove items immediately but Session.Abandon marks the session to be abandoned at the end of the current request. That simply means that suppose you tried to access value in code just after the session.abandon command was executed, it will be still there. So do not get confused if your code is just not working even after issuing session.abandon command and immediately doing some logic with the session.

Related

distinguish between session timeout and session explicit (programmatic) invalidation

I have an HttpSessionListener. Is there a way, inside its sessionDestroyed method to distinguish between the following cases:
the session was destroyed because the session-timeout configured in the web.xml was exceeded
the session was destroyed programmatically by the the application calling HttpSession#invalidate
My use case is that I have a Single Sign On (SSO) arrangement between a number of applications and I want a global single sign off when one of the applications participating in the SSO arrangement explicitly logs off but not when its session times out, hence the need to distinguish between the two cases. I guess a way would be for the application to set some flag in the session object just prior to calling HttpSession#invalidate. The HttpSessionListener would then examine the session object and if that flag is found it would know this was a programmatic logout. If not, it was a container logout. Would that make sense and / or is there a better way?
You can use HttpSession#getLastAccessedTime() to obtain the timestamp of the last request sent by the client associated with the session. Then you can just do the math with help of HttpSession#getMaxInactiveInterval() and the current timestamp.
long lastAccessedTime = session.getLastAccessedTime();
long timeoutInMillis = TimeUnit.SECONDS.toMillis(session.getMaxInactiveInterval());
long now = System.currentTimeMillis();
boolean sessionHasBeenTimedout = (now - timeoutInMillis > lastAccessedTime);
// ...

Asp .net session variables update by thread is not getting reflected in Session

In my page1.aspx i am generating a report from database by using thread.
//on button click
Hashtable ht = (Hashtable)Session["ReportParam"];
ReportThreadClass rth = new ReportThreadClass(ht);
Thread thread = new System.Threading.ThreadStart(rth .Run);
thread.Start();
In my thread class's rum method i am updating values in Hashtable that how many pages i have created.
//in thread' method
public virtual void Run()
{
int pagecount=0;
while(done)
{
//loading data from DB and generating html pages
ht["Total_Pages"] = pagecount;
}
}
At my Page2.aspx i am reading values from Session Variable
Hashtable ht = (Hashtable)Session["ReportParam"];
int TotalPages = (int) ht["Total_Pages"];
When i run above code in InProc mode every thing is working fine i am getting updated values from session.
Because every thing is stored in static variable, and ht is referenced by Session so it automatically get updated in session (HashTable not needed to reassign it to session back).
But when i run code in State server (OutProc mode) It need to store session data in different process by Serializing Hash-table.
But the value of Total_Pages is not getting updated in Page2.aspx even after Thread run completely.
So is there any event or method which get fired to store all updates in session variable to State-Server , if yes then pls tell me . if not then pls suggest me some idea to get updated value in page2.aspx.
I would explictely SET and GET SessionState like so:
In your thread Run
// no complex object like hastable, just a plain value...
Session["pageCount"] = pageCount;
In your page2.apsx:
var pageCount = (int) Session["pageCount"]??0;
The reason your report thread is not updating it's session value when using out-of-proc sessionstate is because the session has no way to detect the hashtable has a changed value, therefor it doesn't update the underlying storew with the serialized version of the hastable. When you explicity store one immutable object it will persist one it's value changed;
As the session might already be gone when your thread finishes a begtter option is to get hold of a reference to SqlSessionStateStore and call SetAndReleaseItemExclusive. Ultimately you might want to have an overloaded SessionStateProvider that can handle your scenario.
In Out Proc Mode Session is saved after some event so if your thread is updating your session variables then it won't persist in storage.
If u are using Inproc Mode then session store in Static Dictionary so if your thread updating it, u will get updated value to any page.
So u have two solutions for this situation
Use inProc mode
Maintain a dictionary in your thread class with key as Session id and value is your hash-table, So if page2.aspx wants to read value of hash-table then it will pass his session id to method and which will return required value.
Less efficient but I'd probably just ping the database for the page count on Page2.
Or create a separate session value for the page count on Page1, at the same time as doing everything else. (EDIT: Nevermind the second part, that's what Rene suggested below).

Session in asp.net/c#

I would like to know the difference between
Session.clear();
Session.Abandon();
Session.RemoveAll();
Please explain the difference I'm struggling with my session sign out.
Thank you in anticipation
Session.Clear() removes all the content from the Object (values). The session with the same key is still alive.
Session.Abandon() destroys the session and the Session_OnEnd event is triggered. If you use this you will lose session and get a new session key. Consider using this with a "log out"
Session.RemoveAll() like Clear() this method deletes all items that have been added to the Session object's Contents collection.
Clear() and RemoveAll() perform the same thing: remove the session variables
but keep the current session in memory. Whereas, Abandon() ends the current
session.

ASP.NET session object lifetime pessimistic assumption !

I check a session object and if it does exist then call another method which would use that object indirectly. Although the second method would access this object in a few nanoseconds I was thinking of a situation when the object exactly expires between two calls. Does Session object extends its lifetime on every read access from code for preventing such a problem ? If not how to solve the problem ?
If you are going to say why I don't pass the retrieved object from first method to second one, this is because I pass the ASP.NET Page object which carries many other parameters inside it to second method and if I try to pass each of them separately, there would be many parameters while I just pass one Page object now.
Don't worry, this won't happen
If I understand your situation it works sort of this way:
Access a certain page
If session is active it immediately redirects to the second page or executes a certain method on the first page.
Second page/method uses session
You're afraid that session will expire between execution of the first and second method/page.
Basically this is impossible since your session timer was reset when just before the first page starts processing. So if the first page had active session then your second page/method will have it as well (as long as processing finishes before 20 minutes - default session timeout duration).
How is Session processed
Session is processed by means of an HTTP Module that runs on every request and before page starts processing. This explains the behaviour. If you're not familiar with HTTP Modules, then I suggest you read a bit about IHttpModule interface.
It's quite difficult to understand your question, IMHO, but I will try.
From what I understand, you're doing something like:
string helloWorld = string.Empty;
if (this.Session["myObject"] == null)
{
// The object was removed from the session or the session expired.
helloWorld = this.CreateNewMyObject();
}
else
{
// Session still exists.
helloWorld = this.Session["myObject"].ToString(); // <- What if the session expired just now?
}
or
// What if the session existed here...
if (this.Session["myObject"] == null)
{
this.Session["myObject"] = this.CreateNewMyObject();
}
// ... but expired just there?
string helloWorld = this.Session["myObject"].ToString();
I thought that Session object is managed by the same thread as the page request, which would mean that it is safe to check if object exists, than use it without a try/catch.
I were wrong:
For Cache objects you have to be aware of the fact that you’re dealing essentially with an object accessed across multiple threads
Source: ASP.NET Cache and Session State Storage
I were also wrong about not reading to carefully the answer by Robert Koritnik, which, in fact, clearly answers the question.
In fact, you are warned about the fact that an object might be removed during page request. But since Session lifespan relies on page requests, it would mean that you must take in account the removal of session variables only if your request takes longer than the session timeout (see How is Session processed in the answer by Robert Koritnik).
Of course, such situation is very rare. But if in your case, you are pretty sure that the page request can take longer than 20 minutes (default session timeout), than yes, you must take in account that an object may be removed after you've checked if it exists, but before you really use it.
In this situation, you can obviously increment the session timeout, or use try/catch when accessing the session objects. But IMHO, if the page request takes dozens of minutes, you must consider other alternatives, as Windows services, to do the work.
I'm having difficulties understanding what the problem here is but let me try it again referring to thread safety.
Thread safety issue
If this is a thread safety issue, you can always issue a lock when creating a certain session object so other parallel requests won't run into a problem by double creating your object.
if (obj == null)
{
lock (objLock)
{
if (obj == null)
{
obj = GenerateYourObject();
}
}
}
Check lock documentation on MSDN if you've never used it before. And don't forget to check other web resources as well.

Make a final call to the Database when user leaves website (ASPX)?

I have a system set up to lock certain content in a database table so only one user can edit that content at a time. Easy enough and that part is working fine. But now I'm at a road block of how to send a request to "unlock" the content. I have the stored procedure to unlock the content, but how/where would I call it when the user just closes their browser?
You also can't know when the user turns off his computer. You have to do it the other way around.
Require that the lock be renewed periodically. Only the web site would do the periodic renewal. If the user stops using the web site, then the lock expires.
Otherwise, require the user to explicitly unlock the content. Other users who want to edit the content can then go yell at the first user when they can't do their jobs. Not a technological solution, but still a good one. Shame works.
The best thing you can really do is add something to your Session_End in your global.asax. Unfortunately, this won't fire until the session times out.
When the user clicks the "X" in their browser, there isn't anyway to guarantee the browser will send you anything back.
A quick note on the Session_End approaches. If you use this method, then you have to ensure
That sessionstate is InProc, eg. add something like this to your Web.config
<sessionState mode="InProc" timeout="timeout_in_minutes"/>
Make sure that you've setup IIS as to not recycle worker processes during normal operation (see for instance this blog post).
Edit:
Not directly answering the question directly, but another approach would be to use Optimistic concurrency control on the data in question.
There is such event as "user closes browser".
Nevertheless, I can think of two workarounds:
Use Javascript/Ajax to permanently
(lets say every 10 seconds) call a
method in your page. The DateTime of
your last query needs to be stored
somewhere. Now you write a windows
service that checks every second
which session are timed out. Perform
your custom action there.
Use the global.asax Session_End()
-Event. (cannot be used with every SessionState, look up for which ones
it is usable)
Trying to leave a stackoverflow answer page pops up an "are you sure" dialog. Perhaps during the on-page-leave event that SO uses (or however SO does this), you can send a final request with an XmlHttpRequest object. This won't cover if the browser process closes unexpectedly (use session_onend for that), but it will at least send the "I'm closed" event earlier
I think your one stored procedure can do the locking and unlocking (used with "Select #strNewMax As NewMax")...
Here is an example from a system I have:
Declare #strNewMax Char
Select #strNewMax = 'N'
BEGIN TRANSACTION
/* Lock only the rows for this Item ID, and hold those locks throughout the transaction. */
If #BidAmount > (Select Max(AB_Bid_AMT) from AuctionBid With(updlock, holdlock) Where AB_AI_ID = #AuctionItemId)
Begin
Insert Into AuctionBid (AB_AI_ID, AB_Bid_AMT, AB_Emp_ID, AB_Entry_DTM)
Select #AuctionItemId, #BidAmount, #EmployeeId, GetDate()
Select #strNewMax = 'Y'
End
COMMIT TRANSACTION
Select #strNewMax As NewMax
This will insert a record as the next highest bid, all while locking the entire table, so no other bids are processed at the same time. It will return either a 'Y' or 'N' depending on if it worked or not.
Maybe you can take this and adjust it to fit your application.

Resources