473,399 Members | 2,858 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

C# .Net Web - Session Variable Not Persisting

Hi, I'm having problems with a DataTable I'm storing in a session variable. I use this as a temporary store for a shopping cart until a customer goes through the checkout and the cart is saved to my database.

I have used DataTables stored in sessions before for shopping baskets with no problems. However, on this occasion I am only passing the AddHandler the product id and the quantity being added. The Handler then calls a getProductDetail method to lookup the product name & price from the database. The handler then passes these details to the AddToDataTable method to add a new row to the DataTable stored in the session.

For some reason the process of retrieving data from the database seems to be killing the session variable. Meaning everytime I add an item to the DataTable the previous item(s) already in the basket are lost and only the most recent item added appears.

I can't for the life of me figure out what is wrong. If I call the AddToDataTable method directly then everything works fine and multiple rows can be added to the TempBasket.

Here my code. Hopefullly someone can point out some stupid mistake I have made. I really need to get this working ASAP as I'm working to a deadline.

Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="C#" Debug="true" %>
  2. <%@ import Namespace="System" %>
  3. <%@ import Namespace="System.Data" %>
  4. <%@ import Namespace="System.Data.OleDb" %>
  5.  
  6.  
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  8.  
  9. <script runat="server">
  10.  
  11.     void bindTempBasket()
  12.     {
  13.         DataTable dtTempBasket = mGetTempBasket();
  14.  
  15.         dgDebugTableDisplay.DataSource = dtTempBasket;
  16.         dgDebugTableDisplay.DataBind();
  17.     }
  18.  
  19.     public DataTable mGetDataTable(string sSQL)
  20.     {
  21.         string sCString = ConfigurationSettings.AppSettings["ConnectionString"];
  22.         using (OleDbConnection myConnection = new OleDbConnection(sCString))
  23.         {
  24.             OleDbCommand myCommand = new OleDbCommand(sSQL, myConnection);
  25.             OleDbDataAdapter myAdapter = new OleDbDataAdapter(myCommand);
  26.             DataTable dtTable = new DataTable("Table");
  27.             myAdapter.Fill(dtTable);
  28.  
  29.             return dtTable;
  30.         }
  31.  
  32.     } //End mGetDataTable method
  33.  
  34.  
  35.     public DataTable mGetProductDetails(int iID)
  36.     {
  37.         string sSQL = "SELECT PVariant_ID, Product_Name, Product_TradeCost FROM qryProductList WHERE PVariant_ID = " + iID + ";";
  38.         DataTable dtProductDetails = mGetDataTable(sSQL);
  39.  
  40.         return dtProductDetails;
  41.     } //End mGetProductDetails method
  42.  
  43.  
  44.     public DataTable mCreateTempBasketTable()
  45.     {
  46.         DataTable myTable = new DataTable("Basket");
  47.         DataColumn dtCol;
  48.  
  49.         dtCol = new DataColumn();
  50.         dtCol.DataType = System.Type.GetType("System.Int32");
  51.         dtCol.ColumnName = "PVariant_ID";
  52.         myTable.Columns.Add(dtCol);
  53.  
  54.         dtCol = new DataColumn();
  55.         dtCol.DataType = System.Type.GetType("System.String");
  56.         dtCol.ColumnName = "Product_Name";
  57.         myTable.Columns.Add(dtCol);
  58.  
  59.         dtCol = new DataColumn();
  60.         dtCol.DataType = System.Type.GetType("System.Int32");
  61.         dtCol.ColumnName = "IOrderLine_Quantity";
  62.         myTable.Columns.Add(dtCol);
  63.  
  64.         dtCol = new DataColumn();
  65.         dtCol.DataType = System.Type.GetType("System.Double");
  66.         dtCol.ColumnName = "IOrderLine_UnitCost";
  67.         myTable.Columns.Add(dtCol);
  68.  
  69.         DataColumn[] myPrimaryKeyColumns = new DataColumn[1];
  70.         myPrimaryKeyColumns[0] = myTable.Columns["PVariant_ID"];
  71.         myTable.PrimaryKey = myPrimaryKeyColumns;
  72.  
  73.         return myTable;
  74.     }//End createBasketTable Method
  75.  
  76.     public DataTable mGetTempBasket()
  77.     {
  78.         if (Session["basket"] == null)
  79.         {
  80.             DataTable dtBasket = mCreateTempBasketTable();
  81.             Session["basket"] = dtBasket;
  82.         }
  83.         return (DataTable)Session["basket"];
  84.     }//End mGetBasket Menthod
  85.  
  86.     public void mSaveTempBasket(DataTable newTable)
  87.     {
  88.         Session["basket"] = newTable;
  89.     }
  90.  
  91.     void mAddHandler(int iID, int iQuantity)
  92.     {
  93.         DataTable dtProductDetail = mGetProductDetails(iID);
  94.  
  95.         if (dtProductDetail.Rows.Count > 0)
  96.         {
  97.             int iPVariant_ID = Convert.ToInt32(dtProductDetail.Rows[0]["PVariant_ID"]);
  98.             string sProduct_Name = Convert.ToString(dtProductDetail.Rows[0]["Product_Name"]);
  99.             double dUnitCost = Convert.ToDouble(dtProductDetail.Rows[0]["Product_TradeCost"]);
  100.  
  101.             mAddToDataTable(iPVariant_ID, sProduct_Name, iQuantity, dUnitCost);
  102.         }
  103.     }
  104.  
  105.     void mAddToDataTable(int iID, string sProductName, int iQuantity, double dUnitCost)
  106.     {
  107.         DataTable dtBasket = mGetTempBasket();
  108.         DataRow dtRow;
  109.         dtRow = dtBasket.NewRow();
  110.         dtRow["PVariant_ID"] = iID;
  111.         dtRow["Product_Name"] = sProductName;
  112.         dtRow["IOrderLine_Quantity"] = iQuantity;
  113.         dtRow["IOrderLine_UnitCost"] = dUnitCost;
  114.         dtBasket.Rows.Add(dtRow);
  115.  
  116.         mSaveTempBasket(dtBasket);
  117.     }
  118.  
  119.     void AddItem_Click(object sender, EventArgs e)
  120.     {
  121.         //Temp method for debug
  122.  
  123.         int iID = Convert.ToInt32(ItemCode.Text);
  124.  
  125.         //mAddToDataTable(iID, "Test Product Name", 1, "", 99.99);
  126.  
  127.         mAddHandler(iID, 1);
  128.  
  129.         bindTempBasket();
  130.     }
  131. </script>
  132.  
  133. <html xmlns="http://www.w3.org/1999/xhtml" >
  134. <head runat="server">
  135.     <title>Product Search</title>
  136.     <link rel="Stylesheet" href="CSS/default.css" />
  137. </head>
  138. <body>
  139.     <form id="form1" runat="server">
  140.  
  141.     <asp:TextBox ID="ItemCode" runat="server"></asp:TextBox>
  142.         <asp:Button ID="AddItem"
  143.         runat="server" Text="Button" onclick="AddItem_Click" />
  144. <asp:datagrid id="dgDebugTableDisplay" runat="server" />
  145.  
  146.  
  147.     </form>
  148. </body>
  149. </html>
  150.  
