[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 774
  • Last Modified:

VERY: URGENT Session_End()

within my c# Global.asax.cs file i am trying to use the following when the website is closed down by the browser ie site exited, session closed

protected void Session_End(Object sender, EventArgs e)
{
      string guidstr = HttpContext.Current.Session.SessionID;
      Lookb4.data.Removesession(guidstr);
}

the above code should be firing a void called Removesession which removes a record from a db, but it never gets fired

How do i remove the record which was inserted during the Session_Start eventI am doing this as i am required to track details about who is currently on line and what they are viewing which is all data held within the Session.

Thanks in advance from a programmer who is going to get his ass kicked shortly if i dont sort this one out!!
Chris
0
Robinsonx6
Asked:
Robinsonx6
  • 17
  • 10
  • 7
  • +1
2 Solutions
 
Robinsonx6Author Commented:
thought id post the Removesession code to help!

            public static void Removesession(string sessid)
            {
                  System.Data.OleDb.OleDbDataAdapter DASession = new System.Data.OleDb.OleDbDataAdapter();
                  System.Data.OleDb.OleDbCommand DeleteCmd = new System.Data.OleDb.OleDbCommand();

                  DeleteCmd.Connection=new System.Data.OleDb.OleDbConnection(connString());
                  DeleteCmd.CommandType=System.Data.CommandType.Text;

                  DeleteCmd.CommandText = "DELETE FROM [Session] WHERE SessionGUID ='" + sessid + "';";
      
                  DASession.DeleteCommand = DeleteCmd;

                  try
                  {
                        DeleteCmd.Connection.Open();
                        DeleteCmd.ExecuteNonQuery();
                  }
                  catch(System.Data.OleDb.OleDbException ex)
                  {
                        System.Web.HttpContext.Current.Response.Write(ex.Message + " " + ex.Source.ToString());
                  }
                  finally
                  {
                        DeleteCmd.Connection.Close();
                  }
            }
0
 
mmarinovCommented:
Hi Robinsonx6,

1. how do you end the session?
2. Try to see if you do not do anything with the browser and the session time out is exceed if the Session_Onend wil fires
3. if you try to end the session when the user close the browser window - then hmm.. the Session_OnEnd is not fired at all :( you have to forcly do it by adding client script to your page that will executed onunload event of the body - there you have to submit the page and kill the session - so the Session_OnEnd fires

Regards!
B..M
mmarinov
0
 
Robinsonx6Author Commented:
thanks for that do you happen to have the client script to kill the session when the browser is closed by the user or when the user leaves our web site to navigate to another

Thanks
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
mmarinovCommented:
Robinsonx6,

check this thread : http://forums.aspfree.com/t4345/s.html

Regards!
B..M
mmarinov
0
 
ryerrasCommented:
Robin,
 Session_End event is not fired until the session timeout is expired. It has no idea, if the user closed the browser or did anything. Remember, browser is a client side object. So, if your session timeout is 20 minutes, Session_End fires only after 20 minutes of idle time. Or you have to call Session.Abandon in  your code behind, which will call the Session_End event. But, to handle browser closing, all you can do is pick an optimum timeout, so that the session is not alive for too long. Remember Session is a server side object, you can not manipulate it on the client, without posting back to server.
0
 
Robinsonx6Author Commented:
oh but will my remove code work once the session times out
0
 
ryerrasCommented:
yup. Anything in the Session_End executes after the Session timeout
0
 
Robinsonx6Author Commented:
in my Session_End code i am using the HttpContext.Current.Session.SessionID to delete the correct record from the database is this value going to be null or is it going to be the value of the closing session?

this could explain why my records are not being deleted
0
 
mmarinovCommented:
Robinsonx6,

it should be null, because the session has been killed already


Regards!
B..M
mmarinov
0
 
ryerrasCommented:
Robin
HttpContext is not available in the Session_End. Remember HttpContext is associated with a http request. Session_End is not associated with any http request.

But, you can catch the id of the session when it starts and store it in a public class variable, then supply it to the Session_End event.

mmarinov, as far as I know, Session is still available in Session_End. Its killed completely only after the event is executed. You could still access some session variable values in Session_End event. I tried it. The Session seem to be still alive in the Session_End event. May be its killed completely only after its execution
0
 
mmarinovCommented:
ryerras,

yes, you are correct
Robinsonx6, sorry for the error

Regards!
B..M
mmarinov
0
 
Robinsonx6Author Commented:
ok so i will store the session id in a static variable within my main class then reference this within my remove record void?????? i hope it doesnt destroy the class before it references the variable?
0
 
ihenryCommented:

Global class in Global.asax.cs inherits from HttpApplication, it has public property named Session so you still can use Session.SessionID in Session_End event.
0
 
Robinsonx6Author Commented:
this wouldnt explain why the record isnt being removed, are you sure its not returning a null SessionID, its hard to test as the breakpoints arnt accessible in the Session_End void!!
0
 
ihenryCommented:

ryerras has explained very well about my previous post. Sorry I didn't read carefully all the posts.
0
 
mmarinovCommented:
Robinsonx6,

what do you mean that breakpoints are not accessible ? they are - just wait until the timeout of session expired

Regards!
B..M
mmarinov
0
 
Robinsonx6Author Commented:
oh ok didnt realise that ill set my timeout to a very low value then for testing, sorry
0
 
ihenryCommented:

:o) Well, to help you to force timeout your page when user close their browser you can try this code.

<HTML>
      <HEAD>
            <title>page2</title>
                  <script language="javascript">
                  <!--
                  function signOutPage()
                  {
                        window.open( "signOut.aspx", "signOff", "menubar=0,resizable=0,toolbar=0,status=1", "");
                  }
                  // -->
                  </script>

      </HEAD>
      <body onunload="signOutPage();">
      </body>
</HTML>

In the signOut.aspx Page_Load event call Session.Abandon()

private void Page_Load(object sender, System.EventArgs e)
{
      Response.Write( String.Format("User with SessionID {0} has been successfully logged out.", Session.SessionID) );
      if (!Page.IsPostBack) Session.Abandon();
}
0
 
ryerrasCommented:
Robin,
 No the class is never destroyed. You could use the static variable.

Global.asax.cs inherits from HttpApplication. This has nothing to do with HttpContext. HttpApplication stores the information about Application, such as Application state. HttpContext is for individual http requests. So, dont be confused between these two.
0
 
ihenryCommented:
One discussion about force session timeout using onunload javascript event.
close browser
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_21142400.html

and when user is leaving their browser too long you can try code from this PAQ
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21104330.html
0
 
Robinsonx6Author Commented:
looking into all this at the moment
0
 
ihenryCommented:

My links and sample code just to trigger Session_Event event when user close the browser or leaving  it too long. But to make sure your session data that's stored in db is removed completely you can't use HttpContext.Current as it returns null when use in Session_Event. Use Session.SessionID instead, that should work.

protected void Session_End(Object sender, EventArgs e)
{
     string guidstr = Session.SessionID;
     Lookb4.data.Removesession(guidstr);
}
0
 
Robinsonx6Author Commented:
this is intersting if i put a breakpoint on the first line of code

string guidstr = Session.SessionID;

the breakpoint works but if i put it on the line of code which calls the Removesession void it doesnt

cant i link to a void during the Session_End
0
 
ryerrasCommented:
Yup henry is right. Your sessionId is still available. Robin, here I would like to add. Session timeout is not the amount of idle. Its the time between the postbacks. If your user is active on your webform and doing some client side stuff, but 20 minutes passed by since the last request to the server, even in that case session gets expired. You should remember that. Most of the people think session timeout is the amount of idle time. Its the minimum time between http requests to the server
0
 
ryerrasCommented:
The break point works even for a void returning method. You can put whatever in the session_end, and it gets executed as usual
0
 
ihenryCommented:

Are you sure Session_End event has only the two lines in your code? Try to debug by putting them in try catch block and see what's the error message.

try
{
      string guidstr = Session.SessionID;
      Lookb4.data.Removesession(guidstr);
}
catch (Exception ex)
{
      string s = ex.Message;
}

Note: any error message occurs in Session_Event will be thrown up to no where.
0
 
Robinsonx6Author Commented:
this is messed up im just going to do a re-boot and try again as it just seems to stop running the code for no reason, sorry about this guys
0
 
Robinsonx6Author Commented:
ok guys i have changed my code as listed below and the catch (System.exception) is returning the following message

      exc.Message      "Format of the initialization string does not conform to the OLE DB specification.  Starting around char[0] in the connection string."      string

Please explain as this connection string works fine in the rest of the site!

Code:

            System.Data.OleDb.OleDbCommand DeleteCmd = new System.Data.OleDb.OleDbCommand();
            try
            {
            string guidstr = Session.SessionID;

            System.Data.OleDb.OleDbDataAdapter DASession = new System.Data.OleDb.OleDbDataAdapter();
                  

            DeleteCmd.Connection = new System.Data.OleDb.OleDbConnection();
            DeleteCmd.Connection.ConnectionString="C:\\Inetpub\\www\\onsite_lookb4\\database\\LookB4.mdb"; // this is where the error is comming from
            DeleteCmd.CommandType=System.Data.CommandType.Text;

            DeleteCmd.CommandText = "DELETE FROM [Session] WHERE SessionGUID ='" + guidstr + "';";
      
            DASession.DeleteCommand = DeleteCmd;


            DeleteCmd.Connection.Open();
            DeleteCmd.ExecuteNonQuery();
            }
            catch(System.Data.OleDb.OleDbException ex)
            {
                  string s = ex.Message + " " + ex.Source.ToString();
                  System.Web.HttpContext.Current.Response.Write(s);
            }
            catch(System.Exception exc)
            {
                  string s = exc.Message + " " + exc.Source.ToString();
                  System.Web.HttpContext.Current.Response.Write(s);
            }
            finally
            {
                  DeleteCmd.Connection.Close();
            }
0
 
Robinsonx6Author Commented:
oooppppssss,, sory guys ive found the problem with the connstring, i wasnt paying atention and forgot the important bit.

Just trying the client script by lhenry, then i should be complete,
0
 
ihenryCommented:

aha..now the real problem came out to surface..

use either of these connection string

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;User Id=admin;Password=;

or

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;Jet OLEDB:Database Password=MyDbPassword;
0
 
Robinsonx6Author Commented:
hia ihenry, thanks i sorted the conn string bit, it was me being stupid, too many hours staring at code does it to a man :-)

