WebView2 | CoreWebView2DownloadStartingEvent Error - c

I need help when i`m starting the webbrowser then i getting this error, i dont know why is it null
CoreWebView2 WebView2;
public TabViewItem CurrentTab;
public TabContent()
{
this.InitializeComponent();
Browser.CoreWebView2.DownloadStarting += DownloadStarting_Event;
}
private void DownloadStarting_Event(CoreWebView2 sender, CoreWebView2DownloadStartingEventArgs args)
{
Debug.WriteLine("This is a test");
}
Exception thrown: 'System.ArgumentException' in System.Private.CoreLib.dll
An exception of type 'System.ArgumentException' occurred in System.Private.CoreLib.dll but was not handled in user code
Delegate to an instance method cannot have null 'this'.

Its not totally clear from the code you have shared, but it doesn't look like you are waiting for the WebView2 element to initialize its CoreWebView2 property before using the CoreWebView2 property. This is described in detail in the WebView2 reference documentation.
In brief, you must await a successful call to WebView2.EnsureCoreWebView2Async() or wait until the WebView2.CoreWebView2InitializationCompleted event is raised successfully before using the WebView2.CoreWebView2 property.

Related

Duplex channel callback calls method that throws exception. Where does the execption go?

And how can I present it to the user?
This post : WCF Duplex: How to handle thrown exception in duplex Callback is very close to my scenario. And this post is useful for helping me re-establish the connection when the channel is faulted.
I have a Publishing application Pub, and a subscribing WPF application Sub. The Pub sends a message and the Sub has subscribed for a callback using a duplex channel.
Sub.ViewModel.ReactToChange(sender, e) tries to read some data, but is unable to and throws an exception.
DispatcherUnhandledException doesn't catch it (I didn't really expect it to.)
AppDomain.CurrentDomain.UnhandledException doesn't catch it (that does surprise me)
The end result is I have an application that is still running, and no exception message is shown to the user so they can correct the problem. Is there a way I can show that exception to the user?
This is a bit tricky, but the only way I've found. I hope this helps others.
The idea is to not let an exception get thrown, but instead create an UnhendledExceptionEventArg and pass it up to your UI layer. Here is some example code:
public class BuggySubscriber : IDisposable
{
public BuggySubscriber(string dataSourceName)
{
SyncContext = SynchronizationContext.Current;
Subscriber = new MockSubscriber(dataSourceName);
Subscriber.Refreshed += OnDataChanged;
}
public SynchronizationContext SyncContext { get; set; }
public event EventHandler<UnhandledExceptionEventArgs> ExceptionOccurred;
// Bouncing Exception Step 3
private void OnExceptionOccured(Exception ex)
{
var callback = new SendOrPostCallback(delegate
{
var handler = ExceptionOccurred;
if (!ReferenceEquals(handler, null))
handler(this, new UnhandledExceptionEventArgs(ex, true));
});
SyncContext.Post(callback, null);
}
void OnDataChanged(object sender, ServiceModel.DataChanged.DataChangedEventArgs e)
{
// Bouncing Exception Step 1 & 2
OnExceptionOccured(new NotImplementedException());
}
So this is the "Sub" code. In the WPF application I add the following when the app starts:
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
BuggySubscriber.ExceptionOccurred += Sub_ExceptionOccurred;
...
}
// Bouncing Exception Step 5
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
if (!ReferenceEquals(exception, null))
ShowErrorMessage(exception);
}
// Bouncing Exception Step 4
void Sub_ExceptionOccurred(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
if (!ReferenceEquals(exception, null))
throw exception;
}
So now let's try to follow the bouncing exception.
In real life, the subscriber was notified and an exception occurs and is caught. (In my sample, I don't show that.)
Then the OnExceptionOccurred(Exception ex) is called.
That then creates the SendOrPostCallback using the ExceptionOccurred event and then does a Post to the current SynchronizationContext.
The WPF application that registered for the ExceptionOccurred (Now if you like, you could handle the exception message here... I chose to use two paths for exceptions rather than three.) It casts and throws the Exception.
Now the CurrentDomain_UnhandledException processes it and shows an error message to the user (right before it exits).
I'm sure there are many variations on this, but this does show some of the trickier code that I could not find in one place.
NOTE: This does not solve any channel problems. If you have an exception you can recover from you will still need to reestablish the channel since it will be faulted or closed.

WPF - Catch exceptions in code executed by SimpleMVVM messagebus

I'm building a WPF application using the SimpleMVVM framework and I'm having trouble catching exceptions. I use the MessageBus of SimpleMVVM to send a message to another viewmodel. This all works fine, but I noticed that exceptions raised in the code executed by the messagebus get suppressed. Here's what I've got so far:
My MainWindow contains a button that fires a TempCommand on the MainWindowViewModel. This command in turn calls the Test method (shown below), which sends out a notification message using the MessageBus of SimpleMVVM.
private void Temp()
{
SendMessage("Temp", new NotificationEventArgs());
}
My MainWindow also contains a Frame with content. The ViewModel of this content, CustomerViewModel, has registered to receive these notifications in its constructor:
public CustomerDetailsViewModel(ICustomerServiceAgent agent)
{
RegisterToReceiveMessages("Temp", Temp);
}
Where the Temp method simply throws an exception:
private void Temp(object sender, NotificationEventArgs args)
{
throw new NotImplementedException("Somewhere, something horrible happened");
}
When I debug the application, I clearly see the Temp method being called and the exception being raised. But for some reason, that's all. The application is unaffected and my exception trapping code is unaware of the exception.
I trap exceptions in two ways. The first is by handling the event on the Dispatcher:
<Application x:Class="MyApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"
DispatcherUnhandledException="App_DispatcherUnhandledException">
Where the code-behind looks like:
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
Log("Exception: " + e.Exception.Message);
e.Handled = true;
}
public static void Log(string message)
{
File.AppendAllText(#"D:\Temp\log.txt", "[" + DateTime.Now.ToString("F") + "] [" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "] " + message + Environment.NewLine);
}
This code catches some exceptions, but not all. I found out that WPF suppresses databinding exceptions by default. Because my ViewModels are bounded through the DataContext property on my view, I thought this was the problem. I found this article, which defines a TraceListener that uses the PresentationTraceSources class. Databinding exceptions now get caught, but... Not the exceptions thrown in the code executed through the MessageBus.
I've created a solution demonstrating this behavior, it can be downloaded here.
And this is where I'm stuck. What am I missing? How do I catch these exceptions?
Big thanks in advance.
JP
I think it is a bug or problem with the implementation of the MessageBus in SimpleMVVM.
Cause multiple subscribers can subscribe to a token, the current implementation ensures that each subscribed method gets called even when one registered method throws an exception. In this case the exception is catched and written out to the Console.
The method that is responsible to call a subscribed method is SafeNotify
private void SafeNotify(Action method, bool post) {
try {
// Fire the event on the UI thread
if (post){
if (Dispatcher.CheckAccess()){
method();
}
else{
Dispatcher.BeginInvoke(method);
}
}
// Fire event on a ThreadPool thread
else{
ThreadPool.QueueUserWorkItem(o => method(), null);
}
}
catch (Exception ex){
// If there's an exception write it to the Output window
Debug.WriteLine(ex.ToString());
}
}
When the method call gets queued in the ThreadPool, you have no chance to handle the thrown exception. See also this post for further information.
The only option you have is to ensure that the code of your own registered methods is always surrounded by a try-catch-block.

how can I get the actual exception from remote webservice in silverlight client?

[WebMethod]
public void Test()
{
throw new ArgumentNullException();
}
I want get the actual Exception (eg:ArgumentNullException) in silverlight client webservice call completed method. how can i implement it?
The Completed event should have two parameters it is expecting back: object sender, and the event's CompletedEventArgs collection, named e.
The completed event args contains an Exception, e.Error, which should be the exception that was returned.

Throw new Exception and Application_UnhandledException

My Scenario:
I'm using a Silverlight MVVM pattern. All my view models inherit from a BaseViewModel class that maintains some basic values and behaviours.
One of these behaviours determines if the user is authorised to use particular functionality and returns a boolean.
If the function is not located, I want to throw a new exception and catch this in the App.xaml Application_UnhandledException method, and raise my own exception event, something like this:
protected bool IsFunctionEnabled(string FunctionName)
{
//fetch the function / role
if (_FunctionRoles().ContainsValue(FunctionName))
{
KeyValuePair<int, string> kvp = _FunctionRoles().GetEntryByStringValue(FunctionName);
//determine if the user has been assigned to this role
return (_UserRoles().ContainsKey(kvp.Key));
}
//throw an exception when the function name is not located.
throw new Exception(string.Format(Constants.UNHANDLED_EXCEPTION, "security role assignment: '" + FunctionName + "' not located."));
}
I then want this automatically picked up in App.XAML:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
// throw this message to the main application exception event handler
ApplicationEvents.OnExceptionOccurred(this,
new ExceptionEventArgs(e.ExceptionObject,
null,
ExceptionImportance.Critical));
}
My Problem
When the exception is thrown, it is not getting bubbled up the stack. When debugging the exception is hit over and over again, no other code is getting run.
What am I doing wrong here?
Thanks,
Mark
I think this is occurring because the exception is getting thrown outside of the UI thread, so there is no other code "waiting to run". Triggering an event here means writing a lot more code, but does allow the UI thread to subscribe to this and render a message in the UI properly.

How can I get the current exception in a WinForms TraceListener

I am modifying an existing WinForms app which is setup with a custom TraceListener which logs any unhandled errors that occur in the app. It seems to me like the TraceListener gets the message part of the exception (which is what gets logged), but not the other exception information. I would like to be able to get at the exception object (to get the stacktrace and other info).
In ASP.NET, which I am more familiar with, I would call Server.GetLastError to get the most recent exception, but of course that won't work in WinForms.
How can I get the most recent exception?
I assume that you have set an event handler that catches unhandled domain exceptions and thread exceptions. In that delegate you probably call the trace listener to log the exception. Simply issue an extra call to set the exception context.
[STAThread]
private static void Main()
{
// Add the event handler for handling UI thread exceptions
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
// Add the event handler for handling non-UI thread exceptions
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
...
Application.Run(new Form1());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MyTraceListener.Instance.ExceptionContext = e;
Trace.WriteLine(e.ToString());
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
// similar to above CurrentDomain_UnhandledException
}
...
Trace.Listeners.Add(MyTraceListener.Instance);
...
class MyTraceListener : System.Diagnostics.TraceListener
{
...
public Object ExceptionContext { get; set; }
public static MyTraceListener Instance { get { ... } }
}
On the Write methods in MyTraceListener you can get the exception context and work with that. Remember to sync exception context.

Resources