weird dataset in asp.net - c#

I have built a dataset named Transaction_Time.
I called it on Page_Load
Transaction_Time tranTme = new Transaction_Time();
put it in the session.
Session["Transaction"] = tranTme;
Then I call that session and cast to dataset.
DataSet dstTranTime = (DataSet)Session["Transaction"];
I got the following error.
Unable to cast object of type 'Transaction_Time' to type 'System.Data.DataSet'.
[InvalidCastException: Unable to cast object of type 'Transaction_Time' to type 'System.Data.DataSet'.]
Transaction_Time.Page_Load(Object sender, EventArgs e) in c:\Inetpub\wwwroot\William29_11_2010\Transaction_Time.aspx.cs:47
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
It is OK for some other pages. But for some page, it doesn't.
Is it something wrong that I do or.. ???

You put in typeof(Transaction_Time) and try to get out typeof(DataSet). this will fail until
Transaction_Time is not derived from DataSet. Try to read Transaction_Time instead of DataSet.
Transaction_Time tranTme = new Transaction_Time();
....
Session["Transaction"] = tranTme;
....
Transaction_Time dstTranTime = Session["Transaction"] as Transaction_Time;
if (dstTranTime == null)
System.Dignostics.Trace.WriteLine("Ups! Expecting Transaction_Time, but got {0}", Session["Transaction"] );

It looks like you may have two classes called Transaction_Time. If you have created a class called Transaction_Time and derived it from DataSet AND you have a class called Transaction_Time that is derived from, say, Page. Then the compiler may be confused about which you mean and you may occasionally be storing the page Transaction_Time rather than the DataSet Transaction_Time.
Be explicit when creating the Transaction_Time class and use the fully qualified name OR rename one of your classes so that the name is not ambiguous. That should solve your problem (assuming my assumptions are correct).

Related

C# System.Web.HttpUnhandledExcpetion when changing page of table

