Intermittent NullReferenceException when closing WPF application - wpf

I have a WPF application with a third party chart control hosted in a WindowsFormsHost. When the application is closed a NullReferenceException is intermittently thrown (about one in every ten closes).
We are plotting real time data on the chart. For plotting we are using Control.Invoke.
Here is the stack trace of the exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Media.MediaContext.RegisterICompositionTargetInternal(ICompositionTarget iv)
at System.Windows.Interop.HwndTarget..ctor(IntPtr hwnd)
at System.Windows.Interop.HwndSource.Initialize(HwndSourceParameters parameters)
at System.Windows.Forms.Integration.ElementHost.OnHandleCreated(EventArgs e)
at System.Windows.Forms.Control.WmCreate(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Integration.ElementHost.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Related

How to fix WPF render exception on floating panel resize?

EDIT: This happens because the dockable panel is semi-transparent when it's moved to floating. The fix was to disable transparency.
I use a custom panel-feature (3rd party, non-public NuGet) that has visual-studio like dockable panels. If I float a panel and resize it (couple of times) on Citrix XenApp it crashes. With following stack in log file (only few lines).
Unhandled exception. System.Runtime.InteropServices.COMException (0x88980406): UCEERR_RENDERTHREADFAILURE (Exception from HRESULT: 0x88980406)
at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
at System.Windows.Media.MediaContext.CompleteRender()
at System.Windows.Interop.HwndTarget.OnResize()
at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
It does not happen when I run it in any environment except Citrix. And it can be reproduced in all customer environments with same Citrix version. This was not reproducable with older version of Citrix XenApp but it's not possible to ask customers to downgrade.
This happens with Citrix version 7.6 on 2012 R2. Seems to happen on all 7.6 and one 7.9 installations.
Does not happen on 6.5 on 2008 R2.

NullReferenceException from PresentationFramework.dll

I'm fighting with a strange NullReferenceException that is apparently fired from the GetNameCore() function of the ItemAutomationPeer class.
The details of the exception are below but the really intriguing aspect is that it doesn't occur on my development machine running Windows 7, or other Windows 7 computers we have tested with. It only happens on my Windows 8 Pro test machine.
The exception is thrown apparently when attempting to edit a cell in a WPF DataGrid control.
I've been trying to track it down all day without success. I tried debugging the process remotely using Visual Studio and stepping through the code but none of the user code seems to be triggering the exception. It's obviously executed by a sequence of events inside of the PresentationFramework.Dll and the exception just bubbles up through the AppDomain and eventually crashes the application.
If anybody can think of anything that might be causing this, or a way to fix it it would really help.
Exception Type: System.NullReferenceException
Exception Message: Object reference not set to an instance of an object.
Method Information: System.String GetNameCore()
Exception Source: PresentationFramework
Stack Trace
at System.Windows.Automation.Peers.ItemAutomationPeer.GetNameCore()
at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
at System.Windows.ContextLayoutManager.fireAutomationEvents()
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.AnimatedRenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
After a lot of back-and-forth with the remote debugger, and nearly fruitless searches online I was able to track down the issue to a couple of miss-behaving ItemAutomationPeer instances.
When I ran into this issue I had zero knowledge about UI Automation and how it is supported in the WPF framework. In fact, when AutomationPeer had me thinking of COM interop for some reason so I chased the wrong issue for a while. If you are reading this and don't know what UI Automation is perhaps starting here and here might give you an idea as far as what UI Automation means in the context of WPF.
In my case, it turns out that the reason why the application was crashing on the Windows 8 test machine yet it was working fine on my development machine (and countless other computers that it had been deployed to) was that the Windows 8 machine had some sort of UI accessibility application (or some other UI Automation client) running. As soon as I started the Narrator application on my Windows 7 development machine I was able to get the app to crash just the same..
Once I understood the root problem, I still was unable to further debug this to find out exactly which control was causing the problem but more reading online seemed to point in the general direction of custom controls and so I started a process of elimination to determine which custom WPF controls were guilty. I found two custom controls - one that extended a DataGrid, and another that extended a ListBox.
Finally, the solution to the problem in my case was to create custom classes that extend the ItemsControlAutomationPeer base class and to provide those as automation peers on each of the custom controls that had issues by overriding the OnCreateAutomationPeer method.
protected override AutomationPeer OnCreateAutomationPeer()
{
return new ControlSpecificCustomAutomationPeer(this);
}
Where the ControlSpecificCustomAutomationPeer class might looks something like this at the very least:
public class ControlSpecificCustomAutomationPeer
: ItemsControlAutomationPeer
{
public ControlSpecificCustomAutomationPeer(ItemsControl owner)
: base(owner)
{
}
protected override string GetNameCore()
{
return ""; // return something meaningful here..
}
protected override ItemAutomationPeer CreateItemAutomationPeer(object item)
{
return new CustomDummyItemAutomationPeer(item, this);
}
}
public class CustomDummyItemAutomationPeer
: System.Windows.Automation.Peers.ItemAutomationPeer
{
public CustomDummyItemAutomationPeer(object item, ItemsControlAutomationPeer itemsControlAutomationPeer)
: base(item, itemsControlAutomationPeer)
{
}
protected override string GetNameCore()
{
if (Item == null)
return "";
return Item.ToString() ?? "";
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
return System.Windows.Automation.Peers.AutomationControlType.Text;
}
protected override string GetClassNameCore()
{
return "Dummy";
}
}
This issue for me was reliably reproducible with turning on Narrator and scrolling in a treeview that was using virtualisation with VirtualizationMode set to Recycling. Setting it to Standard led to a very slight performance hit, but the crash no longer occurs.
I chose to catch the error and handle it as a 'non-fatal' error.
private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
if (e.Exception.Source?.ToString() == "PresentationFramework")
{
e.Handled = true;
Postgres.LogException(e.Exception, false);
return;
}
HandleException(e.Exception);
e.Handled = true;
Shutdown();
}
FYI, this bug will be fixed in a future release of .Net 4.8.
https://developercommunity.visualstudio.com/content/problem/575165/vs-1604-ide-crash-argumentnullexception.html