I am happy to upload the backend access database this page uses if someone wants to test the code.

Thanks in advance for any help that can offered.
Mar 27 '08 #1
7 2666
Plater
7,872 Expert 4TB
I would wonder if you could print out the session ID to the page (for debug purposes) and see if it ever changes.
That is what it is sounding like to me, that for some reason your browser is not correctly maintaining the session cookie id, and thus everytime you load, a new session id is generated?
Mar 27 '08 #2
Hi Plater, what do you mean by print out the Session ID? How would I do that?

What ever the problem it happens in both IE and FF on 4 different computers I've tried.

I have been using the VS2008 built in test server. After I couldnt get it to work their I tried uploading it to our webserver to test if it was some problem with VS2008 losing the session. It worked on the server for an hour and then stopped working their as well, even though I hadn't changed the file?

Very strange!

Ideally I'd like to fix the code I have but if there is some other method of temporily storing the datatable I'd try it. I'd like to avoid storing the temp basket in the database though.
Mar 28 '08 #3
Plater
7,872 Expert 4TB
Are you using the default Session style (and not trying to use a SQL server instance for Session State)?
Is there anywhere where you are Abandon()'ing the Session?
Is it even possible to string-serialize the DataTable object with Data in it?

Session.LCID returns the unique Session ID that gets passed around.
Session.IsNewSession will tell you if this page load is of a new session.
Mar 28 '08 #4
I am using the default session variable and I am not abandoning the session at any point.

I tried using ViewState instead of a Session which worked on the first page. But the problem is I need to use the DataTable on a second page (popup) and can't access the ViewState on the opener page.

