C# Program Crash comboBox SelectedItem ToString - c#

I have no idea, why my program crash.
If i click "Reload" Button:
private void reloadBtn_Click(object sender, RoutedEventArgs e)
{
comboFilter.Items.Clear();
dataGridPrivatecustomers.Columns.Clear();
dataGridPrivatecustomers.ItemsSource = null;
load_columns_privatecustomer();
load_values_privatecustomer();
}
All works.
But if I select a filter for my search function and click reload, then it crashes:
private void comboFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
labelfilter.Content = "Filter: " + comboFilter.SelectedItem;
filtervalue = comboFilter.SelectedItem.ToString();
}
This is the breakpoint:
filtervalue = comboFilter.SelectedItem.ToString();
And I get a NulLReferenceException Error.
I tryed to make a filtervalue = null; in reloadBtn_Click but also doesn't work.

The comboFilter_SelectionChanged is somehow fired after the reload where you remove items from the combo, which is result of clear method. Make sure you have SelectedItem not null in comboFilter_SelectionChanged before you use it.
private void comboFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if( comboFilter.SelectedItem != null)
{
labelfilter.Content = "Filter: " + comboFilter.SelectedItem;
filtervalue = comboFilter.SelectedItem.ToString();
}
}
As a additional note your program must not crash by not catching the exception being thrown in your program. Use try-catch to properly handle the exception. And also try to avoid them before they could occur. Like we did here by checking for null. This will prevent program crashing.
try-catch (C# Reference) - Why program would crash (stop execution)
When an exception is thrown, the common language runtime (CLR) looks
for the catch statement that handles this exception. If the currently
executing method does not contain such a catch block, the CLR looks at
the method that called the current method, and so on up the call
stack. If no catch block is found, then the CLR displays an unhandled
exception message to the user and stops execution of the program.

The exception gets thrown because comboFilter_SelectionChanged is called implicitly from reloadBtn_Click when comboFilter.Items.Clear() is called. In this case comboFilter.SelectedItem changes from the previously selected item to null.
Check for null in comboFilter_SelectionChanged:
private void comboFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (comboFilter.SelectedItem != null)
{
labelfilter.Content = "Filter: " + comboFilter.SelectedItem;
filtervalue = comboFilter.SelectedItem.ToString();
}
}

You may want to add a null-check for comboFilter.SelectedItem, e.g. like comboFilter.SelectedItem?.ToString()

Related

Recalling method for Web Forms OnClick methods from another on Click method

I have a issue where I need to look up if the user is available to work on a task and if they have a prior commitment give then a warning. The way I tried to implement this is to check if they have an a commitment and if they do bail out of the original action while marking that they were warned in the session and storing the original action that I was going to call as an action in session. When they click continue on the modal that pops up it will retrieve that action and since they've already been warned execute said action.
The issue I'm getting when I call the original action is
SetFocus can only be called before and during PreRender.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: SetFocus can only be called before and during PreRender.
Called when the user acknowledges they've received a warning an select ok
protected void BtnAcknowledgeSecureLeave_Click(object sender, EventArgs e)
{
this.vacationWarningModal.ShowOnPageLoad = false;
this.vactionLookup.ExecuteAction(base.FormState.RosterId, base.FormState.AttorneyID);
}
Called to check if they have a conflict or not
private bool DoesUserHaveVacationConflicts(Action action)
{
if (CurrentUser.IsXUser && base.FormState.Id!= null)
{
if(this.vactionLookup.HasAcknowledgedSingle(base.FormState.ID, base.FormState.UserId))
{
return false;
}
else
{
// Stores the action that would have been called in a session
this.vactionLookup.StoreAction(action, base.FormState.ID, base.FormState.UserId);
}
var vacLookup = new VacationLookup();
var vacationLookup = secLeave.GetVacationConflicts(base.CurrentUser);
if (vacationLookup.HasOverlapingDates())
{
this.secureLeaveWarnings.AcknowledgeSingle(base.FormState.ID, base.FormState.CurrentId);
return true;
}
}
return false;
}
Checks if they have been warned about their conflict, if they have on and stores the the action they would have called in a session
protected void BtnSave_Click(object sender, EventArgs e)
{
if (this.DoesUserHaveVacationConflicts(() => this.BtnSave_Click(sender, e)))
{
return;
}
else
{
// Calls Focus, does work setting up the aspx page
DoSomeImportantWork();
}
}

