Autofac: Missing Method Involving MvvmLight RelayCommand - wpf

I have a generic collection class based on the MvvM Light library which I've registered with Autofac:
public class DialogCollection<TViewModel> : ObservableCollection<TViewModel>, IDialogCollection<TViewModel>
{
private readonly IUIManager _uiManager;
public DialogCollection( IUIManager uiManager )
{
_uiManager = uiManager ?? throw new NullReferenceException( nameof(uiManager) );
ViewModelSelectedCommand = new RelayCommand<TViewModel>( DetailItemSelectedHandler );
AddNewViewModelCommand = new RelayCommand( AddNewItemHandler );
}
public RelayCommand<TViewModel> ViewModelSelectedCommand { get; }
public RelayCommand AddNewViewModelCommand { get; }
}
Autofac registration:
builder.RegisterGeneric( typeof(DialogCollection<>) )
.As( typeof(IDialogCollection<>) );
IUIManager, the only argument to the DialogCollection constructor, is also registered with Autofac, and is properly instantiated when the program runs.
The specific instance of IDialogCollection is generated from a lambda method created by Autofac, which is passed in thru the constructor of a class which holds an instance of the collection I want to create:
public class CommunitiesModel
{
private readonly Func<IDialogCollection<CommunityModel>> _colBuilder;
private readonly Func<CommunityModel> _communityBuilder;
private DialogCollection<CommunityModel> _communities;
public CommunitiesModel(
Func<IDialogCollection<CommunityModel>> colBuilder,
Func<CommunityModel> commmunityBuilder
)
{
_colBuilder = colBuilder ?? throw new NullReferenceException(nameof(colBuilder));
_communityBuilder= commmunityBuilder?? throw new NullReferenceException(nameof(commmunityBuilder));
}
// I'm not showing how Load() gets called, but it does :)
public override void Load()
{
// this next line creates an instance of DialogCollection
// it's also where the Autofac Missing Method exception gets thrown
Communities = (DialogCollection<CommunityModel>) _colBuilder();
}
}
Both colBuilder and communityBuilder are properly instantiated when passed into the CommunitiesModel constructor, which I presume means Autofac was able to use the registration information to create methods that create instances of those classes.
I don't understand why there's a missing method exception when _colBuilder() is executed, since the code compiles fine (meaning the RelayCommand ctor is known and available).
If I comment out the two RelayCommand creation lines (i.e., "new RelayCommand...") in the definition of DialogCollection<>, the exception is not thrown.
Which means the Autofac creator method is gacking on not finding something inside a constructor which has already been called with the appropriate constructur arguments.
Here is the exception that gets thrown:
Autofac.Core.DependencyResolutionException HResult=0x80131500
Message=An error occurred during the activation of a particular
registration. See the inner exception for details. Registration:
Activator = DialogCollection1 (ReflectionActivator),
Services =[WpfFramework.IDialogCollection1[[Olbert.CommunityScanner.Manager.ViewModel.CommunityModel,
CommunityScannerManager, Version=0.0.0.1, Culture=neutral,
PublicKeyToken=null]]], Lifetime =
Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership
= OwnedByLifetimeScope Source=Autofac StackTrace: at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1
parameters) at Autofac.Core.Resolving.InstanceLookup.Execute()
at
Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope
currentOperationScope, IComponentRegistration registration,
IEnumerable1 parameters) at
Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration
registration, IEnumerable1 parameters) at
Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration
registration, IEnumerable1 parameters) at
Olbert.CommunityScanner.Manager.ViewModel.CommunitiesModel.Load() in
C:\Programming\CommunityScanner\CommunityScannerManager\ViewModel\CommunitiesModel.cs:line
58 at
Olbert.CommunityScanner.Manager.ViewModel.AppStateModel.set_ActivePageInfo(PageInfo
value) in
C:\Programming\CommunityScanner\CommunityScannerManager\ViewModel\AppWide\AppStateModel.cs:line
117 at
Olbert.CommunityScanner.Manager.App.OnStartup(StartupEventArgs e) in
C:\Programming\CommunityScanner\CommunityScannerManager\App.xaml.cs:line
44 at System.Windows.Application.<.ctor>b__1_0(Object unused) 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)
at System.Windows.Threading.DispatcherOperation.InvokeImpl() at
System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object
state) at
MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object
obj) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) in
f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs:line 954
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) in
f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs:line 901
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) in
f:\dd\ndp\clr\src\BCL\system\threading\executioncontext.cs:line 890
at
MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext
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
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, 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.Application.RunDispatcher(Object ignore) at
System.Windows.Application.RunInternal(Window window) at
System.Windows.Application.Run(Window window) at
System.Windows.Application.Run() at
Olbert.CommunityScanner.Manager.App.Main()
Inner Exception 1: DependencyResolutionException: An exception was
thrown while invoking the constructor 'Void
.ctor(WpfFramework.IUIManager)' on type 'DialogCollection`1'.
Inner Exception 2: MissingMethodException: Method not found: 'Void
GalaSoft.MvvmLight.Command.RelayCommand1..ctor(System.Action1)'.
I can provide more details if needed; what I've shown here is abstracted from a larger code base, but hopefully shows the relevant details.

I would recommend looking at RelayCommand1 - it appears IUIManager or DialogCollection<T> needs that constructor and it's not there. Work bottom up on this. The Autofac part is red herring. Meat of the issue is the inner exception at the bottom.

Related

Touch, Framework 4.7, multiple windows & Windows Creator Update

Since Windows 10 creator update, we have a touch compliant WPF App that crashes:
Crash occurs when we are moving from one window to another on a touch action.
Here is the revelant part of the stack :
Source : PresentationCore
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Input.StylusWisp.WispStylusDevice.get_TabletDevice()
at System.Windows.Input.StylusTouchDeviceBase..ctor(StylusDeviceBase stylusDevice)
at System.Windows.Input.StylusWisp.WispLogic.PromoteMainToMouse(StagingAreaInputItem stagingItem)
at System.Windows.Input.StylusWisp.WispLogic.PromoteStoredItemsToMouse(WispStylusTouchDevice touchDevice)
at System.Windows.Input.StylusWisp.WispStylusTouchDevice.OnManipulationEnded(Boolean cancel)
at System.Windows.Input.ManipulationDevice.OnManipulationCancel()
at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.ManipulationLogic.ReportFrame(ICollection`1 manipulators)
at System.Windows.Input.ManipulationDevice.ReportFrame()
at System.Windows.Input.ManipulationDevice.RemoveManipulator(IManipulator manipulator)
at System.Windows.Input.Manipulation.TryRemoveManipulator(UIElement element, IManipulator manipulator)
at System.Windows.Input.TouchDevice.PromoteMainToManipulation(UIElement manipulatableElement, TouchEventArgs touchEventArgs)
at System.Windows.Input.TouchDevice.PostProcessInput(Object sender, ProcessInputEventArgs e)
at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.TouchDevice.Capture(IInputElement element, CaptureMode captureMode)
at System.Windows.Input.TouchDevice.PromoteMainToManipulation(UIElement manipulatableElement, TouchEventArgs touchEventArgs)
at System.Windows.Input.TouchDevice.PostProcessInput(Object sender, ProcessInputEventArgs e)
at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.TouchDevice.RaiseTouchUp()
at System.Windows.Input.TouchDevice.ReportUp()
at System.Windows.Input.StylusWisp.WispLogic.PromoteMainUpToTouch(WispStylusDevice stylusDevice, StagingAreaInputItem stagingItem)
at System.Windows.Input.StylusWisp.WispLogic.PromoteMainToTouch(ProcessInputEventArgs e, StylusEventArgs stylusEventArgs)
at System.Windows.Input.StylusWisp.WispLogic.PostProcessInput(Object sender, ProcessInputEventArgs e)
at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.StylusWisp.WispLogic.InputManagerProcessInput(Object oInput)
at System.Windows.Input.StylusWisp.WispLogic.PreProcessInput(Object sender, PreProcessInputEventArgs e)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage 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, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, 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.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.ShowDialog()
...
Let me be precise, the product is perfectly working on windows 7/8/8.1/10(non creator) and we do not use any Wacom or stylus device except our finger :)
If you have any idea, let me know and i will test it.

