Cannot navigate to another page - xaml

I have a button and a tapped event:
private void btnSetLocationName_Click_1(object sender, RoutedEventArgs e)
{
ApplicationModel.LocationName = locationName.Text;
Frame.Navigate(typeof(GroupsPage));
}
I want to just navigate to another page. Unfortunately, Frame.Navigate does not work. I have also tried to make sure it runs in the GUI thread:
await this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => Frame.Navigate(typeof(GroupsPage)));
However, it should do, as the click handler for the button runs in the GUI thread.
The following error occurs:
Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

OK, after commenting out bits of code until it worked, it turns out I had an empty OnNavigatedTo override:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//base.OnNavigatedTo(e);
}
If you uncomment base.OnNavigatedTo it now works.
I think what threw me was that the error occurred when navigating FROM a page with this empty override. Also, the cryptic error message didn't help much.

Related

Invoking Message dialog from Settings Flyout causes Message Dialog to flicker

I'm trying to invoke messagedialog from setting flyout for my Windows 8 Metro app but it's causing the message dialog to flicker. Below is the code.
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
SettingsPane.GetForCurrentView().CommandsRequested+=settings_CommandsRequested;
}
private void Settings_CommandsRequested(SettingsPane sender, SetttingsPaneCommandsRequestedEventArgs args)
{
SettingsCommand cmd = new SettingsCommand("test","test1232",new UICommandInvokedHandler(CreateDialog));
args.Request.ApplicationCommands.Add(cmd);
}
private void CreateDialog(IUICommand command)
{
if (ReferenceEquals(command.Id, "cmd"))
{
MessageDialog md = new MessageDialog("Hi");
md.ShowAsync();
}
}
I've contacted official microsoft dev-support and their response was:
"MessageDialog is not recommended within the SettingsFlyout".
So in case you want to implement something simillar to support user's decision from the SettingsPane, you should either:
1) Enable toggling feature in the Flyout.
2) Desiging the SettingsFlyout so it lets the user make decision (for example in Logout cases, add Yes/no buttons inside the settingsFlyout) - Thats the option I chose.

Webview CapturePreviewToStreamAsync error

I am trying to get a screenshot of WebView in a Windows Store app with the following piece of code.
IRandomAccessStream ir = new InMemoryRandomAccessStream();
await scenarioDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
webView.CapturePreviewToStreamAsync(ir).AsTask().Wait();
});
But for some reason, I am hit with System.InvalidOperationException and message
"A method was called at an unexpected time."
The thread here is different but I verified the RunAsync callback is running on correct thread.
Edit: I tried invoking CapturePreviewToStreamAsync() directly using another button click event and it works.
private async void captureButton_Click(object sender, RoutedEventArgs e)
{
IRandomAccessStream ir = new InMemoryRandomAccessStream();
await webView.CapturePreviewToStreamAsync(ir);
}
I also verified the thread ID in both button click event and the delegate in the RunAsync are same. Not sure what I am missing here..
Thanks!

NavigationService.Navigate throws an exception and invokes Application_UnhandledException in WP8

I am developing a simple WP8 application using VS 2013. I have a MainPage.xaml and added a new page called Page1.xaml. I have a list of options on screen when a user clicks on "new item" I want to open a new page to add new item (Page1.xaml for instance).
On the list selection changed event I have written the following code:
private void OptionssList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selection = (MenuItem) e.AddedItems[0];
switch (selection.Id)
{
case 0:
break;
case 1:
break;
case 2:
this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
break;
case 3:
break;
default:
break;
}
}
When I try to debug the application, I notice that the constructor of Page1.xaml is invoked if I had an OnNavigatedTo event handler it is also been invoked however after all this an Unhandled exception is thrown. There is no code that I can see when the exception is thrown however it invokes the Application_UnhandledException event handler.
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
The exception details is as shown below:
System.NullReferenceException was unhandled
Message: An unhandled exception of type 'System.NullReferenceException' occurred in System.Windows.ni.dll
Additional information: Object reference not set to an instance of an object.
I would like to know if I am missing something. I referred to the sample it also shows similar way to Navigate, did not notice any things fancy.
i know this may be a very stupid question, your code looks fine to me, is your page not maybe in another folder? I always put my pages in a folder called UI, so my code will look something like this:
/folder1/folder2/pagename
this.NavigationService.Navigate(new Uri("/UI/Generics/Page.xaml", UriKind.Relative));
Just make sure of that, cause that usually get me.

Unhandled exception handler not called for Metro / WinRT UI async void event handler