How can I avoid the overflow when wheel scolling WPF DataGrid

When I use the mouse wheel to scroll the WPF Toolkit DataGrid on a Vista 64 Machine I get a cryptic low level error:
at System.IntPtr.op_Explicit(IntPtr value)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
I logged an issue on CodePlex.
But has anyone found a way to resolve this already?
I just run into this issue myself.
Not sure if it is still usefull to you but here is the fix I found in case anyone else needs it as well.
I found this thread in the OpenTK project that smelled a lot like the problem I was having for a WPF project in a vista 64 machine. Like explained in that thread, the problem seems to be a misshandled sing bit on the wParam of the MouseWheel message. The Overflow exception happens in the HwndMouseInputProvider call when it tries to cast the wParam IntPtr to an int.
So the workaround is adding a hook to filter windows messages on the main window. The hook callback checks the value of wparam for the WM_MOUSEWHEEL message. If the value overflows then the value shifter around to recover the right bit information, the current message is marked as handled, and a new message is posted with the new value.
public partial class Window1 : Window
{
private const int WM_MOUSEWHEEL = 0x020A;
public Window1()
{
InitializeComponent();
SourceInitialized += (o, e) =>
{
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
};
}
[DllImport("user32.dll")]
private static extern IntPtr PostMessage(IntPtr hwnd, IntPtr msg, IntPtr wParam, IntPtr lParam);
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case WM_MOUSEWHEEL:
// Check that wParam won't cause an OverflowException
if ((long)wParam >= (long)Int32.MaxValue)
{
// Filter the evenet
handled = true;
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
// Repost the event with the proper value
PostMessage(source.Handle, new IntPtr(msg), new IntPtr((long)wParam << 32 >> 32), lParam);
}
break;
}
return IntPtr.Zero;
}
This works well for me. If anyone can add or correct anything would be great!
K
This bug is within Microsoft's libraries and it is unbelievable that its still there.
To circumvent it presuming you have Visual Studio and you are the developer:
Right click on the project and select -> Properties
Select the Build tab.
Platform Target: x86
Then rebuild the project.
Background:
I had a perfectly good program working on 32 bit OS's. Then I bought a new laptop with Windows 7 64 Bit OS. Installed Visual Studio and my solutions. One project that processes windows messages to handle user input with WndProc failed. Yours is similar processing mouse messages.
After finding no patch by Microsoft's Visual Studio team, I changed the platform target from "Any CPU" to "x86", redeployed it to the 64 Bit OS, and saw program operate correctly. This was the only change.

A WPF App fails when coming out of hibernate mode

I have a WPF application that fails to come out of the timed sleep, followed by hibernate.
The render thread seems to be failing during initialization. I tried removing hardware acceleration to check that it's not graphics card related, but that did not help.
Here is an exception along with the stacktrace:
ERROR An unspecified error occurred on the render thread.
Stack trace: at System.Windows.Media.MediaContext.NotifyPartitionIsZombie(Int32 failureCode)
at System.Windows.Media.MediaContext.NotifyChannelMessage()
at System.Windows.Interop.HwndTarget.HandleMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
I googled around, and people suggest that it might have something to do with AllowsTransparency property being set to true; however, i did not see this issue when running a simple test app.
Any ideas about the exception and possible causes/solutions are highly appreciated.
Try this:
967634 FIX: You may experience several issues when you render graphics by using Windows Presentation Foundation (WPF) in an application
967634
Note: Unfortunately, you'll probably have to call. However, it's free even if they charge you at first, they will refund your money if all you do is ask them for the fix.

unhandled exception Handler in .Net 3.5 SP1

I'm converting my own web browser use WPF from Windows XP to Windows 7.
when I test on Windows XP, It has no error and exceptions.
But I convert and test on Windows 7 with Multi-touch Library, My Browser occurred unhandled exception.
Source: PresentationCore
Message: An unspecified error occurred on the render thread.
StackTrace:
at System.Windows.Media.MediaContext.**NotifyPartitionIsZombie**(Int32 failureCode)
at System.Windows.Media.MediaContext.NotifyChannelMessage()
at System.Windows.Interop.HwndTarget.HandleMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
InnerException: null
I want to know where the bug occurred. That Trace Message are garbage information for me.
I already googling to know that message, but i never found any information.
How do I get exactly function where the bug occurred? please tell me something.
I encountered a similar problem myself so I thought I should document it here for others too.
My WPF application runs fine in .net 3.0 / 3.5 or 4.0. However, using a multi-touch screen would cause crashes due to multiple stylus inputs being unhandled:
System.ArgumentException was unhandled
Message="StylusPointDescription cannot contain duplicate StylusPointPropertyInfos.\r\nParameter name: stylusPointPropertyInfos"
Source="PresentationCore"
ParamName="stylusPointPropertyInfos"
It turns out this is a debug in .net 3.0 / 3.5 that is addressed (in theory) with this hotfix from MS:
http://thehotfixshare.net/board/index.php?showtopic=14251
However, that actually never worked for me.
Currently the only work around I have found for this multi-touch crash is to upgrade to VS2010 and use .NET 4.0. (as this bug was fixed in WPF 4 and back ported to 3.5 I believe)

Resources