Unable to serialize the session state - asp.net

i am tired wondering the issue for this problem. have read so many blogs and forums for this but i am not able to find out the problem.
I am using "SQLServer" mode to store session.
Everything is working fine. But whenever i use search function in my website, it throws the below error:
"Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode."
I am assuming that this is because of the paging code i have used on that page. That code is as below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select xxxxqueryxxxx";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
try
{
using (con)
{
con.Open();
da.Fill(ds);
}
}
catch
{
ds = null;
}
finally
{
if (ds != null)
{
CustomPaging page = new CustomPaging();
DataTable dt = ds.Tables[0];
page.PageSize = 10;
page.DataSource = dt;
page.CurrentPageIndex = 0;
no = 1;
Session["DT"] = dt;
Session["page"] = page;
bindData(page, dt);
//set these properties for multi columns in datalist
DataList2.RepeatColumns = 1;
DataList2.RepeatDirection = RepeatDirection.Horizontal;
}
}
}
}
void bindData(CustomPaging page, DataTable dt)
{
try
{
DataList2.DataSource = page.DoPaging;
DataList2.DataBind();
//DataList2.DataSource = SqlDataSource1;
//DataList2.DataBind();
lbtnPre.Enabled = !page.IsFirstPage; //Enable / Disable Navigation Button
// lbtnPre.CssClass = "disabledbtn";
lbtnNext.Enabled = !page.IsLastPage;
//lbtnNext.CssClass = "disabledbtn";
lblStatus.Text = NavigationIndicator(); //Build Navigation Indicator
//for creating page index
DataTable dt1 = new DataTable();
dt1.Columns.Add("PageIndex");
dt1.Columns.Add("PageText");
for (int i = 0; i < page.PageCount; i++)
{
DataRow dr = dt1.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt1.Rows.Add(dr);
}
dlPaging.DataSource = dt1;
dlPaging.DataBind();
dlPaging.RepeatColumns = 10;
dlPaging.RepeatDirection = RepeatDirection.Horizontal;
}
catch (Exception)
{
}
finally
{
page = null;
}
}
string NavigationIndicator()
{
string str = string.Empty; //Page x Of Y
str = Convert.ToString(((CustomPaging)Session["page"]).CurrentPageIndex + 1) + " of " + ((CustomPaging)Session["PAGE"]).PageCount.ToString() + " Page(s) found";
return str;
}
protected void lbtnPre_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsFirstPage)
//Decrements the pageIndex by 1 (Move to Previous page)
((CustomPaging)Session["page"]).CurrentPageIndex -= 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsLastPage)
//Increments the pageIndex by 1 (Move to Next page)
((CustomPaging)Session["page"]).CurrentPageIndex += 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?partnumber=" + DataList2.DataKeyField[DataList2.SelectedIndex].ToString());
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
no = int.Parse(e.CommandArgument.ToString()) + 1;
((CustomPaging)Session["page"]).CurrentPageIndex = int.Parse(e.CommandArgument.ToString());
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton btn = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (btn.Text == no.ToString())
{
btn.ForeColor = System.Drawing.Color.Maroon;
btn.Font.Underline = false;
}
else
{
btn.ForeColor = System.Drawing.Color.DarkCyan;
btn.Font.Underline = false;
}
}
I just want to know what the problem is in the coding and "how to serialize the session"?
What shold i do to improve the coding?
Any help will be appreciated.
Thank You

I guess your custom paging control is not serializable. This must be the cause of the issue.
Anyway, storing a control in session is not a good idea. Just store the few serializable properties which enable to rebuild the control (PageSize and CurrentPageIndex), or pass them in query string for example.
You could also use ViewState if you can
About storing the DataTable in Session, this might be a really bad idea if you have a lot of data and many connected users.

Related

remove previously stored value of a checkbox in a session when user unchecks this checkbox

