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.
Related
My Winform app is logging AppDomain.CurrentDomain.UnhandledException and Application.ThreadException at the root level, and I got this exception:
System.InvalidOperationException: Operation is not valid due to the current state of the object. at System.Windows.Forms.DataGridView.DataGridViewDataConnection.ProcessListChanged(ListChangedEventArgs e) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object sender, ListChangedEventArgs e) at System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e) at System.Windows.Forms.CurrencyManager.List_ListChanged(Object sender, ListChangedEventArgs e) at System.ComponentModel.BindingList1.OnListChanged(ListChangedEventArgs e) at System.ComponentModel.BindingList1.FireListChanged(ListChangedType type, Int32 index) at System.ComponentModel.BindingList1.InsertItem(Int32 index, T item) at System.Collections.ObjectModel.Collection1.Add(T item) at System.ComponentModel.BindingList1.AddNewCore() at System.ComponentModel.BindingList1.System.ComponentModel.IBindingList.AddNew() at System.Windows.Forms.CurrencyManager.AddNew() at System.Windows.Forms.DataGridView.DataGridViewDataConnection.AddNew() at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnNewRowNeeded() at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred) at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick) at System.Windows.Forms.DataGridView.ProcessDownKeyInternal(Keys keyData, Boolean& moved) at System.Windows.Forms.DataGridView.ProcessEnterKey(Keys keyData) at System.Windows.Forms.DataGridView.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData) at System.Windows.Forms.TextBoxBase.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.PreProcessMessage(Message& msg) at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg) at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
This is the result of ex.ToString(), and it returns no custom code of my app, only internal System.Windows.Forms methods.
The exception is raised time to time on some customer machine, I'm even not able to reproduce it myself.
This smell not good, and my assumption was something when I change the datasource bounding of the datagridview. But in this case I should see at least my class in the exception stack, but here nothing.
Any clue to find the root cause, or to debug that?
Many thanks
If you investigate the stack trace, you'll see the root of the problem: customer is trying to add a new record on the grid, so the event handler tries to add the record to the datasource, which lead to another event handler, which tries to add a record to the binding list, which lead to event currencyManager_listChanged firing up, which fails due to wrong state of the object.
Either you dispose your list or you do not unsubscribe from the events of the disposed control.
I've experienced exactly the same exception, and it occurs after the user deletes multiple rows (multi select enabled), and includes the last row in the selection. The last row is for adding new items. Everything works fine, until the user then goes to edit remaining rows, and the exception occurs.
When the user doesn't include the last/add new item row in the selection, everything works fine after the delete.
I haven't had time to investigate exactly why this behavior occurs, but the work around was to not allow the add new item row to be included when multi-selecting items, which can be detected by the IsNewRow property of DataGridViewRow and then calling ClearSelection() on the DataGridView if this row is in the selection.
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
if (row.IsNewRow)
{
dataGridView1.ClearSelection();
return;
}
}
}
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 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).
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.