BackgroundWorker not passing FileNotFoundException to RunWorkerCompleted

I'm working on a WinForms project and at one point I have to load a XmlDocument in the background. I have a BackgroundWorker do this, but when the XmlDocument can't be found the BackgroundWorker throws a System.IO.FileNotFoundException in DoWork instead of passing it onto RunWorkerCompleted.
private void LoadBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
//---download manifest---
SetStatusText("Downloading manifest...");
Manifest = new System.Xml.XmlDocument();
Manifest.Load(Properties.Resources.ManifestUrl); // <-- this is where the code gets stuck, it alerts me that the exception is unhandled
}
private void LoadBgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Success = false;
Error = e.Error;
this.Close();
}
else
{
//---loading complete, close form---
Success = true;
this.Close();
}
}
Am I missing something here? Shouldn't the exception automatically trigger RunWorkerCompleted so it can be handled there?
Did you check if you have the System.IO.FileNotFoundException "Break when thrown" ticked in the Exception Settings ?
It might be it, as backgroundworker DoWork catch an exception if thrown.
From Microsoft (full article here) :
Tell the debugger to break when an exception is thrown
The debugger can break execution at the point where an exception is
thrown, so you may examine the exception before a handler is invoked.
In the Exception Settings window (Debug > Windows > Exception
Settings), expand the node for a category of exceptions, such as
Common Language Runtime Exceptions. Then select the check box for a
specific exception within that category, such as
System.AccessViolationException. You can also select an entire
category of exceptions.

How to ensure log the exception when there is unhandled exception

I want a crash reporting, so I register the UnhandledException event in App.xaml.cs like following. But there are 2 problems:
Sometimes, there is no callstacks for exception
Sometimes, I don't have enough time to write log into file before the process is terminated.
Any advice?
this.UnhandledException += App_UnhandledException;
private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (!hasHandledUnhandledException)
{
e.Handled = true;
_logger.Error("Unhandle exception - message = {0}\n StackTrace = {1}", e.Exception.Message, e.Exception.StackTrace);
await CrashHandler.ReportExceptionAsync(e.Exception.Message, e.Exception.StackTrace);
hasHandledUnhandledException = true;
throw e.Exception;
}
}
Make sure to access e.Exception only once. In some cases, information about the stacktrace is lost the second time you access the property. Save the exception in a variable and work directly with that variable. Also, as mentioned by Panagiotis Kanavos in the comments, directly log e.Exception.ToString() to make sure to miss no information. This will include the message, the callstack, and all inner exceptions (which you are not logging in your current code).
private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (!hasHandledUnhandledException)
{
e.Handled = true;
var exception = e.Exception;
_logger.Error("Unhandled exception - {0}", exception);
await CrashHandler.ReportExceptionAsync(exception.Message, exception.StackTrace);
hasHandledUnhandledException = true;
throw e.Exception;
}
}
As for the problem of not having enough time to log the exception, it's controlled by the runtime so you can't do anything about it.

Resting a private variable that should not happen