I have a table in my web app that displays a list of users from my SQLExpress DB but for some reason when I navigate to page 8 I get this stacktrace in my logs:
ERROR Global Exception Logged in Global.asax.cs: Exception of type 'System.Web.HttpUnhandledException' was thrown.Data is Null. This method or property cannot be called on Null values. at System.Data.SqlClient.SqlBuffer.get_String()
at BusinessLayer.Appl.UserDetailMgr.PopulateObjectFromReader(UserDetailMgr obj, IDataReader rdr)
at BusinessLayer.Appl.UserDetailMgr..ctor(IDataReader dr)
at BusinessLayer.Appl.UserDetailMgr.GetUserList(Int32 startIndex, Int32 recordsPerPage, Int32 colNo, Int32 order)
at PresentationLayer.Pages.User.BSLeadListing.Display(String sortBycolumnNo)
at PresentationLayer.Pages.User.BSLeadListing.gdPager_ItemCommand(Object source, RepeaterCommandEventArgs e)
at System.Web.UI.WebControls.Repeater.OnItemCommand(RepeaterCommandEventArgs e)
at System.Web.UI.WebControls.Repeater.OnBubbleEvent(Object sender, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.RepeaterItem.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
2018-08-02 14:56:26,853 [6008] ERROR Global Request URL: http://mednet.butterflyscheme.org.uk/WebEvaluation/Pages/User/BSLeadListing.aspx
2018-08-02 14:56:26,853 [6008] ERROR Global Exception is not null & type of exception is 'HttpUnhandledException'.
Literally every page of the table works excpet page 8.
I have no clue where to start looking since I write the original code. Any thoughts would be much appreciated
When I look in my logs, it crashes just after this function is complete:
/// <summary>
/// Repeater event
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
protected void gdPager_ItemCommand(object source, RepeaterCommandEventArgs e)
{
logger.Debug("gdPager_ItemCommand - Start");
try
{
ViewState["UserListPageIndex"] = Convert.ToInt32(e.CommandArgument);
Display(Convert.ToString(ViewState["ColumnNo"]));
PopulatePager();
}
finally
{
logger.Debug("gdPager_ItemCommand - End");
}
}
UPDATE:
I searched for every value that would exist on page 8 using the search feature of the table while on the site. Every result displayed. So now I'm left wondering what is null?
The error says
Data is Null
It looks like the query returns no data, on page 8, and that causes the problem. you can use it in a try-catch.
I think you have not correctly calculated the number of pages, so page 7 should be the last page, however, still you have do add error handling there.

C# ASP.NET Session Manager throwing null reference exception

I am trying to implement a static SessionManager class that is supposed to act as a wrapper around a SessionStore object, which is stored in HttpContext.Current.Session["objSession"] and actually holds all of the user's session data. The SessionManager class has identical properties as SessionStore, but has extra methods needed to manipulate the session data as needed. Basically, the SessionManager facilitates getting/setting properties stored in the session object.
All classes are stored in the same namespace as the web solution, and all are serializable.
I have tried two different solutions to my problem, both threw a null reference exception at the same point, when trying to do ANYTHING with HttpContext.Current.Session:
public static class SessionManager
{
static SessionManager()
{
if (HttpContext.Current.Session != null)
{
try
{
if (HttpContext.Current.Session["objStore"] == null)
{
HttpContext.Current.Session["objStore"] = new SessionStore();
}
}
catch (NullReferenceException)
{
HttpContext.Current.Session["objStore"] = new SessionStore();
}
}
}
Code-behind of the calling page:
protected void Page_Load(object sender, EventArgs e)
{
if (SessionManager.groupSettings.Count > 0)
{
pnlDashboard.Visible = true;
pnlLogin.Visible = false;
getDisplayData();
}
else
{
pnlDashboard.Visible = false;
pnlLogin.Visible = true;
}
}
The debugger steps into SessionManager all the way down to line
if (HttpContext.Current.Session != null)
where it then stops and throws the exception. However, when I hover over the code and the properties dialog opens, it shows that the HttpContext.Current.Session object is NOT null. The resulting call stack is here, but indicates that the source line is if (SessionManager.groupSettings.Count > 0), which is in the code-behind:
[NullReferenceException: Object reference not set to an instance of an object.]
Project.Default.Page_Load(Object sender, EventArgs e) in C:\Users\ASP\Project\Project\Default.aspx.cs:20
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2952
My second attempt had all of the code within the static constructor above, but had it in a public static sessionStart() method, which was called above the first if statement in the calling page's code-behind:
protected void Page_Load(object sender, EventArgs e)
{
SessionManager.sessionStart()
if (SessionManager.groupSettings.Count > 0)
{
pnlDashboard.Visible = true;
pnlLogin.Visible = false;
getDisplayData();
}
else
{
pnlDashboard.Visible = false;
pnlLogin.Visible = true;
}
}
I am really stumped as to what could be causing this problem. I have static classes elsewhere in my code and haven't had any issues, and the Session seems to not be null.
I appreciate all help. Thank you!
So it seems I did not initialize some objects within my SessionStore class, because I added a constructor that initialized them, and the problem is now fixed. Maybe the problem was actually happening when the object was being serialized (as is the case when an object is stored into the stateserver), and the error message confused me.
Edit - I always do this... Figure out the solution AFTER I've posted to StackOverflow... :(

System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

I am getting the below exception in a UserControl, Page Load. I have tried searching for this on Google, but have not found much information. Please let me know if anybody could help me with the same .
The situation is, there is one ascx.cs file for various usercontrols in different languages.
The application is running properly , but this exception is getting thrown for sometimes.
Exception information:
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.
at SmartSoft.SmartLiveWeb.UserControls.Common.PayoutForms.BoundAccountsOfMember()
at SmartSoft.SmartLiveWeb.UserControls.Common.PayoutForms.Page_Load(Object sender, EventArgs e)
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Request information:
Is authenticated: True
Authentication Type: Forms
Thread account name: IIS APPPOOL\SLC Website
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
/*
if (Request.QueryString.Count > 0 && Request.QueryString["MId"] != null)
this.MId = int.Parse(Request.QueryString.Get("MId"));
*/
HideAllForms();
AddValidationAttributesToControls();
**BoundAccountsOfMember();**
BoundWithdrawMethods();
/*
* if (IsNetentConfirmationRequired())
LoadNetentConfirmationForm();
*
*/
CurrentPayoutMethod = (PayoutMethodEnum)Convert.ToInt16(SessionController.GetSessionData<object>("PayoutMethod"));
}
PlaceHolder phWithdraw = this.FindControl("phWithdraw") as PlaceHolder;
Panel pnlKYC = this.FindControl("pnlKYC") as Panel;
if (SessionController.CurrentMember != null && SessionController.CurrentMember.Approved == 10)
{
phWithdraw.Visible = false;
pnlKYC.Visible = true;
}
else
{
phWithdraw.Visible = true;
pnlKYC.Visible = false;
}
}
Please find the BoundAccountsofMember method code behind .
private void BoundAccountsOfMember()
{
Dictionary<Int16, AccountType> accountTypes = SessionController.CurrentMember.GetAccountTypes();
ddlWithdrawFrom.Items.Clear();
foreach (AccountType accountType in accountTypes.Values)
{
ddlWithdrawFrom.Items.Add(new ListItem(accountType.AccountName, accountType.AccountId.ToString()));
}
ListItem li = ddlWithdrawFrom.Items.FindByValue(SessionController.DefaultAccountId.ToString());
if (li != null)
{
ddlWithdrawFrom.SelectedIndex = -1;
li.Selected = true;
}
}
The above exception is being thrown from Page_Load event.
Regards
Srividhya
I could guess that you have a problem with a session here. You're checking SessionController.CurrentMember != null in Page_Load, but not in your BoundAccountsOfMember.
I believe that is a problem here if you're saying it happens time to time. You probably should work on session renewal/invalidation in your modules to make sure your code will not run without a valid session.