Exception in async method executing in UI-thread crashes application

When I await on a method that throws an exception, try/catch do not save application from crashing.
There is a throwing method
void CurrentStep.Process(CancellationToken cancellationToken)
{
throw new Exception();
}
It is called from the UI thread by the means of ICommand.Execute()
ProcessCurrentStepCommand = AsyncCommandFactory.Create(async cancellationToken =>
{
try
{
await Task.Run(() => CurrentStep.Process(cancellationToken));
}
catch {}
CurrentStep = CurrentStep.NextStepViewModel;
});
ProcessCurrentStepCommand is bound to the button on UI. When I click the button, my application breaks.
I feel that there is a general problem with throwing an exception on UI thread, but at the same time I don't understand why catch block isn't saving me from exception.
I have found the only way that works for me now:
await Task.Factory.StartNew(
action: () => CurrentStep.Process(cancellationToken),
creationOptions: TaskCreationOptions.LongRunning);
But it looks ugly. If I forget in the future what I wanted to do with this code I might think that I need to clean it and get into trouble with some exception knocking out the whole application.
When in debug mode, everything behaves nicely.
Original break on the source of exception.
Call stack:
UI.exe!UI.Steps.ViewModels.SvmConnectionViewModel.Process(System.Threading.CancellationToken
cancellationToken)
UI.exe!UI.MainViewModel..ctor.AnonymousMethod__1() Line 18
mscorlib.dll!System.Threading.Tasks.Task.InnerInvoke() Line 2911
mscorlib.dll!System.Threading.Tasks.Task.Execute() Line 2523
mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object
obj) Line 2888
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) Line 581
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) Line 531
mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot) Line 2853
mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution) Line 2792
mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
Line 2729
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() Line 830
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Line 1171
Next break happens in TaskAwaiter.cs in method ThrowForNonSuccess(): NotImplementedException occured: A first chance exception of type 'System.NotImplementedException' occurred in mscorlib.dll.
Call stack:
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task
task) Line 180
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task
task) Line 170
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Line 125
UI.exe!UI.MainViewModel..ctor(System.Threading.CancellationToken cancellationToken) Line 18
[Resuming Async Method]
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(object
stateMachine) Line 1065
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) Line 581
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) Line 531
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
Line 1045
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.OutputAsyncCausalityEvents>.AnonymousMethod__0()
Line 973
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.ContinuationWrapper.Invoke()
Line 1085
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.OutputWaitEtwEvents.AnonymousMethod__0()
Line 301
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.ContinuationWrapper.Invoke()
Line 1085
mscorlib.dll!System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.GetActionLogDelegate.AnonymousMethod__3()
Line 470
mscorlib.dll!System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation..cctor.AnonymousMethod__6(object
state) Line 393
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate
callback, object args, int numArgs) Line 118 Unknown
WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object
source, System.Delegate method, object args, int numArgs,
System.Delegate catchHandler) Line 41 Unknown
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeImpl()
Line 583 Unknown
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(object
state) Line 528 Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) Line 581
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) Line 531
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state) Line 520
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.Invoke()
Line 441 Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.ProcessQueue() Line 2227 Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.WndProcHook(System.IntPtr
hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool
handled) Line 2480 Unknown
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)
Line 345 Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object
o) Line 494 Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate
callback, object args, int numArgs) Line 111 Unknown
WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object
source, System.Delegate method, object args, int numArgs,
System.Delegate catchHandler) Line 41 Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority
priority, System.TimeSpan timeout, System.Delegate method, object
args, int numArgs) Line 1447 Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) Line
398 Unknown
[Native to Managed Transition]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame
frame) Line 2281 Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame
frame) Line 369 Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() Line 328 Unknown
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object
ignore) Line 2745
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window
window) Line 1841
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window
window) Line 261
PresentationFramework.dll!System.Windows.Application.Run() Line 222 UI.exe!UI.App.Main()
[Native to Managed Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) Line
2031
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object
state) Line 74
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) Line 581
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state, bool preserveSyncCtx) Line 531
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state) Line 520
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() Line 111
[Async Call]
UI.exe!UI.Commands.AsyncCommandFactory.Create(System.Threading.CancellationToken
token) Line 27
[Async Call]
UI.exe!UI.NotifyTaskCompletion.WatchTaskAsync(System.Threading.Tasks.Task
task) Line 66
[Async Call]
UI.exe!UI.Commands.AsyncCommand.ExecuteAsync(object parameter) Line 55
[Async Call]
UI.exe!UI.Commands.AsyncCommandBase.Execute(object parameter) Line 15
The next break with the same exception and almost the same as previous stack trace (the difference is only in the first of 4 last methods called).
Call stack:
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task
task) Line 180
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task
task) Line 170
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Line 125
UI.exe!UI.Commands.AsyncCommandFactory.Create(System.Threading.CancellationToken token) Line 27
[Resuming Async Method]
...
The next one is again differs only in the one method.
Call stack:
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task
task) Line 180
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task
task) Line 170
mscorlib.dll!System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Line 125
UI.exe!UI.NotifyTaskCompletion.WatchTaskAsync(System.Threading.Tasks.Task task) Line 66
[Resuming Async Method]
...
After previous break there are no more raised exceptions and Task.IsFaulted is set to true. Now UI successfully shows the exception message using this binding:
<Label Content="{Binding ProcessCurrentStepCommand.Execution.ErrorMessage}" Visibility="{Binding ProcessCurrentStepCommand.Execution.IsFaulted, Converter={StaticResource BooleanToVisibilityConverter}}" />
Final Edit.
To understand the context of the question and the accepted answer, you will need to look at these articles:
Async Programming : Patterns for Asynchronous MVVM Applications: Data Binding
Async Programming : Patterns for Asynchronous MVVM Applications: Commands
I don’t want to propagate exceptions directly back to the main UI loop; I want to capture any exceptions and set properties so that the error handling is done via data binding.
In that case, what you really need is a synchronous command that just starts the asynchronous operation, where the asynchronous operation is represented using NotifyTaskCompletion (or some similar type you write). Breaking apart the operation like this (into a synchronous "start" and asynchronous data binding) is easier than trying to do it all in one (which is also possible - it's just that the code isn't as short or reusable):
// Represents the execution of the current step.
NotifyTaskCompletion ProcessCurrentStepCommandExecution
{
get { return _processCurrentStepCommandExecution; }
set { _processCurrentStepCommandExecution = value; PropertyChanged(); }
}
...
var cancellationToken = ...; // Wherever you get this from.
ProcessCurrentStepCommand = new DelegateCommand(() =>
{
ProcessCurrentStepCommandExecution = new NotifyTaskCompletion(async () =>
{
await Task.Run(() => CurrentStep.Process(cancellationToken));
// I'm assuming here you only want to move to the next step if there are no errors.
// Otherwise, this should be in a finally block.
CurrentStep = CurrentStep.NextStepViewModel;
});
});
Edit:
I believe you may be running into a bug in the example code for that article (there used to be updated code in the comments before MSDNMag decided to delete them all, and I'm working to get the code sample updated, a surprisingly long process). The bug occurs if the task completes synchronously (with exception or success); in that case, NotifyTaskCompletion<T>.TaskCompleted will be null.
To fix this, change the constructor for NotifyTaskCompletion<T> from this:
{
Task = task;
if (!task.IsCompleted)
TaskCompletion = WatchTaskAsync(task);
}
to this:
{
Task = task;
TaskCompletion = WatchTaskAsync(task);
}

visual studio 2013 Xaml ui designer crash when trying to add event

Everytime I double click an event(to automatically add event template in code behind), xaml ui designer crash. These are the error message.
System.Runtime.InteropServices.COMException
Error HRESULT E_FAIL has been returned from a call to a COM component.
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at Microsoft.VisualStudio.CSharp.Services.Language.CodeModel.CCodeFunction.get_Type()
at EnvDTE.CodeFunction.get_Type()
at Microsoft.VisualStudio.ExpressionHost.Platform.DTECodeContext.CompatibleWith(CodeFunction function, IHostCodeEvent codeEvent)
at Microsoft.VisualStudio.ExpressionHost.Platform.DTECodeContext.<Microsoft.Expression.DesignHost.IHostCodeContext.GetCompatibleMethods>d__9.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteHostCodeContext.<>c__DisplayClass13.<Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteHostCodeContext.GetCompatibleMethods>b__12()
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c__DisplayClass2a`1.<MarshalIn>b__29()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.Runtime.InteropServices.COMException
Error HRESULT E_FAIL has been returned from a call to a COM component.
Server stack trace:
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalInSynchronous(Action action, Int32 targetApartmentId, CancellationToken cancelToken, CallModality callModality, String methodName, String filePath, Int32 lineNumber)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalIn(Action action, Int32 targetApartmentId, CancellationToken cancelToken, CallSynchronizationMode syncMode, CallModality callModality, String methodName, String filePath, Int32 lineNumber)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn(IRemoteObject targetObject, Action action, CallSynchronizationMode syncMode, CallModality callModality, ApartmentState apartmentState, String memberName, String filePath, Int32 lineNumber)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalIn[TResult](IRemoteObject targetObject, Func`1 func, CallModality callModality, ApartmentState apartmentState, String memberName, String filePath, Int32 lineNumber)
at Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteHostCodeContext.Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteHostCodeContext.GetCompatibleMethods(String eventName, RemoteHostParameter[] parameters, String returnType)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Expression.DesignHost.Isolation.Remoting.IRemoteHostCodeContext.GetCompatibleMethods(String eventName, RemoteHostParameter[] parameters, String returnType)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalHostCodeContext.<>c__DisplayClass16.<Microsoft.Expression.DesignHost.IHostCodeContext.GetCompatibleMethods>b__15(IRemoteHostCodeContext cxt)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.<>c__DisplayClassa`2.<MarshalOut>b__9()
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.Call.InvokeWorker()
System.Runtime.InteropServices.COMException
Error HRESULT E_FAIL has been returned from a call to a COM component.
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.WaitForCompletion(NestedCallContext nestedCallContext, BlockingCall call, WaitHandle timeoutSignal)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOutSynchronous(Action action, Int32 targetApartmentId, WaitHandle aborted, WaitHandle timeoutSignal, CancellationToken cancelToken, String methodName, String filePath, Int32 lineNumber)
at Microsoft.Expression.DesignHost.Isolation.Remoting.STAMarshaler.MarshalOut(Action action, Int32 targetApartmentId, WaitHandle aborted, CancellationToken cancelToken, CallSynchronizationMode syncMode, WaitHandle timeoutSignal, String methodName, String filePath, Int32 lineNumber)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TValue](RemoteHandle`1 targetObject, Action action, CallSynchronizationMode syncMode, ApartmentState apartmentState, String methodName, String filePath, Int32 lineNumber)
at Microsoft.Expression.DesignHost.Isolation.Remoting.ThreadMarshaler.MarshalOut[TResult,TValue](RemoteHandle`1 targetObject, Func`2 func, CallSynchronizationMode syncMode, ApartmentState apartmentState, String methodName, String filePath, Int32 lineNumber)
at Microsoft.Expression.DesignHost.Isolation.Remoting.LocalHostCodeContext.Microsoft.Expression.DesignHost.IHostCodeContext.GetCompatibleMethods(IHostCodeEvent codeEvent)
at Microsoft.Expression.DesignSurface.UserInterface.PropertyInspector.CodeContext.CreateEventHandler(ISourceItemContext item, String typeName, IEvent eventKey, String methodName)
at Microsoft.Expression.DesignSurface.UserInterface.PropertyInspector.EventHandlerProvider.CreateEventHandler(IEvent eventKey, String methodName)
at Microsoft.Expression.DesignSurface.UserInterface.PropertyInspector.EventHandlerModel.SetMethodName(String newName)
at Microsoft.Expression.DesignSurface.UserInterface.PropertyInspector.EventHandlerModel.GenerateAndCommit()
at Microsoft.Expression.DesignSurface.UserInterface.PropertyInspector.EventHandlerModel.<get_GenerateAndCommitCommand>b__1(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.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()
at Microsoft.Expression.DesignHost.Isolation.DesignerProcess.RunApplication()
at Microsoft.Expression.DesignHost.Isolation.DesignerProcess.<>c__DisplayClass2.<Main>b__0()
at System.Threading.ThreadHelper.ThreadStart_Context(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.Threading.ThreadHelper.ThreadStart()
I tries loading visual studio in SafeMode, unfortunately, xaml ui designer is totally unloadable.
Thanks.

MS Access 2013: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

We are running windows 8 64 bit and MS Office 2013 64 bit on a virtual machine. I got this error when I am trying to query the access database with parameters in the query string. The stack trace is:
at System.Data.Common.UnsafeNativeMethods.ICommandText.Execute(IntPtr pUnkOuter, Guid& riid, tagDBPARAMS pDBParams, IntPtr& pcRowsAffected, Object& ppRowset)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
at _64AccessTest.MainWindow.Button_Click_1(Object sender, RoutedEventArgs e) in c:\Users\xiaosu\Documents\Visual Studio 2012\Projects\64AccessTest\64AccessTest\MainWindow.xaml.cs:line 110
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage 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, 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 _64AccessTest.App.Main() in c:\Users\xiaosu\Documents\Visual Studio 2012\Projects\64AccessTest\64AccessTest\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
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.Threading.ThreadHelper.ThreadStart()
I have got the following code:
var connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\temp\templates\64Access.accdb;Persist Security Info=False;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
const String query = "PARAMETERS #Id LONG; select * from Subject where Id = #Id";
OleDbCommand _command = new OleDbCommand(query, connection);
_command.Parameters.Add("#Id", OleDbType.Integer);
_command.Parameters["#Id"].Value = 1;
using (OleDbDataReader reader = _command.ExecuteReader()){
......
}
}
The exception occurs at this line: using (OleDbDataReader reader = _command.ExecuteReader()
We are running .NET 4 with Visual Studio 2012 and this is a WPF application.
The wired thing is if I do not pass parameters to the sql query, it works fine. Once the query has some parameters, the error occurs.
In Visual Studio, the platform is set to AnyCPU which is what we want. We do not want to change this to x86.
Thanks for the help.

System.InvalidOperationException: Dispatcher processing has been suspended, but messages are still being processed

I'm converting a MFC app in x64. This app has a few WPF controls/dialogs. The problem I have is, for a few users, displaying a WPF control/dialog does not work. I get this exception:
System.InvalidOperationException: Dispatcher processing has been suspended, but messages are still being processed.
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.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Threading.WaitHandle.WaitOneNative(SafeHandle waitableSafeHandle, UInt32 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext)
at System.Threading.WaitHandle.InternalWaitOne(SafeHandle waitableSafeHandle, Int64 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext)
at System.Windows.Input.PenThreadWorker.WorkerCreateContext(IntPtr hwnd, IPimcTablet pimcTablet)
at System.Windows.Input.TabletDevice.CreateContext(IntPtr hwnd, PenContexts contexts)
at System.Windows.Input.TabletDeviceCollection.CreateContexts(IntPtr hwnd, PenContexts contexts)
at System.Windows.Input.PenContexts.Enable()
at System.Windows.Input.StylusLogic.RegisterHwndForInput(InputManager inputManager, PresentationSource inputSource)
at System.Windows.Interop.HwndStylusInputProvider..ctor(HwndSource source)
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)
The app than hangs for a few seconds and crashes.
Has anybody ever had similar problems with MFC/WPF in 64bit ?

Resources