I try to dynamically create checkboxes - all of them with assigned checkedChanged event.
In the event handler i test if the checkbox is checked and if so I sore the value attribute in a session.
But here occurs a big problem for me.
For example a client decides to check one checkboxes and it's value attribute is added to the session, but then he suddenly decides that he doesn't want that checbox to be checked and he unchecks it - it's ok, but this value will stay stored in the session and I don't eant that.
So is there any way to delete this value when the user unchecks the checkbox
protected void btnProba_Click(objectore sender, EventArgs e)
{
lblProba.Text = ((String)Session["chk"]);
// lblProba.Text = pr.ToString();
}
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
//lblProba.Text += chk.Text;
//myche.Add(chk.Text);
Session["chk"] += chk.InputAttributes["value"];
}
}
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
chkddlchange = true;
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd= cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
CheckBox mycheckbox = new CheckBox();
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Text = rd["Extra_Charge_Description"].ToString();
mycheckbox.InputAttributes.Add("value", rd["Extra_Charge_ID"].ToString());
mycheckbox.AutoPostBack = true;
mycheckbox.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(mycheckbox);
}
}//End of try
catch (Exception ex)
{ }
}//end of for
}
}
}
It seems like you store checkboxes values as a concatenated string in Session["chk"]. It makes removing anything from there pretty hard. I guess it might be better to store a list of strings in Session["chk"], so you would be able to easy add/remove entries from there...

change a pageDataSource page

Hi all i have a page that takes items from a sql datasource and puts them into a repeater. I want to know how to change the page index of the pagedDatasource when i click another button
page load
DataSourceSelectArguments arg = new DataSourceSelectArguments();
arg.MaximumRows = 8;
arg.AddSupportedCapabilities(DataSourceCapabilities.Page);
DataView set = (DataView)SQLDataSourceProducts.Select(arg);
int rows = arg.TotalRowCount;
PagedDataSource paged = new PagedDataSource();
paged.DataSource = set;
paged.AllowPaging = true;
paged.PageSize = 3;
int pageIndex = 1;
paged.CurrentPageIndex = pageIndex - 1;
RepeaterProducts.DataSource = paged;
RepeaterProducts.DataBind();
On a button press
protected void moreButton_Click(object sender, EventArgs e)
{
//Change the pageIndex
}
Thanks all
Hi all found the answer and this is how i done it for anyone who wants to know
public void popRepeater()
{
//Clear datasource so you can repopulate without getting duplication error
SQLDataSourceProducts.SelectParameters.Clear();
//Your query
SQLDataSourceProducts.SelectParameters.Add
DataSourceSelectArguments arg = new DataSourceSelectArguments();
arg.MaximumRows = 8;
arg.AddSupportedCapabilities(DataSourceCapabilities.Page);
DataView set = (DataView)SQLDataSourceProducts.Select(arg);
int rows = arg.TotalRowCount;
PagedDataSource paged = new PagedDataSource();
paged.DataSource = set;
paged.AllowPaging = true;
paged.PageSize = 3;
//int pageIndex = 1;
paged.CurrentPageIndex = CurrentPage ;
RepeaterProducts.DataSource = paged;
RepeaterProducts.DataBind();
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default page index of 0
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
protected void moreButton_Click(object sender, EventArgs e)
{
CurrentPage += 1;
popRepeater();
}

update cancel on gridview asp.net

I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.

Bind two datasources into one grid

I have two input controls through which I need to browse and upload the documents.
Below is my ascx
I need to have both teh files uploaded in the gridview.
Below is the code on how I am trying to achieve this.I am creating a datatable for the first upload and then a second datatable for the second upload, and then merging the twodatables into a new combined one and assigning that as the datasource for the gridview.
namespace Sharepoint.WebParts.Upload_WebPart
{
public partial class Upload_WebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
this.btnUpload.Click += new EventHandler(btnUploadUploadClick);
this.uploadsupport.Click+=new EventHandler(uploadsupport_Click);
this.btnSubmit.Click += new EventHandler(btnSubmit_Click);
this.dgdUpload.RowDeleting += new GridViewDeleteEventHandler(dgdUpload_RowDeleting);
}
protected void btnUploadUploadClick(object sender, EventArgs e)
{
fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
string x = Path.GetExtension(fileName);
if (fileName != "")
{
if (x == ".zip")
{
string _fileTime = DateTime.Now.ToFileTime().ToString();
string _fileorgPath = System.IO.Path.GetFullPath(inputFile.PostedFile.FileName);
string _newfilePath = _fileTime + "~" + fileName;
length = (inputFile.PostedFile.InputStream.Length) / 1024;
string tempFolder = Environment.GetEnvironmentVariable("TEMP");
string _filepath = tempFolder + _newfilePath;
inputFile.PostedFile.SaveAs(_filepath);
AddRow(fileName, _filepath, length);
lblMessage.Text = "Successfully Added in List";
}
else
{
lblMessage.Text = "Please upload a zip file";
return;
}
}
else
{
lblMessage.Text = "Select a File";
return;
}
}
private void AddMoreColumns()
{
dt = new DataTable("DT");
dc = new DataColumn("FileName", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FilePath", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FileSize", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("KB", Type.GetType("System.String"));
dt.Columns.Add(dc);
Page.Session["DT"] = dt;
}
private void AddRow(string file, string path, double length)
{
dt = (DataTable)Page.Session["DT"];
if (dt == null)
{
AddMoreColumns();
}
dr = dt.NewRow();
dr["FileName"] = file;
dr["FilePath"] = path;
dr["FileSize"] = Convert.ToString(length);
dr["KB"] = "KB";
dt.Rows.Add(dr);
Page.Session["DT"] = dt;
}
Similary i add rows to the datatable dt1.
protected void bindgridview()
{
dt = (DataTable)Page.Session["DT"];
dt1 = (DataTable)Page.Session["DT1"];
joineddt = (DataTable)Page.Session["Files"];
if (joineddt == null)
{
joineddt = dt.Copy();
joineddt.Merge(dt1);
}
this.dgdUpload.DataSource = joineddt;
this.dgdUpload.DataBind();
Page.Session["Files"] = joineddt;
}}
}
Please help me to correct this , also is there a simple way to achieve this.
You can't databind to more than one data source at the same time. If the datatable joineddt does not have SupportName in it then your code would not work.
Rather than trying to try an finagle 2 data sources into one GridView, you should create one data source that has all the data you expect to display in a row of the GridView in one row of the data source.

