When I click, the second page is loaded, but the application crashes with System.NullReferenceException:
private async void Forecast_Click(object sender, RoutedEventArgs e)
{
await
CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() => {
Frame.Navigate(typeof(Forecast), null);
}
);
}
A NullReferenceException occurs when trying to access a member of an object which is null.
This is likely happening within your code. Reproduce the error while running your application in Debug mode, and view the call stack/current point of execution when you encounter the exception. It should then be clear to you in which statement your code is trying to access a member of a null object.
Related
I have created a button click handler, code of which goes like this
private void Next_imga2_Click(object sender, EventArgs e)
{
Pothole p = new Pothole();
p.waterLevel = selected;
Intent i = new Intent(this, typeof(createissue4));
try
{
i.PutExtra("issueObj", JsonConvert.SerializeObject(p));
this.StartActivity(i);
}
catch(Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
My application is stopping on
i.PutExtra("issueObj",JsonConvert.SerializeObject(p));
I can't really understand why this is causing application to stop, when this line occurs the app stops and visual studio automatically starts to debug the app again.
I have tried:
applying the try/catch block so to make sure that it is not an exception that is causing this.
making sure that pothole class object "p" is not null.
making sure that this method is being executed on button click
Write JsonConvert.SerializeObject(p) in the separate line and check whether this line of code is causing issue.
And you can check the application output window, if any crash log availability.
I have tried same kind of code and have not observed any crash.
When I run my code in debug mode, I get an exception (System.Web.HttpException: 'Request is not available in this context'), but when I run in release mode (Ctrl-F5), the exception doesn't even show up. The exception appears at the Server.Transfer line.
How can I prevent this from happening when I run in debug mode?
protected void Application_Error(object sender, EventArgs e)
{
//Gets the last error, emails it
var exc = Server.GetLastError();
Server.ClearError();
if (exc == null)
{
exc = new ApplicationException("*** Application Exception - Unknown/null exception ***");
}
if (exc is HttpException)
{
var errorCode = ((HttpException)exc).GetHttpCode();
Response.Redirect("~/ErrorPage.aspx?e=" + errorCode.ToString());
}
else
{
exc.Publish();
Server.Transfer("~/ErrorPage.aspx?e=unknown");
}
}
I believe the issue may be that IIS runs in single-threaded mode when debugging. The Server.Transfer queues a message behind the current request which calls it but the current request cannot complete because the Server.Transfer cannot complete because the thread is blocked.
Try removing all breakpoints from your initial request and adding one in ErrorPage.aspx.
Alternatively, try a Response.Redirect instead of Server.Transfer. Because Response.Redirect will return to the client it completes the current request. I realise this may not be the functionality you require but it will help in debugging, then you can return to Server.Transfer for live running.
Server.Transfer can only happen for single HttpContext. Each virtual directory or app has its own HttpContext object and they know not that they co-exists!
You can find a more complete explanation here Error Message When You Use Server.Transfer or Server.Execute in ASP.NET Page
The solution is to change the method for another like Response.Redirect("~\somepath.aspx"); or HttpContext.Current.RewritePath("somepath.aspx");
I am using the CustomMessageBox control from the Silverlight Toolkit for Windows Phone. When passing an anonymous callback (a 'delegate' in MS speak?) as suggested in the tutorials I reference a member of the page's partial class defined in the code-behind file. This builds and deploys but crashes when I reach the logic at runtime.
I noticed from the VS debugger that the scope inside the callback only contains members from the XAML side of the page partial class and not the members from the code-behind file. This means that the member I refer to is not in the scope (even though Intellisense is fine with it). Moreover I cannot use NavigationService.Navigate inside the callback.
How do I call code within the containing class from the callback?
Here is the code,
// This is a member of the partial class which inherits from
// PhoneApplicationPage
private void cancelBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
if ((this.nameTextBox.Text != String.Empty) || (bool)this.protectCheckBox.IsChecked)
{
CustomMessageBox messageBox = new CustomMessageBox()
{
Caption = "Confirm leave page",
Message = "You have entered some profile data which will be lost if you leave this page. Are you sure you want to leave this page?",
LeftButtonContent = "no",
RightButtonContent = "yes"
};
messageBox.Dismissed += (s1, e1) =>
{
if (e1.Result == CustomMessageBoxResult.RightButton)
{
// Both of these raise an exception ...
GoToProfilePage();
//NavigationService.Navigate(new Uri("/View/MainPage.xaml", UriKind.Relative));
// Inspecting the debugger here shows only half the expected
// number of methods in the 'this' object - specifically only
// those defined in XAML
}
};
messageBox.Show();
}
else
{
// This works fine
GoToProfilePage();
}
}
Where GoToProfilePage() is a method in the code-behind file.
This is the exception,
System.NullReferenceException was unhandled
Message=NullReferenceException
StackTrace:
at Microsoft.Phone.Controls.CustomMessageBox.ClosePopup(Boolean restoreOriginalValues)
at Microsoft.Phone.Controls.CustomMessageBox.c__DisplayClass4.b__1(Object s, EventArgs e)
at Microsoft.Phone.Controls.Transition.OnCompleted(Object sender, EventArgs e)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
Update
It looks like the code is executed, it is only when the delegate finishes that the null reference exception is raised so it may not be a problem with scope ...
OK figured it out. The latest build of the Windows Toolkit .dll (which includes CustomMessageBox) needed a reference in my solution.
Apparently there is an older version of the Windows Toolkit which is included in the default references somewhere since both ContextMenu and CustomMessageBox worked at least partially beforehand which is very confusing ...
To add the updated reference, I built the .dll from the source in a separate project and copied it to my project. I added a reference from the Reference right-click menu in VS and browsed to the file in the debug\bin directory.
A quick hack is to comment line 657 of CustomMessageBox.cs file in the toolkit source code and compile again. Then reference this new dll in your app.
...
private void ClosePopup(bool restoreOriginalValues)
{
// Remove the popup.
_popup.IsOpen = false;
//_popup = null; <-- THIS IS LINE 657
...
There is an issue posted in http://phone.codeplex.com/workitem/10575
I'm trying to use Method.Invoke to call a windows form dialog, have a user perform some selections/interaction and continue execution. This invoke call is happening in an asynchronous method.
While everything works fine, should an error occur on the windows form, an unhandled exception is thrown, even when trying to catch TargetInvocationException or just Exception.
Both forms are in the same winforms project. I realize where are other ways to perform an async call but this is just to illustrate the issue.
The form dialog is as follows:
public partial class FakeDialog : Form
{
public FakeDialog()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
throw new Exception("oh noes!");
this.DialogResult = DialogResult.OK;
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
public new DialogResult ShowDialog()
{
base.ShowDialog();
return this.DialogResult;
}
}
And here is the calling code. None if the catch blocks are being executed, even when not debugging (my problem is not debugging exceptions in the IDE as mentioned here. The following results in an unhandled exception).
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MethodInvoker simpleDelegate = new MethodInvoker(InvokeForm);
IAsyncResult tag = simpleDelegate.BeginInvoke(null, null);
simpleDelegate.EndInvoke(tag);
MessageBox.Show("All done");
}
private void InvokeForm()
{
try
{
Type t = typeof(FakeDialog);
MethodInfo showDialogMethod = t.GetMethod("ShowDialog", new Type[] { });
object dialog = Activator.CreateInstance(t);
System.Windows.Forms.DialogResult result = (System.Windows.Forms.DialogResult)showDialogMethod.Invoke(dialog, new object[] { });
MessageBox.Show(result.ToString());
}
catch (TargetInvocationException tie)
{
MessageBox.Show("Tie exception");
}
catch (Exception ex)
{
MessageBox.Show("general exception");
}
}
}
UPDATE:
Strangely, I'm able to catch the exception when running with debugging (I'm sure the IDE is helping here). Running without debugging causes the unhandled exception.
Also, invoking via an async call doesnt seem to make a difference. If i just call InvokeForm() (ignore all the methodInvoker stuff), I can achieve the same result.
Operating on .NET 2.0 using Visual Studio 2008.
Ok, figured it out.
The result from the code was unhandled exceptions. And while using Method.Invoke for a simple method in another class would behave correctly, the environment changes with the source of the exception occurring in a form. A form event. And I eventually found on Microsoft Support that unhandled exceptions in Windows Form events are not propagated up call stack. There's some pretty interesting reasons for this ("Windows Forms applications have a top-level exception handler that allows the program to continue to run if it can recover").
It also gives credence to what Marc mentioned over putting things in the Load event. Sigh. So the reason for all this is pretty obvious now.
As for the code running fine while debugging (as opposed to without), I think I can thank the JIT debugger for that. #fluf pointed to me that specifically enabling the JIT debugger gave the same result as running with debugging. #Marc Gravell, depending on VS settings this might explain only I and fluf could reproduce. There's some more info on it here but it's not a production fix.
So the real solution is either handling the exceptions in the event handlers themselves or use the solution as mentioned in the Microsoft Support article above, which solves my issues.
I can't actually repro from your code, but: the Load event is.... different, and some odd things can happen if you get an exception inside the Load event. Simply my advice would be: move this code out of the Load event. It also doesn't help that attaching a debugger here changes the behaviour (a Heisenbug).
Without seeing MethodInvoker's declaration i can only guess, but it is possible that InvokeForm() method is executed on non-UI thread.
MethodInvoker simpleDelegate = new MethodInvoker(InvokeForm);
IAsyncResult tag = simpleDelegate.BeginInvoke(null, null);
To show a dialog you may consider to rewrite this as follows:
Action simpleDelegate = new Action(InvokeForm);
this.BeginInvoke(simpleDelegate);
As stated in the title my web application builds successfully, although every time I run it in debug mode I get the following .Net error:
If I hit refresh then the application gets no more errors until I next start it up again, any ideas?
Here is my global.asax file:
<%# Application Language="C#" Inherits="MyCompany.Web.MyApp.Shell.CustomWebClientApplication" %>
<script runat="server">
void Session_End(Object Sender, EventArgs e)
{
FormsAuthentication.SignOut();
}
protected void Session_Start(Object sender, EventArgs e)
{
if (Session.IsNewSession)
{
Response.Redirect(System.Web.Configuration.WebConfigurationManager.AppSettings["HomePage"]);
}
}
protected void Application_Error(Object sender, EventArgs e)
{
System.Exception oops = Server.GetLastError();
//Injection attack error handling
if (oops.GetBaseException() is System.Web.HttpRequestValidationException)
{
Response.Redirect("ErrorPage.aspx");
}
}
</script>
You have something which is trying to access a variable which is set to null (or hasn't been initialized). Do you have anything in the Global.asax or anything that fires on the start of the application? Do you have any asynchronous operations that fire on the start of the application?
Check on your Home.aspx page to see what is happening there. It looks like your application redirects to that page, so I would guess that on either the init or page_load event there is something which is executing that it causing the problem.
System.Exception oops
I think that this is source of problems. When there is no object returned from
Server.GetLastError();
then you will get NullReferenceException on line
oops.GetBaseException()
It makes perfect sense. On first run, oops is null (because no error occured before), thus throwing NullReferenceException. On second page refresh, GetLastError() returns object reffering previous errror (NullReferenceException) and page is displayed. Always check objects for null before accessing them.
Anyway, you can always try catching all runtime exceptions (Debug->Exceptions->Common Language runtime) and see where a problem is.
Sounds like an initialization issue. You're probably trying to use a resource before it's initialized, but by the time you refresh it's had time to be initialized.