I have a strange problem I'm checking in my code behind the user if he is active or not with as simple if .. in my Page_Load method as you can see here
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
this.getParameters();
if (!this.IsPostBack)
{
if (paramTR.ZevUser.Active == 0)
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
}
But when I make a go throw to this method I get allays nullreferenceexception why so ever .. but the private ZevUser variable is not null it's full..
I really don't have a clue why is this happing, it would be really cool if someone could explain me this why this is happening
Thanks for help and fast answer
You need to break your code down so you can debug it easier or add logging if you cannot debug this code locally.
Remember that when debugging something, the worse mistake you can make is to make assumptions. Start from the beginning and follow the process through. Don't assume that the problem is something and don't assume that the problem can't be something:
I've included a broken down, more readable version below. You can now add logging around this or easily add breakpoints:
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
this.getParameters();
if (!this.IsPostBack)
{
if ((this.paramTR != null) &&
(this.paramTR.ZevUser != null) &&
(this.paramTR.ZevUser.Active == 0))
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
string sessionId = Session["SessionId"] as string;
if (sessionId != null)
{
int session = int32.Parse(sessionId);
ZevUser user = ZevUser.GetById(session);
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
}
}
Why are you passing the session id to ZevUser.GetById()? I would expect this to take a user id, or for the method to be called something like ZevUser.GetBySessionId(). At the moment it's quite confusing.
This line is causing the issue:
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
This is because Session["SessionId"] can be null, and is null in this case.
If you are looking to get the SessionId that is set by ASP.net, then use this.Session.SessionID (source).
If you are storing a value in Session["SessionId"] that you are trying to retrieve, then do a null-check first:
if (Session["SessionId"] != null) { ...
You should consider testing the SessionId variable before using it by doing something like that :
if (!string.IsNullOrEmpty(Session["SessionId"].ToString()))
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
The best way to debug your exception is to enable debug when the exception is thrown.
For this, go to Debug>>Exceptions
and then enable first four checkboxes (maybe) and then try debugging the project. You will be halted at the position from where the exception will be thrown.

What causes Winforms to silently discard unhandled exceptions (with no try/Catches)?

I'm in the middle of adding new functionality to my winforms controls, and part of that requires that a variable that was once always used to now be optional (if it's null, get the data from a second source). I made some changes and ran my form, only to find out nothing was happening, even functionality that previously worked. Confused I stepped through the code and found out that my Winforms user control was throwing a NullReferenceException when it encountered my variable, but in the UI no errors were being thrown.
My setup is I have a UserControl with a combo box. When the user changes that combo box it loads a secondary UserControl in a panel the first control has. The second control is what is throwing the exception.
Here are the code paths:
private void cmbActionType_SelectedIndexChanged(object sender, EventArgs e)
{
if (_loading)
return;
// ActionType was changed, update the action.ActionType value
if (cmbActionType.SelectedItem != null)
{
if (cmbActionType.SelectedItem.ToString() == SETVALUE_OPTION)
_action.ActionType = ActionTypes.SetValue;
else if (cmbActionType.SelectedItem.ToString() == CHECKVALUE_OPTION)
_action.ActionType = ActionTypes.CheckValue;
else
_action.ActionType = ActionTypes.CustomAction;
}
RefreshActionPanel();
_editor.DataModified();
}
private void RefreshActionPanel()
{
// Control defaults
AnchorStyles styles = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
UserControl subControl = null;
// Clear the currently active control
pnlActionDetails.Controls.Clear();
// Determine what type of control to load in the panel
if (cmbActionType.SelectedItem != null && cmbCaseType.SelectedItem != null)
{
// SetValue or CheckValue actions
if (cmbActionType.SelectedItem.ToString() == CHECKVALUE_OPTION || cmbActionType.SelectedItem.ToString() == SETVALUE_OPTION)
{
if (_caseTypeMap.ContainsKey(cmbCaseType.SelectedItem.ToString()))
subControl = new SetCheckActionControl(_action, _editor, _caseTypeMap[cmbCaseType.SelectedItem.ToString()]);
}
// CustomAction action type
else
{
// Check if the requested case is a type or defined in a script
if (_caseTypeMap.ContainsKey(cmbCaseType.SelectedItem.ToString()))
{
subControl = new CustomActionControl(_action, _editor, _caseTypeMap[cmbCaseType.SelectedItem.ToString()]);
}
else if (_editor.ScriptDefinitions.Any(x => x.CaseName == cmbCaseType.SelectedItem.ToString()))
{
var definitions = _editor.ScriptDefinitions.Where(x => x.CaseName == cmbCaseType.SelectedItem.ToString()).ToList();
subControl = new CustomActionControl(_action, _editor, definitions);
}
}
}
if (subControl != null)
{
subControl.Anchor = styles;
subControl.Height = pnlActionDetails.Height;
subControl.Width = pnlActionDetails.Width;
pnlActionDetails.Controls.Add(subControl);
}
}
public CustomActionControl(TestAction action, fmEditor editor, IList<TcScriptDefinition> scriptDefinitions) : base(action, editor)
{
_loading = true;
InitializeComponent();
_scriptDefinitions = scriptDefinitions;
PopulateActionList();
SetupDataGrid();
_loading = false;
}
private void SetupDataGrid()
{
// Clear the current contents of the datagrid
grdParameters.Rows.Clear();
if (cmbAction.SelectedItem == null)
return;
// Retrieve the action code from the drop down
string actionCode = cmbAction.SelectedValue.ToString();
// Check if any paramters are available for this action
if (!_availableActionParameters.ContainsKey(actionCode))
return;
// Add a new row for each parameter available for this action
foreach (string param in _availableActionParameters[actionCode])
{
string display = param;
// Determine if the parameter has a display string
if (_formInstance.CodeDisplayMap.ContainsCode(param))
display = _formInstance.CodeDisplayMap.GetDisplayStringFromCode(param);
// Create the array for the row, with an empty string as the current value
string[] row = { display, string.Empty };
// Check if the current action uses this action code.
// If so, retrieve the value for this parameter and use it in the row
// Note: Case-INsensitive comparison must be performed here
if (_action.Attributes["action"].Equals(actionCode, StringComparison.CurrentCultureIgnoreCase))
if (_action.Attributes.ContainsKey(param))
row[1] = _action.Attributes[param];
grdParameters.Rows.Add(row);
}
}
The NullReferenceException is coming from the SetupDataGrid() method where _formInstance is being called. However, usually when an application encounters an unhandled exception the JIT system throws an error message saying such (and as you can see, there's no try/catch statements used unless I am blind).
Why does my winforms application show no signs of an exception occurring. I'd rather an unhandled exception message occur rather than nothing happening, as that makes it harder for users to know something critical went wrong (as opposed to it not responding to their commands)
Edit: To clarify since there seems to be some confusion, I do NOT care about breaking on this exception in visual studio when debugging. The fact of the matter is that the application should not be hiding unhandled exceptions, and my application should crash (or rather show the JIT message that an unhandled exception occurred), even when not in debug mode outside of visual studio.
This is not a debug time question but a production run time question. If this code throws an OutOfMemoryException for instance, I need it to not be silently ignored. Right now it is being ignored.
Go to Debug->Exceptions... (Ctrl-D, E if you are using default shortcuts) from your menu bar in Visual Studio and check the box for Thrown under Common Language Runtime Exceptions. This will cause your program to break on exceptions even if they are in a try/catch block. You can then do a step forward and see where the code is jumping to for the next instruction. That should bring you to the catch block that is hiding your exception.
It may be jumping in to .NET code for the catch, you can go to Debug->Options and Settings.. and turn on Enable .NET framework Source Stepping to see what it is jumping in to.
Here is a example of catching the unhandeled execptions in code
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form1());
MessageBox.Show("0");
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show("1");
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
throw new ArgumentNullException();
}
}
Click the button and 1 appears, the program should still run afterwards.
However as I said in my last comment, check that user-unhandeled is checked (maybe uncheck and recheck) in Debug->Exceptions first it may solve your initial issue..
They can be caught if you have a try/catch in your Main, or if you have a ThreadException handler. Also check out SetUnhandledExceptionMode.
Note that if they're caught in Main, your program will just exit silently. ThreadException can "catch" and ignore them.
EDIT: Since the debugger doesn't break when you uncheck the box for Thrown under Common Language Runtime Exceptions, it's being caught by the code for Windows Forms. This is not ideal, but a lot of the BCL does this. You don't need to worry about it catching OutOfMemoryException or anything like that; the BCL should only be catching exceptions that it expects (vexing exceptions).
To be clear, the exception is not "unhandled". It is handled by the BCL code.

Categories