System.ComponentModel.Win32Exception occurs with Parameter is incorrect message while accessing control through automation - c#

I am trying to access a wpf control using AutomationElement but sometimes it throws and exception.
Below is the code:
if (automationElement.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
{
ValuePattern valuePattern = pattern as ValuePattern;
valuePattern.SetValue(valueToBeSet);
}
I am doing till here, this triggers some methods calls in MS.Win32.UnsafeNativeMethods which then gives the exception.
Stack trace from event log:
Exception Messages:
Win32Exception : The parameter is incorrect
Type : System.ComponentModel.Win32Exception, System, Version=4.0.0.0, Culture=neutral
Message : The parameter is incorrect
Source : WindowsBase
NativeErrorCode: 87
ErrorCode : -2147467259
TargetSite : Int32 GetWindowText(System.Runtime.InteropServices.HandleRef, System.Text.StringBuilder, Int32)
Stack Trace : at MS.Win32.UnsafeNativeMethods.GetWindowText(HandleRef hWnd, StringBuilder lpString, Int32 nMaxCount)
at System.Windows.Automation.Peers.WindowAutomationPeer.GetNameCore()
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.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 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
The WPF control is standard WPF control(No customization). I am not able to cause of this error. I believe it is the window handle which is incorrect(param for GetWindowText) but have no idea how to check this? In case it is something else please do tell.

Related

using MySqlBulkCopy of MySqlConnector to upload a datatable into MySql. Exception thrown

Well i switched to MySqlConnector in order to be able to use its functionality to upload a Datatable into a MySql Table.
I'm following their simple example for this function as follow :
DataTable datatable = Globals.ds.Tables["Song"];
using (var connection = new MySqlConnection(Globals.connString + "AllowLoadLocalInfile = true;"))
{
await connection.OpenAsync();
var bulkCopy = new MySqlBulkCopy(connection);
bulkCopy.DestinationTableName = "Song2";
await bulkCopy.WriteToServerAsync(datatable);
}
The Song2 table is a empty copy of the Song table that contains 17000 lines and that is feeding the Datatable through a adapter.fill() method (i even did a .FillSchema() before).
When i run this, i have 2 exceptions :
The first one (the innerexception) is Failed to read the result set. while the second one is "System.Reflection.TargetInvocationException"
Anyone can help ?
Thanks in advance
EDIT :
Here is the call stack
System.Reflection.TargetInvocationException
HResult=0x80131604
Message=Une exception a été levée par la cible d'un appel.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
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.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at MP3_manager.Program.Main() in C:\Users\Utilisateur\source\repos\MP3-manager\MP3-manager\Program.cs:line 23
This exception was originally thrown at this call stack:
MySqlConnector.Utilities.SocketAwaitable.GetResult() in SocketAwaitable.cs
MySqlConnector.Protocol.Serialization.SocketByteHandler.DoWriteBytesAsync(System.ReadOnlyMemory<byte>) in SocketByteHandler.cs
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>.ConfiguredValueTaskAwaiter.GetResult()
MySqlConnector.Protocol.Serialization.ProtocolUtility.WritePacketAsync.__WritePacketAsyncAwaited|8_0(System.Threading.Tasks.ValueTask<int>, byte[]) in ProtocolUtility.cs
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>.ConfiguredValueTaskAwaiter.GetResult()
MySqlConnector.Core.ServerSession.SendReplyAsyncAwaited(System.Threading.Tasks.ValueTask<int>) in ServerSession.cs
...
[Call Stack Truncated]
Inner Exception 1:
MySqlException: Failed to read the result set.
Inner Exception 2:
SocketException: Une connexion existante a dû être fermée par l’hôte distant

WPF DependencyProperty.UnsetValue throws 'System.InvalidOperationException'

I have a WPF application that throws System.InvalidOperationException when pressing Alt or Ctrl keys because of a DependencyProperty.UnsetValue. Stack trace and debug output give no hint who is causing the exception. Here is the stack trace:
WindowsBase.dll!System.Windows.DependencyObject.GetEffectiveValue(System.Windows.EntryIndex entryIndex, System.Windows.DependencyProperty dp, System.Windows.RequestFlags requests) Unknown
WindowsBase.dll!System.Windows.DependencyObject.GetValueEntry(System.Windows.EntryIndex entryIndex, System.Windows.DependencyProperty dp, System.Windows.PropertyMetadata metadata, System.Windows.RequestFlags requests) Unknown
WindowsBase.dll!System.Windows.DependencyObject.GetValue(System.Windows.DependencyProperty dp) Unknown
PresentationFramework.dll!System.Windows.FrameworkElement.FocusVisualStyle.get() Unknown
PresentationFramework.dll!System.Windows.Input.KeyboardNavigation.ShowFocusVisual(System.Windows.DependencyObject element) Unknown
PresentationFramework.dll!System.Windows.Input.KeyboardNavigation.ProcessInput(System.Windows.Input.InputEventArgs inputEventArgs) Unknown
PresentationCore.dll!System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(System.Windows.Input.ProcessInputEventHandler postProcessInput, System.Windows.Input.ProcessInputEventArgs processInputEventArgs) Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input) Unknown
PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport) Unknown
PresentationCore.dll!System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawKeyboardActions actions, int scanCode, bool isExtendedKey, bool isSystemKey, int virtualKey) Unknown
PresentationCore.dll!System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(ref System.Windows.Interop.MSG msg, ref bool handled) Unknown
PresentationCore.dll!System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(ref System.Windows.Interop.MSG msg, System.Windows.Input.ModifierKeys modifiers) Unknown
PresentationCore.dll!System.Windows.Interop.HwndSource.OnPreprocessMessage(object param) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority priority, System.Delegate method, object arg) Unknown
PresentationCore.dll!System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(ref System.Windows.Interop.MSG msg, ref bool handled) Unknown
WindowsBase.dll!System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(ref System.Windows.Interop.MSG msg) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) Unknown
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) Unknown
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) Unknown
> ProInspectX14x64.exe!ProInspectX.App.Main() Line 48 C#
How can I understand which FrameworkElement is causing the exception?

