ethem
ethem

Reputation: 2908

session variables lost for some reason

I try to setup a E-shop. Next to every item I've an asp:imagebutton when this imagebutton is clicked I'm checking whehter the session varialbe session["basket"] exists or not if not then I add the values in a list (entity class) and I add this list in the session.

if the session is not empty then I retrieve the values from session into List and change the list and then add the list back to session.

Issue:

For some reason I loose the session variable, suddenly. I checked on my watch (time) and it's unpredicatble sometimes it takes less than 1 minute, sometimes 3 minutes and sometimes 5 minutes etc....

why do I loose the session variable?

I googled and I've found - it can happen if you use Response.Redirect - w/o false parameter, or if you're in an UpdatePanel etc.

I'm loosing the variable in the same page for the moment.

The whole idea is put in a session variable and do checkout and retrieve the session variable in second aspx page... but this is not always working, because most of the case the session variables becomes empty. And sometimes it works.

can someone advice ? what and where do I need to check? In some website pages (google) they advice to use caching, but caching is application based, so everybody will retrieve the same value.

In my page any user (authenticated or anynomous user) in other words any user without login should able to order (I'll send invoice to pay upfront)....

I''m not using webfarm, nor web garden... I just checked the IIS - website - session state - It's in process, cookie settings = use cookies, name = asp.net_sessionid, time-out = 20....

please advice?

It's C#, ASPX 3.5, IIS7.5

I DON't have PAGE_LOAD in my ASPX page.

// the only place I put the sessoin=null is a linkbutton, for the rest I don't put null in session["basket"]....

protected void lnkDeleteAllSelected_Click(object sender, EventArgs e)
    {
        Session["Basket"] = null;
        ReloadBasketItems();

    }

 protected override void OnInit(EventArgs e)
    {

        base.OnInit(e);
        //System.Diagnostics.Debugger.Break();

        lvJuridisch.ItemDataBound += new EventHandler<ListViewItemEventArgs>(this.lv_ItemDataBound);
        lvJuridisch.DataBound += new EventHandler(lv_DataBound);

    }

imgButtonAddtoBasket -> is defined as asp:imagebutton in the asp:listview

 protected void imgButtonAddtoBasket_Click(object sender, ImageClickEventArgs e)
    {
        ListViewDataItem lvi = ((sender as ImageButton).NamingContainer) as ListViewDataItem;
        DataKey currentDataKey = (lvi.NamingContainer as ListView).DataKeys[lvi.DataItemIndex];
        WebShopInfo SingleItem = new WebShopInfo();
        SingleItem.cd_type_pub = currentDataKey[0].ToString();
        SingleItem.no_pub = currentDataKey[1].ToString();
        SingleItem.no_suite_pub = Convert.ToInt32(currentDataKey[2]);
        SingleItem.cd_langue = Convert.ToChar(currentDataKey[3]);
        SingleItem.lb_titre_red = (lvi.FindControl("HiddenfieldProductRed") as HiddenField).Value;

        SingleItem.m_price = Convert.ToDecimal((lvi.FindControl("hiddenField_M_Price") as HiddenField).Value);
        SingleItem.nm_price = Convert.ToDecimal((lvi.FindControl("hiddenField_NM_Price") as HiddenField).Value);
        SingleItem.mt_pourc_tva = Convert.ToDecimal((lvi.FindControl("hfBTW") as HiddenField).Value);


        List<WebShopInfo> lws = new List<WebShopInfo>();
        if (Session["Basket"] == null)
        {

            //Session is empty so add listview to the session....
            //Session.Timeout = 20;  -- I tried this but this is not working too...
            lws.Add(SingleItem);
            Session["Basket"] = lws;
        }
        else
        {
            //Session is not empty so get asp:listview from the session.
            lws = Session["Basket"] as List<WebShopInfo>;

            WebShopInfo wsi = lws.Where(a => a.cd_type_pub == SingleItem.cd_type_pub &&
                                            a.no_pub == SingleItem.no_pub &&
                                            a.no_suite_pub == SingleItem.no_suite_pub &&
                                            a.cd_langue == SingleItem.cd_langue).SingleOrDefault<WebShopInfo>();
            if (wsi != null)
                lws.Remove(wsi);

            if (SingleItem.Count > 0)
                lws.Add(SingleItem);
            Session["Basket"] = lws;
        }

        ReloadBasketItems();
    }

Upvotes: 3

Views: 29236

Answers (5)

James McCormack
James McCormack

Reputation: 9944

Sounds like your appdomain is being recycled. Is your web.config compilation element set in debug mode? In debug mode, ASP.NET resets the appdomain every 15 dynamic compilations. When that happens, if your sessions are stored in memory (InProc mode - the default), they'll be lost.

FYI, a dynamic compilation will occur whenever a file change happens on your site, like you editing an ASPX file, or an image being generated, or a web.config change.

So either put the site into Release mode (<compilation debug="false" ... />), or increase the numRecompilesBeforeAppRestart value from 15 in web.config, or use a non-volatile session storage mode - e.g. SQL Session State.

Upvotes: 6

sll
sll

Reputation: 62494

Check out whether you are using Application Pool which is shared across multiple web sites/applications, if you are sharing the same AppPool with an other web application/site - switch to separate AppPool.

The best way is to use server-based session state, in this case you can forget about such issues. See HOW TO: Configure SQL Server to Store ASP.NET Session State

Upvotes: 0

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

you will be surprised to know the behind the scene the session uses the cache!

have a look at the below(you will find all the common problem about session issue):

http://mmtripathi.blogspot.com/2008/09/session-lost-problem-after.html

http://zeeshanumardotnet.blogspot.com/2009/07/why-sessions-are-terminatedloss.html

http://classicasp.aspfaq.com/general/why-won-t-my-session-variables-stick.html

Upvotes: 3

davecoulter
davecoulter

Reputation: 1826

mesut:

Honestly Session memory can be very volitile. If the application goes down you can loose it, or like you said, if the user's session gets restarted you can loose it. Generally the options for Asp.Net are to store data in:

  • ViewState (stored as encrypted text accessable by your code-behind)

  • Session Memory (essentially a dictionary, but as above, a little
    volatile)

  • ASP.Net's State Service (which stores the values in a separate process. watch out for server farm scenarios)

  • Cookies

  • Cache

  • Url Parameters

Each of these methods has a trade-off in terms of performance, memory, or being dependent on a user's environment. I would try a different method and see if that is more robust for you.

Upvotes: 2

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

Are you losing just that particular variable? - If so, then it is probably some part of your code that is doing this.

If you are losing the entire session object, then unless your session has timed out, the other reason is that if you are using inproc session state at your server and ran out of memory - this recycles your worker process causing you to lose the session value. Check your event log to see if this is the case.

Upvotes: 3

Related Questions