System.ExecutionEngineException PropertyChanged - silverlight

If anyone can provide some help for this one, I'd be very grateful!
We are using: Silverlight 3 / MVVM / Blacklight DragDock Control / ComponentOne Silverlight Controls
I have a Silverlight application that relies heavily on the MVVM pattern. The application has seemingly been running fine, until recently. I have started to notice semi-random (semi-random = over a long enough period of time ~2 - 5 mins) I can reproduce a System.ExecutionEngineException coming from the PropertyChanged event being raised. The property name which the notification is being raised for is not always the same property name (the firing of the property change event happens in a base ViewModel class).
The code basically looks like this:
if (PropertyChanged != null) Application.Current.RootVisual.Dispatcher.BeginInvoke( () => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
The code works for everything else in the application. Basically everything that throws off a property changed event goes through this. I'm not sure why this is failing all of a sudden. Please throw some thoughts my way.
I've been knee deep in windbg trying to get some grasp on what is going on, and still have very little. I'd by happy provide a dump or any other information that might be helpful. Obviously, there is very little information given from this particular error...
Thank you ahead of time, David Justice

A question you might ask yourself: is this ExecutionEngineException happening in IE only and, for instance, not in FireFox?
I know Silverlight is supposed to be browser-independent, but I already encountered a similar known Silverlight-issue that occured randomly in IE only.
The fact that you get an ExecutionEngineException is pointing out that the SL runtime blows up for some reason.

This exception is quite the exotic one. If one gets thrown, it's Game Over, 0 Continues for the CLR. No managed code can catch that exception.
When I ran into it, it was the result of a driver writing into a buffer that wasn't marshaled properly and so was not pinned, and the CLR moved the buffer while the driver was writing into it. It wouldn't crash instantly, but usually happened after the mouse ran over the form's menu bar (which probably resulted in creating and destroying lots of small objects, which then lead to the CLR running the GC and compacting the managed heap). Even though one of my worker threads was communicating with the driver, it was the main thread that threw the exception, which made things way more confusing.
Make sure things are being marshaled properly. If ANYTHING is being passed back and forth to unmanaged code, make sure you use GCHandle to pin the objects.

Related

MVVM Application not Restoring State Correctly

I have built a class library that acts as a GUI framework that can be inherited by other projects. This application is based on projects Wild and Gemini.
My problem is that upon restoring Avalon Dock's layout using the standard serializer
var layoutSerializer = new XmlLayoutSerializer(manager);
where manager is type DockingManager. The manager restores and empty tab. My guess is that Caliburn Micro cannot find the stored ViewModel (named HomeViewModel). However, I am struggling to confirm this.
I believe my bootstrapper to be correct and that the MEF containers are being setup correctly to allow resolution of external types. I have debugged the project to a point where I think this issue is occurring and in the output window I can see Attach(Home) where the attach is occurring (note, "Home" is the display name of the HomeViewModel). However, I don't know what is wrong with the attach process as this is handled by MEF/Caliburn.
I am really stuck with debugging this an wondered if
Any one could offer any insightful advice as to how to proceed with the debugging process?
Anyone would be willing to take a look at the solution?
I have spent a hell of a lot of time debugging this without any luck and the problem is sufficiently esoteric and illusive as to render most posts here irrelevant to me.
Thanks for your time.
as discussed and after looking on the sample code provided, I understand that the following
HomeViewModel or can say LayoutItemBase is not supposed to be reopened as ShouldReopenOnStartup is set to false
if you close the application while leaving a document open for HomeViewModel it is restored on next start with blank view [Not OK]
Analysis
the SaveState method was correctly honoring ShouldReopenOnStartup value and was not emitting the state for the HomeViewModel but dock manager was still emitting an element for the document.
So upon next restart the LoadState does not find any stored state but a window was created as an element was present in the dock manager's layout state
<LayoutDocument Title="HomePP" IsSelected="True" IsLastFocusedDocument="True" ContentId="d716f824-cfff-4b54-8fd6-2d026a99369a" .../>
you did try to use e.Cancel property of Serialization callback to cancel the event, but seems like it is not supposed to prevent of loading a window but just simply to cancel the event if not needed.
Resolution
So the ideal approach is to close the documents which are not supposed to be restored before saving the layout
here is how I did
ShellViewmodel.cs : Line 279 method SaveState(string)
change the following code
if (!item.ShouldReopenOnStartup)
continue;
to
if (!item.ShouldReopenOnStartup)
{
//this item is not supposed to be restored so close the window before saving layout
IDocument doc = item as IDocument;
if (doc != null)
CloseDocument(doc);
continue;
}

Need to force refresh on a WPF Label

I am making an asynchronous call to a web service. Since it might take a few seconds there is a status Label used to let the user know what's going on. But even though the call is async the first call seems to block for a few seconds and the status label takes too long to get updated. In WinForms I could force the label to refresh (using Update() I think) but not in WPF. Any super easy ways to get this working?
Thanks,
Gerry
You could move the entire call logic into a QueueWorkUserItem or BackgroundWorker block. That way the first proxy initialization would not block the UIThread (before the async. Begin/End pattern kicks in). Assuming that you are using databinding the object exposing the property bound to the Label implemented INotifyPropertyChanged everything should happen automagically.
I'd (wildly) guess that the blocking is due to the creation/initialization of the service proxy classes. If so, you could try to create the proxy earlier, or call your asynchronous web service in another thread.
The general answer to your question about refreshing controls... I have always relied on data binding to do this. That won't help though if the main UI thread is stuck doing something. And if the UI thread is stuck, I don't know that there's any way to get it to draw.
There isn't a way to tell the label to refresh that will actually work in your case. If the UI is being blocked, it won't refresh. Basically, when you actually get to the point where you update the label's text, it will show in WPF. The only possible exception that I can think to that would be if you are using a non-WPF control but even then it should work.
My suggestion would be to update the label before you perform the first action (even before variables are initialized, since this might be where the issue actually is). Here is a pseudocode example of what I mean (just in case I wasn't clear):
private void KickOffProcess()
{
label1.Text = "Processing ..."; //This is where you need to move the label update code
AsyncCall();
}

WPF performance problem with CommandManager

We've created a new, quite complex, WPF application from the ground up and have run into a performance problem as the number of commands registered with the CommandManager increase. We're using simple lightweight commands in our MVVM implementation, however the third party controls we're using (Infragistics) do not, and call CommandManager.RegisterClassCommandBinding liberally to add RoutedCommands. The performance problem manifests itself as a perceived sluggishness in the UI when responding to user input, for example tabbing between controls is slow, text input is 'jerky' and popup animation is 'clunky'. When the app is first fired up the UI is snappy. As more screens containing Infragistics grids are opened the performance deteriorates.
Internally, the CommandManager has a private field named _requerySuggestedHandlers, which is a List< WeakReference>. I've used reflection to get a reference to this collection, and I've noticed that when I call .Clear(), the responsiveness of the UI improves back to its initial state. Obviously I don't want to go round clearing collections that I know little about, especially using reflection (!) but I did it to see if it would cure the performance problems, and voila it did.
Normally, this situation would clean itself up after a certain amount of time passes. However, the collection of WeakReferences (_requerySuggestedHandlers) will only get trimmed once a garbage collection is initiated, which is non-deterministic. Because of this, when we close down windows containing grids (Infragistics XamDataGrid), the CanExecute property for 'dead' grid commands continue to be evaluated unnecessarily, long after the window is closed. This also means that if we close down a number of windows, the performance is still sluggish until a garbage collect is initiated. I understand that this can happen on allocation, and I've seen that myself because if I open a further window this causes the initial memory (from the disposed Windows) to be collected and performance returns to normal.
So, given the above, here are my questions:
How, and from where, does CommandManager.InvalidateRequerySuggested() get called? I haven't found any documentation on MSDN that explains this in any great detail. I hooked up to the CommandManager.RequerySuggested event and it looks like it's being called whenever controls lose focus.
Is is possible to suppress CommandManager.InvalidateRequerySuggested() being called in response to user input?
Has anyone else run into this issue, and if so, how have you avoided it?
Thanks!
This sounds like one of the rare cases where deterministically calling GC.Collect() is the right thing to do. The ordinary argument against it is that the garbage collector is smarter than you are. But when you're dealing with WeakReference objects, you enter territory where you may know something that the garbage collector doesn't. Kicking off garbage collection is certainly better than clearing _requerySuggestedHandlers - among other things, it won't do anything to the WeakReference objects that point to controls that are still alive.
I'd choose this over trying to figure out how to suppress RequerySuggested, since that would screw up the behavior of those commands that you still care about.

Adding a user control "The Enumerator is not valid"

I'm using Visual Studio 2010 to create a small WPF application. I've created a user control that I am now trying to add to my main form. The user control does show up in toolbox but every time I try to drag the control to the form I get the error:
The enumerator is not valid because the collection changed.
I should know what's wrong and it is bugging me that I can't figure it out.
You have a bug in the constructor of the usercontrol - you are using a foreach-loop over an IEnumerable and while the loop is running, the IEnumerable is changed, this is not allowed with a foreach loop. Use a for loop instead if you are manipulating the Collection you are iterating over.
The problem here is that you don't know what code is throwing the exception.
WPF is terrible about exceptions, especially in constructors. The framework insists on catching and re-throwing a new exception, usually multiple times, and it's difficult to find the original stack trace. I've found the easiest way to track down this kind of error is to tell Visual Studio to stop as soon as the exception is thrown, rather than waiting until WPF has re-thrown it a couple of times and made the details difficult to dig out.
I don't have Visual Studio 2010 in front of me, but here's how to do this in VS2008 -- 2010 is probably similar:
Go to the Debug menu > Exceptions...
Next to "Common Runtime Language Exceptions", check the box in the "Thrown" column
Then debug your app again. It will stop at the line that's actually causing the problem, and it'll be much easier for you to see what's going on. And if you're still not sure why it's throwing an exception, you'll be able to post a code sample.
In order for a user control to function properly you need to have a constructor that takes zero arguments. This way the form designer has a way to render the control in a "default" manner.
I then overloaded my constructor to take the arguments I needed to actually run the control properly and everything worked as expected.
You need to:
Remove the DLL reference
Add a reference to your control
Rebuild the solution
Add your control. It should work!

Why Does WPF Swallow Databinding Exceptions?

I am in the process of learning WPF, and am puzzled by the fact that databinding exceptions do not cause a runtime/unhandled exception.
Can anyone explain the benefits of databinding working in this way? I'm assuming that there are benefits, but so far I don't see any (disclaimer: I am just getting started with databinding).
Links to resources that explain the theoretical (or practical) reasons for making this decision would work as well.
I don't know for sure, but I suspect it's because there's nowhere to handle the exception.
Suppose you have something whose properties you want to bind to, but sometimes that something is null. (For example, {Binding Name.Length}, where Name is a string property that might be null.) In this case you're happy for this to be a no-op, because you know the control will never be shown when the Name is null (due to a trigger say) or because you know this will be a transient condition while the binding source is loading its data.
Now suppose WPF propagated the NullReferenceException when trying to call Length on the null Name string. In procedural code, you'd catch this exception and swallow it because you knew it was benign. But you don't get to put an exception handler around the WPF binding code. It's called from somewhere deep inside WPF. So the exception would bubble all the way up to Application.Run, which is not a very useful place to catch it.
So rather than making you centralise your binding exception handlers all the way up in Application.Run, I think the WPF guys decided to swallow the exceptions themselves. Only a theory though...
I would argue it is because the cost of producing an Exception is prohibitive. The current implementation works even in the case there are some invalid bindings and in current form that can actually have a very significant effect on performance. Take this example, create a DataGrid that does binding and this load 1,000 records into it. Measure performance with all bindings correct and again with one of them wrong. The difference is considerable. Add on top of that standing up exception class instances and it could get out of control bad. Just my opinion.
I don't know why that is the default behavior, but there are ways around.
For example, even though it will not tell you about the binding error, the Output window will. You can kind of catch that using binding validations as well.
EDIT:
I found this article that has a very good idea to create test cases that will catch those annoying silent binding errors (and I loved the photo at the top of the article)
Here is link to a blog post where the blogger writes about a case where it argues that it does make sense that the binding errors are silent

Resources