Trying your code for the log off forcing timeout , shortly will let you know how it goes.

thanks
0
 
ihenryCommented:

:0) that happen to the best of us. hows the problem?
0
 
Robinsonx6Author Commented:
yeah hav not forgoten about this, just got pulled off things yesturday for meetings, but my head is still connected to my body, so no big problems :-)

Will be sorting this out once i have completed some documentation
0
 
Robinsonx6Author Commented:
Hi ihenry Can i do your suugestion without opening a new window, i think it might anoy our clients or can i close the window onse the code has been performed?

if so how do i close the current window with c#
0
 
Robinsonx6Author Commented:
cant i close the seesion within the javascript instead of opening a new window?

sorry im not a java man!
0
 
ryerrasCommented:
Session can not be closed in javascript. YOu have to go to server to close the session. Or simply wait until the timeout, for your code in the session_end to execute. I am not sure if you want to postback to server when the user clicks the close button, that will annoy them more than another window
0
 
ihenryCommented:

Like ryerras said, no.
You can't end a asp.net session from client-side code and you can't close client browser from server-side code. Having another window opens after close one browser is annoying really, but sometimes it depends how you present that to your user. You can have the new window open big,  obvious, ugly and irritating. Or make its size small or even almost invisible to the user so that the annoyance can be kept as minimum as possible. But your main problem is when the user have installed "Popup blocker" in their machine as there's nothing you can do with it.

So do we come to a conclusion that session timeout is the only option? I guess not, I believe many options are still available. But I do agree rely on session timeout would be quickest way. Just make sure your code that responds to Session_End event has no flaw which can cause any error and prevents the event raises gracefully.
0
 
ihenryCommented:

Forgot to mention, you can make the new window open to close itself. Anyway, popup blocker will prevent that from opening.
0
 
Robinsonx6Author Commented:
thankyou for your time, patience and help, i have learned a lot, thank you

regards
chris
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 17
  • 10
  • 7
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now