String was not recognized as a valid DateTime

I have a search feature (written by my predecessor) which takes date range, id, available programs as input and displays the results in a gridview. The feature works fine most of the time (I have tested it) but for one of the users of my application it gave this error message. I am not able to reproduce this error by myself in order to fix it. Don't know what's wrong!
Can you guys help?
Exception of type 'System.Web.HttpUnhandledException' was thrown.
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.Convert.ToDateTime(String value)
at APP_ViewFollowupWorkload.GetFilterString() in d:\SharedServices\APP\ViewFollowupWorkload.aspx.cs:line 1415
at APP_ViewFollowupWorkload.Page_Load(Object sender, EventArgs e) in d:\SharedServices\APP\ViewFollowupWorkload.aspx.cs:line 268
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.app_viewfollowupworkload_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\bad754dd\a11f74ff\App_Web_viewfollowupworkload.aspx.ae7ca9bd.uwyek3vs.0.cs:line 0
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Here is the .cs file code where the error generating:
if (txtDateTo.ToString() != string.Empty)
{
if (txtDateTo.ToString().Length > 2)
strFilter = strFilter + " AND submission_date <= ''" + Convert.ToString(Convert.ToDateTime(txtDateTo.ToString()) + new TimeSpan(1, 0, 0, 0)) + "''";
}
The error indicates that the passes in value of txtDateTo is not a valid DateTime - say 32/11/2011.
You can change the code to something that will not throw an exception by using one of the DateTime.TryParse overloads. This will not parse invalid values, but will avoid an exception being thrown - you still need to determine what to do in such a case.
Try to use ParseExact instead - here (MSDN)
.
Maybe they use some unusual date time format. Ask your user which value in textbox is used to convert to datetime.

ViewState is NULL in Page_Load but not postback

I've got a weird problem with a NullReferenceException on a high traffic website my company hosts. The exceptions are logged with full stack-traces but I am unable to reproduce it.
The exception occurs a couple of times a day, for different users, and it's a NullReferenceException thrown in the code block below:
protected void Page_Load(object sender, EventArgs e)
{
...
if (!Page.IsPostBack)
{
...
this.ViewState[StaticClass.StaticStringProperty] = StaticClass.StaticIntProperty; // this is the line the exception occurs on
...
}
}
The only place I can figure that a NullReferenceException would be thrown is if ViewState is NULL, but I've never known that and can't find any reason why this would be the case in a Page_Load that isn't a postback.
StaticStringProperty and StaticIntProperty are both initialised, static properties of StaticClass.
StaticStringProperty is defined as:
public const string StaticStringProperty = "IdFromClient";
Does anyone know how this could happen, or any other reason why a NullReferenceException would be thrown on the above line?
EDIT
As requested, the full stack-trace for the error is as follows. Line 54 is the line I've highlighted above.
at MyCompany.MyApplication.Appliance.Page_Load(Object sender, EventArgs e) in C:\Documents and Settings\shellama\My Documents\MyApplication\Appliance.aspx.cs:line 54
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at MyCompany.MyApplication.PageBase.OnLoad(EventArgs e) in C:\Documents and Settings\shellama\My Documents\MyApplication\App_Code\PageBase.cs:line 58
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
The only thing I can say about it (I had a similar situation recently) is that StaticClass.StaticStringProperty is NULL. But then again, you must have paid attention to this. I can't think of something else.

Categories

Resources