NullReferenceException after calling ShowDialog() in System.Windows.Interop.HwndSource.OnPreprocessMessage

I have a WPF application and sometimes app crashes just after I call ShowDialog() on Window (http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog%28v=vs.110%29.aspx)
When application starts I open a main dialog (it's always opened) then I want to open a new child dialog (see below ShowModal method), and usually everything works fine but sometimes after calling ShowDialog() (see below code snippet) it throws System.NullReferenceException in PresentationFramework.dll in method System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param).
After calling ShowDialog() the window is shown in App, then when I click anywhere on it (for example a textbox), it throws NullReferenceException .
I'm unable to reproduce crashing pattern it behaves completely randomized. And I'm starting to go crazy because I don't have any clue how to trace where is the problem.
This is the snippet from my code:
private Window Wnd { get; set; }
public bool ShowModal(ViewModel vm)
{
if( Wnd == null )
{
throw new InvalidOperationException( "Window was already closed" );
}
Wnd.DataContext = vm;
Result = Wnd.ShowDialog().Equals(true);
return Result;
}
Wnd is not null it contains instance of window I want to show. Exception is thrown in this line
Result = Wnd.ShowDialog().Equals(true);
actually after Wnd.ShowDialog()
Thrown exception snapshot:
System.NullReferenceException {"Object reference not set to an instance of an object."}
HResult = -2147467261
Message = Object reference not set to an instance of an object.
Data = {System.Collections.ListDictionaryInternal}
InnerExcpetion = null
Source = PresentationCore
StackTrace
at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param)
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 System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled)
at System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled)
at System.Windows.Interop.ThreadMessageEventHandler.Invoke(MSG& msg, Boolean& handled)
at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
at Intes.Utility.VisualizerService.UiWindow.ShowModal(ViewModel vm) in d:\Coder\Branch-AT\Source\Utilities\VisualizerService\Window abstraction\Implementation\UiWindow.cs:line 109
// this part of call stack is not important, but I will leave it
at A13.ViewModels.CalGroupExplorer.CalGroupExplorerPanelViewModel.NewMessage(IEnumerable`1 referenceIDs) in d:\Coder\Branch-AT\Source\A13\A13\ViewModels\CalGroupExplorer\CalGroupExplorerPanelViewModel.cs:line 159
at A13.ViewModels.EntryViewModel.AddReferencedMessage() in d:\Coder\Branch-AT\Source\A13\A13\ViewModels\CalGroupExplorer\EntryViewModel.cs:line 147
at A13.ViewModels.EntryViewModel.<get_AddReferencedMessageCommand>b__4(Object param) in d:\Coder\Branch-AT\Source\A13\A13\ViewModels\CalGroupExplorer\EntryViewModel.cs:line 136
at Intes.Utility.Wpf.RelayCommand.Execute(Object parameter) in d:\Coder\Branch-AT\Source\Utilities\Wpf\RelayCommand.cs:line 70
at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
at System.Windows.Controls.MenuItem.InvokeClickAfterRender(Object arg)
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.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
It seems like bug in .NET Framework, I'm using .NET Framework 4.5 for both projects A13 and Intes. A13 is main project , while Intes is referenced (method ShowModal is in class that is in project Intes). A13 is compiled as platform target: x86, while Intes as platform target: AnyCPU.
I'm running application in DEBUG mode on Windows 8.1 on x64 processor (Application has to be a x86).
Does anybody have any idea where could be the problem or any help how to trace the problem?

An unhandled exception of type 'System.Reflection.TargetParameterCountException' occurred in mscorlib.dll - Web Client.Download

I am trying to download a json string from a web page. I have been using System.Net.WebClient.
When I run it, it works fine on the first loop through, however when it comes through a second time it throws this error.
An unhandled exception of type 'System.Reflection.TargetParameterCountException' occurred in mscorlib.dll
Additional information: Parameter count mismatch.
I have narrowed down the line of code that is causing this error and I am completely baffled by it as works fine on the first attempt but doesn't on the second.
using (var client = new WebClient())
{
var url = string.Format(#"{0}{1}", _partOne, partTwo);
var result= client.DownloadString(url);
}
It is throwing the error on the following line specifically.
var result= client.DownloadString(url);
Just for more background this is a MVVM WPF application.
Stack Trace:
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Delegate.DynamicInvokeImpl(Object[] args)
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.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.Application.RunInternal(Window window)
at System.Windows.Application.Run()
at MyApp.App.Main() in c:\MyApp\obj\Debug\App.g.cs:line 0
I forgot to mention that the error is thrown on this line then I am able to see that it did infact return the correct data but won't let me continue to the next line.

Thread invoke the main window?

So basically I have a MainWindow, a class SetupViewModel defined in a separate cs file, and another class ImageViewModel in a separate cs file;
I am wondering is there anyway I can invoke the operation in MainWindow from ImageViewModel. More details listed below:
in ImageViewModel, invoke the change in MainWindow as following (following code in MainWindow):
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
((SetupViewModel)this.DataContext).ViewType = Convert.ToInt32(ViewTypes.ViewType2D);
}
)
);
The ViewType variable is defined in SetupViewModel as follows
private int _viewType;
public int ViewType
{
get
{
return _viewType;
}
set
{
_viewType = value;
OnPropertyChanged("ViewType");
}
}
Here is how I did, but was not successful; The invoke code in ImageViewModel:
try
{
Action SwitchTo2DView = delegate()
{
((CaptureSetupViewModel)System.Windows.Application.Current.MainWindow.DataContext).ViewType = Convert.ToInt32(ViewTypes.ViewType2D); };
System.Windows.Application.Current.MainWindow.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, SwitchTo2DView);
}
catch (Exception ex)
{
Console.WriteLine("Caught exception: " + ex.ToString());
}
and the exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at CaptureSetupDll.ViewModel.LiveImageViewModel.<StartZStackPreview>b__2c()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
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.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
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, 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.DispatcherOperation.Wait(TimeSpan timeout)
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)
at CaptureSetupDll.ViewModel.LiveImageViewModel.StartZStackPreview()
I am a layman to C#; Any idea how I can make this work? Thanks a lot.
I'll bet you five bucks your DataContext is null at the time this is being called. Which means its probably being called too early. Which probably means you should push whatever you're doing off on the Dispatcher.
While you may assume your application is completely loaded at the time this method is being called, it isn't necessarily true. To test this, set a breakpoint during debugging and check the DataContext to see if it's null.
If it is null, you have two choices. First, just return. Depending on how the method is being called, it may be called multiple times during load. A later call may reveal a non-null context.
The other option is to use the Dispatcher to re-call the method later, once the application is loaded.
Here's a little pseudocode which looks kind of like C# and may even compile:
public void CheckTheDataContext()
{
// is it null?
if(this.DataContext == null)
{
// then drop an Action re-invoking this method later
// when the application idles out a bit
Dispatcher.BeginInvoke((Action)(() =>
{
CheckTheDataContext();
}), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
return;
}
DoSomethingElseWithTheContext(DataContext);
}

Categories