Solved

Deleting Session Objects when user leaves a particular asp.net page. Unload? Dispose?

Posted on 2004-08-18
12
5,427 Views
Last Modified: 2008-01-09
When a user visits one of my pages in my web application I create several objects and save them in session. These objects or only used for this particular page. The problem is, if a user leaves this page and comes back, the page loads the information from the session. What I want to do is delete those objects I created in session for this page when the user leaves. There are a couple of exit points for the page. I tried the following, but it seemed to fire the event with each post back (Dispose method).

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            public override void Dispose()
            {
                  // DELETE SESSION OBJECT HERE <------------
                                                // SEEMS TO FIRE WITH EACH POSTBACK
                  if(Session["dsSuggest"] != null)
                  {
                        Session.Remove("dsSuggest");
                  }
                  base.Dispose ();
            }

            private void InitializeComponent()
            {    
                  this.btnUpdateIdea.Click += new System.EventHandler(this.btnUpdateIdea_Click);
                  this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
                  this.Load += new System.EventHandler(this.Page_Load);
            }
            #endregion


Is there an event I can call that gets called only once when the user navigates to another page (will unload work?)? Please post example code.
Thank You.
0
Comment
Question by:douglashammon
  • 4
  • 4
  • 3
  • +1
12 Comments
 
LVL 18

Expert Comment

by:DotNetLover_Baan
ID: 11837513
Hi there, try to use Page_Unload event.

    Private Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Unload
        Session.Abandon();   //This will clear all the session variables.
    End Sub
0
 
LVL 21

Expert Comment

by:tovvenki
ID: 11838383
Hi,
try this
if(Session["dsSuggest"] != null)
               {
                    Session.Remove("dsSuggest");
               }

when you are moving to other pages for e.g before a redirect call.

How do you move to the other pages?

Regards,
venki
0
 
LVL 8

Accepted Solution

by:
shovavnik earned 350 total points
ID: 11840929
You can also try clearing the session before the inital load of the page:

.. Page_Load() {
  if( !IsPostBack ) {
     Session.Remove("dsSuggest"); // or Abandon(), or Clear().
  }
}
0
 
LVL 8

Expert Comment

by:shovavnik
ID: 11840947
I forgot to mention, this way you ensure the session is cleared before you use it initially, but can still use it for postbacks.

Even if you clear the session on Page_Unload, you should verify the session is cleared as I mentioned when the page is called.
0
 

Author Comment

by:douglashammon
ID: 11843499
Thanks for the responses.

DotNetLover_Baan :
I tried the Page_UnLoad, but it fires every postback. I registered the event in the InitializeComponent() method like this:

this.Unload += new System.EventHandler(this.Page_UnLoad);

 I only want the event to fire once, when the user leaves the page.


tovvenki:
There are a couple of buttons that redirect the user and a dropdown menu with several links to other pages. I could call a function to clear the session before each redirect, but it seems to me there is has to be a better way, and if the user clicked on one of the dropdown menu links the session objects would still be there.

shovavnik:
Would there be any benefit to always deleting the session objects after leaving the page, like server resources? A user does not always come back to the page. I use the session a lot for things like paging, storing the logged in user’s information, tree view navigation, etc. I thought if I could delete the session objects I user for each page when a user leaves that would save on server resources.  

Thank you for your replies.
Does anybody know why the unload event is fired every postback? Is there an event I can use that ONLY gets fired when a user leaves a particular page?
shovavnik is the closest one to coming up with a workable solution, but I would like to know if anybody can tell me of an event I can use instead of the Page_Load? Please continue submitting ideas!
0
 
LVL 18

Expert Comment

by:DotNetLover_Baan
ID: 11844466
>>"user leaves the page"<< that means the page is Unloading. Even if you do Response.Redirect()... it will unload the current page and load the redirected page.
Not clear what is ur goal.... what do you mean by "user leaves the page" ?

-Baan
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:douglashammon
ID: 11844788
Hi Bann,

>>"user leaves the page">> User leaves the current page and visits a different page, in other words: if the user is currently viewing “submitIdea.aspx” and then visits “viewMyIdeas.aspx”. The page unload is triggered every postback, so my session objects are deleted every time the user does something on the page that causes a postback(clicks a button). I want the session objects to be deleted only when the user leaves the current page and views other.

I have increased the points! I really need a good solution for this problem.

-Douglas H.
0
 
LVL 18

Expert Comment

by:DotNetLover_Baan
ID: 11844910
ok. now it's clear to me...
hmm... you can clear the session variables in other page's load event.... I don't see any other way.
0
 
LVL 8

Expert Comment