I tried just using a Session briefly to take the content of the ViewState["TempBasket"] and pass it to the ViewState on the popup page. This made everything work for a bried period but not it stopped working again.

It driving me insane. Is there some other way to store a DataTable but also allows it to be passed between pages?
Mar 30 '08 #5
balabaster
797 Expert 512MB
It almost sounds like you want to restructure your site slightly. Use master pages, store your basket in the master frame and then use content pages to update and manage the basket. Should bypass the issue of needing to pass the basket between pages.
Mar 31 '08 #6
Plater
7,872 Expert 4TB
I had no trouble making a DataTable persist through Session?

I put this on my default page.
Expand|Select|Wrap|Line Numbers
  1. DataTable tempdt;
  2. if (Session["temptable"] == null)
  3. {
  4.     tempdt = new DataTable("Barny");
  5.     tempdt.Columns.Add("Page");
  6.     tempdt.Columns.Add("Hits");
  7.     DataRow dr = tempdt.NewRow();
  8.     dr["Page"] = "Default";
  9.     dr["Hits"] = 1;
  10.     tempdt.Rows.Add(dr);
  11.     Session.Add("temptable", tempdt);
  12. }
  13. else
  14. {
  15.     tempdt = (DataTable)Session["temptable"];
  16.     foreach (DataRow d in tempdt.Select("Page='Default'"))
  17.     {
  18.         int h = int.Parse(d["Hits"].ToString());
  19.         h++;
  20.         d["Hits"] = h;
  21.         Session["temptable"] = tempdt;
  22.     }
  23. }
  24.  
Everytime the page is loaded it will increment (or create if first time) a value and then update it in the object.
Then on a different page I have it displaying the contents of the Session object.

Something like:
Expand|Select|Wrap|Line Numbers
  1. DataTable tempdt;
  2. string n = "";
  3. if (Session["temptable"] == null)
  4. {
  5.     n = "(Empty)";
  6. }
  7. else
  8. {
  9.     tempdt = (DataTable)Session["temptable"];
  10.     foreach (DataRow d in tempdt.Rows)
  11.     {
  12.         n+="'"+d["Page"].ToString()+"' : "+d["Hits"].ToString()+"</br>\r\n";
  13.     }
  14. }
  15. myLabel.Text = n;
  16.  
Mar 31 '08 #7
Session in .net suck, you have to be extremely careful, and yes they are kinda buggy in my opinion.
  • You should check iis settings, maybe theres a problem there.
  • Check Session timeout.
  • Try something else

By trying something else, you should consider the fact that saving a whole shopping cart in session can also be e memory problem for the server if there are a lot of users this can be a problem. and your current issue. i think you should consider using a temporary table in the database, containing maybe a list of userid and the product id.

anyways its just a suggestion, since u seem to be out of time, this can be a fast solution.
Mar 31 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Jim Douglas | last post by:
I am starting the analysis and design on how we are going to handle session data. We are on a large web-farm which limits our solutions. The best solution is persisting to MS SQLServer but I'm not...
5
by: PJ | last post by:
I posted a few days ago concerning requests being blocked from a main window after a popup window had initiated a file download. Apparently this has to do with the fact that asp.net or iis...
5
by: Marc Rivait | last post by:
Here is a very interesting scenario. I have a simple test application that loads a page and sets a session variable on the load event. On the first page there is a link to a second page. The...
7
by: Seth | last post by:
I have noticed that the id of my session object changes when I switch from a non-secure to a secure connection. What I'm trying to do: I have a cookie that is built on the non-secure side of...
4
by: Amy | last post by:
I'm having a problem with clearing my session variables. I'm using session variables to pass data from a web form to a pdf generator. The problem comes in when a user goes back to the original...
4
by: c676228 | last post by:
Hi all, In the second web form, I have the following code: (The peopleinfo is a user control which has name and ssn infomation, each field in this user control I have set enableviewstate=true). I...
4
by: Sam | last post by:
I have an asp.net 2.0 app that uses a sitemap, Master Page, and has several content pages. While this feature has simplified the process of creating a data-driven site menu, it does seem to have...
9
by: Garry Jones | last post by:
Elsewhere on a form page I am declaring a variable ******************************* session_start(); $_SESSION = "sometext"; At the top of the page that will process the form code I have this...
1
by: Andy | last post by:
I want to store a key in an ASP.NET session variable that points to an ASP.NET page cache. The page cache contains an XML document that holds a draft of the user's work. After the user is...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.