Consider the following to be extracts from a Windows 8 Metro / WinRT app, which have been reduced to the bare minimum required to show the anomaly:
public class App : Application
{
public App()
{
UnhandledException += (sender, e) => e.Handled = true;
}
}
public class MainPage : Page
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
}
So given a Metro UI with two buttons and their click event handlers, the only difference is that the second event handler is marked as async.
Then clicking on each button, I would expect the UnhandledException handler to be called in both cases, since they (should) both be entered via the UI thread and associated synchronization context.
My understanding is that, for async void methods, any exceptions should be captured and 'rethrown' (preserving the original stacktrace) via the initial synchronization context, which is also clearly stated in the Async / Await FAQ.
But the UnhandledException handler is not called in the async case, so the application crashes! Since this challenges what I consider an otherwise very intuitive model, I need to know why! Yes, I know I could wrap the body of the handler in a try { } catch { }, but my question is why isn't the backstop UnhandledException handler called?
To further emphasise why this doesn't make sense, consider the following practically identical extracts from a WPF app also using async / await and targeting .NET Framework 4.5:
public class App : Application
{
public App()
{
DispatcherUnhandledException += (sender, e) => e.Handled = true;
}
}
public class MainWindow : Window
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
}
[There is a subtle difference that WPF has both an Application DispatcherUnhandledException event handler as well as an AppDomain UnhandledException event handler, but you can only mark the exception as 'handled' in the DispatcherUnhandledException, which aligns with the Metro / WinRT Application UnhandledException event handler above.]
Then clicking on each button, the DispatcherUnhandledException handler is indeed called in both cases, as expected, and the application does not crash.
Answered here: No UnhandledException fired from async event callback
It is a known limitation of WinRT. Hopefully, it gets fixed in the next update.
The solution in the following post worked for me, with one small change: I had to move AsyncSynchronizationContext.Register(); to the App.OnLaunched event
http://www.markermetro.com/2013/01/technical/handling-unhandled-exceptions-with-asyncawait-on-windows-8-and-windows-phone-8/
As explained in the documentation (source: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.application.unhandledexception.aspx):
It’s important to be aware of several limitations of the
Application.UnhandledException event. This event is only used with
exceptions encountered by the XAML framework. Exceptions encountered
by other Windows Runtime components or parts of the application that
are not connected to the XAML framework will not result in this event
being raised.
For example, if a different Windows component calls
into application code and an exception is thrown and not caught, the
UnhandledException event won’t be raised. If the application creates
a worker thread, and then raises an exception on the worker thread,
the UnhandledException event won’t be raised.
As pointed out in this conversation, only way to retrieve exceptions happening in a worker thread is to wrap them in a try/catch block. As a consequence, here's the workaround I'm using in my app: instead of using Task.Run or equivalents to execute code on a worker thread from the UI, I'm using this method:
/// <summary>
/// Runs code in a worker thread and retrieves a related exception if any.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="action">The action.</param>
public static void SafeRun(this DependencyObject target, Action action)
{
Task task = ThreadPool.RunAsync(o =>
{
try
{
action();
}
catch (Exception ex)
{
/* Call the same error logging logic as in the UnhandledException event handler here. */
}
}).AsTask();
task.Wait();
}
Bottom line is that to log all errors in your app, you should:
Subscribre to the UnhandledException event to get XAML stack related errors,
Wrap actions happening in a worker threads in a try/catch block.
From my point of view the only right answere was downvoted here (Try UnobservedTaskException event of TaskScheduler)
the problem is that you are using 'async void' where the exceptions cannot be handled. This is not a WinRT limitation but as design behaviour of async. You need to understand the async deeply to correctly implement exception handling here. See this article: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Exceptions are rethrown whe GC collects the tasks as unobserved. You can get them by registering TaskScheduler UnobservedTaskException event. Note - it takes some time till the exception arrives there, because it is noted with garbage collector.
Generally do not use 'async void', but in UI event handlers you have to, so this is thy only way..
This question is old; nonetheless, a similar issue now plagues my UWP app. Occasionally I must unwind the call stack by allowing an exception to propagate up it. I need the exception to reach the app's UnhandledException handler, but that wasn't always happening. This issue included the obvious case of throwing on a non-UI thread. It also included a non-obvious case, the causality of which I have yet to pin down, of throwing on the UI thread.
I conjured up the below solution. I catch the exception and then explicitly post it to the synchronization context. Due to the strange aforementioned issue, I must do this even while already running on the current synchronization context. Otherwise, the exception sometimes doesn't reach the UnhandledException handler.
private void Throw( Exception exception )
{
uiContext.Post( arg => throw exception, null );
throw new OperationCanceledException();
}
Try UnobservedTaskException event of TaskScheduler

Newbie trying to creating a Signal Event in MonoDevelop

Newbie here, just trying to create a signal event handler in response to an onclick menu item.
Aint working for me.
I click on the menu item, click signals, to the right of "Activated" where it says "Click to Add Handler", I type in "MyOnClick"
then it shoots me out an error. weird.
Exception has been thrown by the target of an invocation.
I am running this in windows 7 under a vm on macbook pro. Windows is not sharing folders from Macbook Pro so shouldn't be a UNC issue. Pathways seem fine.
Any ideas?
Ben
I have the same issue on mac and windows with current monodevelop versions.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NotImplementedException: The method or operation is not implemented.
It's annoying me so much! Must be some bug.
EDIT: I've solve it!
In source add method like this:
protected virtual void onClick (object sender, EventArgs e)
{
MessageDialog md = new MessageDialog (this, DialogFlags.Modal,
MessageType.Error, ButtonsType.Close, "Some error");
md.Response += delegate(object o, ResponseArgs args) {
if (args.ResponseId == ResponseType.Close)
Console.WriteLine ("Response: Closed");
else
Console.WriteLine ("Other response happened.");
};
md.Run ();
md.Destroy ();
}
Then switch to visual designer and instead double click on signal/method name just type in method name [this case] onClick (no brackets). This time a method is implemented and doesn't cause throwing error.
It work but is not as comfortable as double click.