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.
Related
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.
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... :(
I have a custom error handler for an asp.net site.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
//if (System.Configuration.ConfigurationManager.AppSettings["ProductionMode"] == "Yes")
#if (!DEBUG)
Server.Transfer("~\\GlobalExceptionHandler.aspx");
#endif
}
It works fine and dandy when retrieving exception information cause it'll just snag Server.getLastException() and email it on to me for review
However, I have some TextBoxes on the page and I'd like to send the value of those textboxes along with the email. Maybe it's not quite the DOM I'm looking for access to but instead those posted variables.
I tried looking at HttpContext.Current.Request.Form but it showed no keys.
So Does anyone know how to access the formvalues when globally catching an exception?
Accessing the Form Values
To access the form values in Global.Application_Error, you can simply use HttpContext.Current.Request.Form.
Here is a proof of concept, where a page immediately throws an exception on post(back) to hit the application error handler:
void Application_Error(object sender, EventArgs e)
{
var test = HttpContext.Current.Request.Form;
}
Setting a breakpoint on the assignment to test, then stepping over it (with F10) when it is hit, you can see that test is indeed set to the post(back)'s form-values collection.
Accessing the Postback Control Values
Alternatively, you can access the postback control values by adding them to the session on postback, for example...
// ************code behind
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session["TextBox1"] = TextBox1.Text;
}
..., and accessing the session in the application error handler - for instance:
// ************Global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
// Use Session["TextBox1"].
}
A CodeVerge thread speaks to approach well - particularly Benson Yu's reply.
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.
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).