by:shovavnik
ID: 11846916
Obviously if you can delete the session when the user leaves the page, you'll conserve some system resources.  It's really a question of concurrency: how many concurrent users is the system designed to support?  15? 100? 10000?  It's a big difference and can affect the desig.  For example, if you're using hosting services, like AccuWebHosting or the like, you'll want to make an extra effort to keep things clean, but if you're building an in house solution and you control the server "strength", then you may reach the conclusion that the extra cpu time the server spends cleaning the session is more expensive than the amount of memory the open sessions cosume.

Basically, I've never found a need to maintain a pure clean session.  The reason is that the server and the client are disconnected, which inevitably means that the user's next action is always unpredictable.  This is why you have so many options for temporary storage (Cache, ViewState, Session, Application, and others) - so you can find the method that best suits your needs.  Note that they all expose a very similar interface even though they specialize to a certain extent, so you just have to weight the advatnages of the storage system, and not its ease of use.

One way to avoid needing to clear the session, is not to use it.  You can use the ViewState for example, which is optimal for small data, like sorting and paging info (sort columns and order, page number, etc).  The session is generally better suited for stuff that should not be accessible by the user directly (for security reasons) or needs to be accessible from multiple pages (like the user id or login state or global default settings for the user).

If you do want to use the session to store this info, then you need to ensure it's cleared on the initial call to the page using the Page.IsPostBack property.  You don't *have* to clear it, because the session always has a timeout and the server process will eventually clear the session anyway.  To minimze overhead, you can reduce the timeout and put small data in the session.  Avoid putting whole datasets in the session (or in the viewstate, for that matter).  If you need to persist large data, usually the best solutions are to use a database and a file system, where the file system ca be used to cache results.

Say, for example you have a datagrid that binds to a DataTable whose data is retrieved from the db.  If the user want to change the sort order, you can persist the sort columns and page numbers to the viewstate and store the datatable to a file using serialization.  On page load, you check if this is a post back, and if so, you attempt to deserialize.  No session.  Minimal overhead.  The price is that you need space for the files and deserialization from the file system is more expensive than deserialization from the session.
0
 

Author Comment

by:douglashammon
ID: 11856151
shovavnik:
Thanks for your feedback. Interesting Information. Could you post a couple of links for more information about de-serialization and using the file system for temporary storage? How do you keep track of each user if you use the file system and not the session? Thanks again for the info.

Is there an event I can catch when a user leaves a particular page?

If nobody can answer this in a couple more days, I will probably award shovavnik the points, as clearing the session variables on page_load is the only solution I can find. If there is an event I can catch, that would be great to know.

-Douglas H.
0
 
LVL 8

Expert Comment

by:shovavnik
ID: 11858765
I don't know of any event that will help you, and I think is precisely because the user's actions are inevitably unpredictable.  Consider for example, that using certain browsers, it's possible to browse using the same session in two different browser windows.  One window could remain on the old page, and the second could be somewhere else.  You'd have no way to know if the user left the page.

This is one reason why a session timeout exists.

As for links, serialization is a very big topic.  Some starter links:

You can find a bunch of code examples (from the mouth of *god*, no less :)), for xml serialization:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconanexampleofxmlserializationwithxmlserializer.asp
The first example is for serializing a dataset.  Note that the StreamWriter used in the example can be pretty much any type of stream (Memory, File, whatever).

A more detailed explanation of serialization (topic heading):
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconSerialization.asp
Note that the Framework has builtin Binary Serialization, which makes more compact serialized files, except for datasets which always serialize to xml.

As for keeping track of users using the file system, I don't know of any links off hand, as I pretty much figure it out as I went along.  There are two basic things to keep in mind:
1. Make sure the files are secure, and not accessible at all via the web.  That is, either don't put them under wwwroot or whereever your application is, or make sure the path is only accessible via special permissions (maybe impersonalization, but you'll have to look that up).
2. Define some way to specify unique file names.  For example, in a reporting system I developed, I found that I needed 2 separate pieces of information to create the cached files.  I needed both the user id and the report id.  So I would name the files "report_{userid}_{reportid}.dat".
You can even zip the files (I used SharpZipLib with BZip2 compression) to conserve hard disk space (which was necessary for me because datasets always serialize to xml which is wasteful and I was limited in hard disk space).  If security is a big issue, you can hash the file name.

Another way to this is to create random file names and store a filename to user mapping in the database.  I found that I didn't need that level of security, and the whole point was to avoid calling the database when unnecessary (even if the call is lighter).
0
 

Author Comment

by:douglashammon
ID: 11859386
Thanks shovavnik.

0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now