how to retain the value of global string variable even after page load in asp.net

I am having problems in retaining the string variable which I defined on the top of my scoop, everytime when page loads the string value becomes null. below is the snippet of the code:
public partial class Caravan_For_Sale : System.Web.UI.Page
{
string check;
PagedDataSource pds = new PagedDataSource(); //paging
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = null;
switch (check)
{
case "0-1500":
break;
case "1500-2000":
dt = caravans.GetFilterbyPrice1();
break;
case "2000+":
break;
default:
dt = caravans.GetAllCaravans();
break;
}
// DataTable dt = caravans.GetAllCaravans();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 3;//add the page index when item exceeds 12 //Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
DataList1.RepeatColumns = 3; // 4 items per line
DataList1.RepeatDirection = RepeatDirection.Horizontal;
DataList1.DataSource = pds;
DataList1.DataBind();
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
doPaging();
}
protected void lnkPrice2_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
check = _sender.CommandArgument;
// items["test"] = test;
DataTable dt = caravans.GetFilterbyPrice2();
if (dt.Rows.Count < 3)
{
lnkbtnNext.Enabled = false;
lnkbtnPrevious.Enabled = false;
}
CurrentPage = 0;
BindGrid();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
The string check becomes null everytime when the dlPaging_ItemCommand becomes active(page loads). Any help or suggestions will be appreciated
As far as I know, you have two options:
1) Load it again.
Not sure if it's possible in your case. This is usually done when dealing with database queries.
2) Put it in the ViewState just like this:
ViewState["check"] = check;
And load it after with this:
string check = Convert.ToString(ViewState["check"]);
Your class is instantiated on every load so it will not have a global variable from page view to page view. You will need to store it somehow. Like in the querystring or a session. You can also use the viewstate.
For example
ViewState("Variable") = "Your string"
Viewstate is the way to go, as the other people have answered. Whatever you do, please don't stuff it in the session.

Resources