Webview CapturePreviewToStreamAsync error - xaml

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!

Related

Enable - Disable a button while threading vsto for ms word

I'am very new to threading and quite unclear as to why this is happening in my code, when I click on a button that verifies hyperlinks in my document, I start a new thread that does the verification once it starts I want to disable the ribbon button and enable it again after thread finished but this is not happening and I dont know what is the mistake .Here is what I have tried so far:
public class Alpha :Ribbon1
{
// This method that will be called when the thread is started
public void Beta()
{
foreach() { //do something } after this loop ,enable the button again
button.enable=true //not applying
} }
private void button_Click(object sender, RibbonControlEventArgs e)
{
Alpha oAlpha = new Alpha();
// Create the thread object, passing in the Alpha.Beta method
Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
// MessageBox.Show("Please wait till the document is checked for invalid links");
// Start the thread
oThread.Start();
button7.Label = "Pls wait";
button7.Enabled = false;
}
Ribbon needs to be rendered again after enable/disable for change to take effect, you can do this by calling IRibbonUI.Invalidate()

Cannot navigate to another page

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.

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

Exception accessing XAML controls inside a task

If I try to access XAML controls inside a task (and task::then) my Metro XAML app always stops with an exception. The same code works without any problems outside the task. I didn't find any answer - what did I miss?
VS11 Debugger reports: Concurrency::unobserved_task_exception
Exception: The application called an interface that was marshalled for a different thread.
Many thanks for your help!
void MyClass::MyMemberFunction()
{
xamlStoryboard->Stop(); // ok
xamlImage->Source = ref new BitmapImage(); // ok
task<void> atask([this] ()
{
xamlStoryboard->Stop(); // exception!
xamlImage->Source = ref new BitmapImage(); //exception!
});
atask.then([this] ()
{
xamlStoryboard->Stop(); // exception!
xamlImage->Source = ref new BitmapImage(); //exception!
});
}
The atask.then() continuation code runs without exception if we add task_continuation_context::use_current()
as second parameter:
atask.then([this] ()
{
xamlStoryboard->Stop(); // now ok!
xamlImage->Source = ref new BitmapImage(); // now ok!
}, task_continuation_context::use_current());
You are calling your UI elements from a thread other than the UI/Dispatcher thread. You need to call your UI elements' methods using control.Dispatcher.InvokeAsync() or otherwise make sure you are not calling them from a background thread.

Monotouch: UIAlertView and WCF services, debugger.StackTrace

I'm currently using WCF in monotouch to call an existing service and a custom UIAlertView.
The problem is that if I create an UIAlertView as class instance and the I do the following:
public override void ViewDidAppear()
{
_alertView.Message = "Loading...";
_alertView.Show();
_client.GetDataAsync("test");
_client.GetDataCompleted += GetDataCompletedDelegate;
base.ViewDidAppear();
}
void GetDataCompletedDelegate(object sender, GetDataEventArgs)
{
// do someting with data
_alertView.Hide();
}
it works but this advice is written in console : UIAlertView: wait_fences: failed to receive reply: 10004003
else, if I try to run this code:
public override void ViewDidAppear()
{
using(CustomAV _alertView = new CustomAV())
{
_alertView.Message = "Loading...";
_alertView.Show();
_client.GetDataAsync("test");
_client.GetDataCompleted += delegate{
InvokeOnMainThread(delegate{
// do someting with data
_alertView.Hide();
});
};
}
base.ViewDidAppear();
}
the first time the code run, but now alert is shown. The second time the simulator can't startup. Couldn't register "com.yourcompany.wcftest" with the bootstrap server. Error: unknown error code. This generally means that another instance of this process was already running or is hung in the debugger.StackTrace. In this case I have to reboot the machine.
Thank you in advance.
EDIT:
Thank you Geoff, I've checked my code and into GetDataCompletedDelegate I've inserted a function that runs inside the UI Thread.
InvokeOnMainThread(delegate{
doSomething();
});
private void doSomething()
{
// do stuff here
_alertView.Hide();
}
The fency error continues to appear. If I use your solution inside doSomething() method, it works
_alertView.InvokeOnMainThread(delegate{
_alertView.Hide();
});
Why? Maybe I didn't understand, but in the first snippet of code do something() works in the UI thread!! Isn't true?
You have 2 seperate problems here.
1: _alertView.Hide () is not running on the UI thread (this is what causes the fences error)
2: In your second example you're disposing the UIAlertVeiw immediately after creating it, but you have a instance delegate dangled off it. This crashes the runtime in a hard way, and then when you run it again since the old crashed process is still running the simulator wont let you start a second instance.
Use case #1 but do _alterView.InvokeOnMainThread (delegate { _alertView.Hide (); });