InvalidOperationException when using a command on a second UI thread - wpf

We are adding a second UI thread to our catel 4.4.0 MVVM application.
I have created my view and view model on the second UI thread and am using a DispatcherTimer to update the view model periodically. That part seems to be working fine. However, when I create a Catel.MVVM.Command in the constructor of my view model I am running into issues. When the CanExecute of the command fires I am getting a System.InvalidOperationException on my second UI thread.
The command is nothing special.
private bool ImageClickCanExecute()
{
return true;
}
public void ImageClickAction()
{
if(ImageClickTarget != null)
Process.Start(ImageClickTarget.ToString());
}
The view is not either.
<Grid>
<Button Command="{Binding ImageClickCommand}">
<Image Name="ImageSource" Source="{Binding ImageSource, FallbackValue={x:Null}}"/>
</Button>
</Grid>
The stack trace is below.
0:010> !PrintException /d 00000282cb8effd0
Exception object: 00000282cb8effd0
Exception type: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
InnerException: System.InvalidOperationException, Use !PrintException 00000282cb8edee8 to see more.
StackTrace (generated):
SP IP Function
000000B0459FD510 0000000000000000 mscorlib_ni!System.RuntimeMethodHandle.InvokeMethod(System.Object, System.Object[], System.Signature, Boolean)+0x1
000000B0459FD510 00007FFFCC5E1C20 mscorlib_ni!System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(System.Object, System.Object[], System.Object[])+0x80
000000B0459FD580 00007FFFCC5BE789 mscorlib_ni!System.Delegate.DynamicInvokeImpl(System.Object[])+0x99
000000B0459FD5D0 00007FFF70FC83AE UNKNOWN!Catel.EventHandlerExtensions.SplitInvoke(System.Delegate, System.Object[])+0xfe
000000B0459FD630 00007FFF7164E085 UNKNOWN!Catel.EventHandlerExtensions.SafeInvoke(System.EventHandler, System.Object, System.EventArgs)+0x55
000000B0459FD680 00007FFF71674998 UNKNOWN!Catel.MVVM.Command`2+<<RaiseCanExecuteChanged>b__32_0>d[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].MoveNext()+0x38
000000B0459FD7B0 00007FFFCD2E1224 mscorlib_ni!System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)+0xd3f9c4
000000B0459FD7F0 00007FFFCC5A17AD mscorlib_ni!System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)+0x3d
000000B0459FD820 00007FFF71674515 UNKNOWN!Catel.MVVM.Command`2+<>c__DisplayClass35_0+<<AutoDispatchIfRequiredAsync>b__0>d[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].MoveNext()+0xf5
000000B0459FD9B0 00007FFFCCFCDA88 mscorlib_ni!System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0(System.Object)+0x38
000000B0459FD9E0 00007FFFA8119C0E WindowsBase_ni!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)+0xae
000000B0459FDA50 00007FFFA8119AC6 WindowsBase_ni!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)+0x36
000000B0459FDAA0 00007FFFA811CA2B WindowsBase_ni!System.Windows.Threading.DispatcherOperation.InvokeImpl()+0x10b
000000B0459FDB20 00007FFFCC5CA79E mscorlib_ni!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)+0x15e
000000B0459FDBF0 00007FFFCC5CA637 mscorlib_ni!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)+0x17
000000B0459FDC20 00007FFFCC5CA5F2 mscorlib_ni!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)+0x52
000000B0459FDC70 00007FFFA8333810 WindowsBase_ni!MS.Internal.CulturePreservingExecutionContext.Run(MS.Internal.CulturePreservingExecutionContext, System.Threading.ContextCallback, System.Object)+0x80
000000B0459FDCD0 00007FFFA811C784 WindowsBase_ni!System.Windows.Threading.DispatcherOperation.Invoke()+0x64
000000B0459FDD30 00007FFFA8117C24 WindowsBase_ni!System.Windows.Threading.Dispatcher.ProcessQueue()+0x1a4
000000B0459FDDB0 00007FFFA8118061 WindowsBase_ni!System.Windows.Threading.Dispatcher.WndProcHook(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)+0x71
000000B0459FDE30 00007FFFA8119E53 WindowsBase_ni!MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)+0xc3
000000B0459FDEC0 00007FFFA8119D82 WindowsBase_ni!MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)+0x82
000000B0459FDF10 00007FFFA8119BC9 WindowsBase_ni!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)+0x69
000000B0459FDF80 00007FFFA8119AC6 WindowsBase_ni!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)+0x36
000000B0459FDFD0 00007FFFA8117583 WindowsBase_ni!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)+0x173
000000B0459FE070 00007FFFA81194FF WindowsBase_ni!MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)+0x11f
000000B0459FE390 0000000000000000 WindowsBase_ni!MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)+0x1
000000B0459FE450 00007FFFA812D8FC WindowsBase_ni!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)+0xec
000000B0459FE4E0 00007FFFA26A98B3 PresentationFramework_ni!System.Windows.Application.RunDispatcher(System.Object)+0x73
000000B0459FE520 00007FFFA26A969D PresentationFramework_ni!System.Windows.Application.RunInternal(System.Windows.Window)+0x8d
000000B0459FE580 00007FFF70FD70F7 UNKNOWN!xxx.Wpf.App.Main()+0x67
000000B0459FF0C0 0000000000000000 mscorlib_ni!System.AppDomain._nExecuteAssembly(System.Reflection.RuntimeAssembly, System.String[])+0x1
000000B0459FF0C0 00007FFFCCD57EBF mscorlib_ni!System.AppDomain.ExecuteAssembly(System.String, System.Security.Policy.Evidence, System.String[])+0x7f
000000B0459FF110 00007FFF7053434E UNKNOWN!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()+0x3e
000000B0459FF150 00007FFFCC5CA79E mscorlib_ni!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)+0x15e
000000B0459FF220 00007FFFCC5CA637 mscorlib_ni!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)+0x17
000000B0459FF250 00007FFFCC5CA5F2 mscorlib_ni!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)+0x52
000000B0459FF2A0 00007FFFCC51BEF2 mscorlib_ni!System.Threading.ThreadHelper.ThreadStart()+0x52
StackTraceString: <none>
HResult: 80131604
0:010> !PrintException /d 00000282cb8edee8
Exception object: 00000282cb8edee8
Exception type: System.InvalidOperationException
Message: The calling thread cannot access this object because a different thread owns it.
InnerException: <none>
StackTrace (generated):
SP IP Function
000000B0459FCD70 00007FFFA8446977 WindowsBase_ni!System.Windows.Threading.Dispatcher.VerifyAccess()+0x32faf7
000000B0459FCDA0 00007FFFA8112806 WindowsBase_ni!System.Windows.DependencyObject.GetValue(System.Windows.DependencyProperty)+0x26
000000B0459FCE00 00007FFFA27EBB5B PresentationFramework_ni!System.Windows.Controls.Primitives.ButtonBase.get_Command()+0x2b
000000B0459FCE30 00007FFFA27EBB00 PresentationFramework_ni!System.Windows.Controls.Primitives.ButtonBase.UpdateCanExecute()+0x10
StackTraceString: <none>
HResult: 80131509

This is because, by default, the commands automatically dispatch change notifications using the DispatcherService. Since you are running an edge-case scenario (2 ui threads), I recommend that you turn off the automatic dispatching and take care of this yourself.
Since this is a static protected member, you will need to derive your own command class from CommandBase and set AutomaticallyDispatchEvents to false.
ps. I recommend using the IProcessService instead of directly using Process.Start, it allows you to mock it or replace it if you need to.

Related

Exception has been thrown by the target of an invocation. (REDIS Cache)

I'm trying to resolve an issue we have specific to using REDIS cache on our web apps but need help understanding the stacktrace.
We intermittently get Exception has been thrown by the target of an invocation logged in our error table when users are viewing the report viewer, but there are no signs client side that anything has gone wrong.
I've had a read through this article: How to solve: "exception was thrown by the target of invocation" C# however it doesn't seem to cover our specific issue.
The stacktrace logged by our logger;
at System.RuntimeMethodHandle.SerializationInvoke(IRuntimeMethodInfo method, Object target, SerializationInfo info, StreamingContext& context)
at System.Runtime.Serialization.ObjectManager.CompleteISerializableObject(Object obj, SerializationInfo info, StreamingContext context)
at System.Runtime.Serialization.ObjectManager.FixupSpecialObject(ObjectHolder holder)
at System.Runtime.Serialization.ObjectManager.DoFixups()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at Microsoft.Web.Redis.BinarySerializer.Deserialize(Byte[] data) in D:\BuildAgent\work\f55792526e6d9089\src\Shared\BinarySerializer.cs:line 37
at Microsoft.Web.Redis.ChangeTrackingSessionStateItemCollection.GetData(String normalizedName) in D:\BuildAgent\work\f55792526e6d9089\src\Shared\ChangeTrackingSessionStateItemCollection.cs:line 156
at Microsoft.Web.Redis.ChangeTrackingSessionStateItemCollection.get_Item(String name) in D:\BuildAgent\work\f55792526e6d9089\src\Shared\ChangeTrackingSessionStateItemCollection.cs:line 141
at System.Web.SessionState.HttpSessionStateContainer.get_Item(String name)
at Microsoft.Reporting.WebForms.ViewerDataOperation..ctor()
at Microsoft.Reporting.WebForms.HttpHandler.GetHandler(String operationType)
at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Looks to be an issue during Deserialization. Could the class definition have changed between when it was serialized and when it is being deserialized?

Why am I getting "Unable to load the specified metadata resource" error?

I have an MVC5 web application which I usually develop using my laptop.
I am trying to get the app running on my main machine at home for home-working days but have a problem connecting to the local dev database on SQL Server - when I start the app I get the following error:
More info 30/11/16:
Note that the model is generated from EDML using Entity Developer
Unable to load the specified metadata resource. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
The solution consists of 2 projects, one of which is an entity model project which is generated from EDMX.
Note: On my main machine (where it isn't working) the connection string in Web.config is the same as the machine where it works except for Data Source which refers to the SQL Server name on the main machine - I have checked this is correct several times:
I have read several Stack Overflow posts with similar issues - most point to something wrong with the path to the csdl, ssdl, msl part of the connection string.
I have:
Checked the server name is correct in the connection string
Checked the database name is correct in the connection string
Checked the database exists and is available
Checked each of the three files are where the connection string says they are (they are)
Tried using wildcard in the connection string: res://*/dllname.csdl|res://*/dllname.ssdl|res://*/dllname.msl
Update 30/11/2016:
From the suggestions in this link I have:
Checked the MetadataArtifactProcessing property - it is not set to Copy to Output directory
Checked the connection string
We don't have a post-compile task
From the suggestion in this link I have tried setting the connection string connectionString="metadata=res://*/;
Stack Trace:
[MetadataException: Unable to load the specified metadata resource.]
System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.LoadResource() +85
System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.CreateReader() +10
System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.CreateReaders(DataSpace spaceToGet) +72
System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderComposite.CreateReaders(DataSpace spaceToGet) +99
System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadEdmItemCollection(MetadataArtifactLoader loader) +41
System.Data.Entity.Core.Metadata.Edm.<>c__DisplayClass5.<GetMetadataWorkspace>b__0(String k) +37
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +72
System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace(String cacheKey, MetadataArtifactLoader artifactLoader) +75
System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace(DbConnectionOptions effectiveConnectionOptions) +126
System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace() +43
System.Data.Entity.Core.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection() +20
System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor, ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, Translator translator, ColumnMapFactory columnMapFactory) +393
System.Data.Entity.Core.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName) +35
App.Models.Entities..ctor() in C:\Users\Me\Desktop\App\App.MVC5\App.Entities.cs:37
App.MVC5.Models.CurrentUser..ctor(Boolean IsGuiDetailsRequired) in C:\Users\Me\Desktop\App\App.MVC5\Models\AccountModels.cs:87
App.MVC5.Controllers.HomeController..ctor() in C:\Users\Me\Desktop\App\App.MVC5\Controllers\HomeController.cs:11
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +114
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +11
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'App.MVC5.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +76
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +88
Castle.Proxies.Invocations.IControllerFactory_CreateController.InvokeMethodOnTarget() +118
Castle.DynamicProxy.AbstractInvocation.Proceed() +80
Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed() +11
Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult) +41
Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +25
Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation) +84
Castle.DynamicProxy.AbstractInvocation.Proceed() +108
Castle.Proxies.IControllerFactoryProxy.CreateController(RequestContext requestContext, String controllerName) +214
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +194
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
There's a very popular question over there and from its rating I can assume it helped a lot of people. It even mentions a blog post with complete troubleshooting for this problem. Also, this answer looks like something you didn't try yet.

Root Cause: Recursive call to Automation Peer API is not valid

We've used WPF Tookit DataGrid and .NET 3.5 for about 2 years. And we've got two cases which throw exception - "Recursive call to Automation Peer API is not valid". It's quit strange and eratic, very few PCs has such issue.
Case One:
A dropdown combox (WPF Tookit DataGrid as DropDown content control):
And it can be resolved by:
protected override AutomationPeer OnCreateAutomationPeer()
{
return null;
}
This solution is from WPF Recursive call to Automation Peer API is not valid.
Case Two:
A WPF Tookit DataGrid has a Temlate Column , which the cell template has a dropdown combox (WPF Tookit DataGrid as DropDown content control). It can not be fixed by the solution above.
*Exception Stack:
Exception object: 0ac4e048
Exception type: System.InvalidOperationException
Message: Recursive call to Automation Peer API is not valid.
InnerException: <none>
StackTrace (generated):
SP IP Function
0036E3A4 61A0CEFE PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.GetChildren()+0x366bde
0036E3D4 616A5C34 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x18
0036E3EC 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E404 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E41C 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E434 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E44C 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E464 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E47C 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E494 616A5E52 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.ValidateConnected(System.Windows.Automation.Peers.AutomationPeer)+0xaa
0036E4A8 616A444E PresentationCore_ni!MS.Internal.Automation.ElementProxy.StaticWrap(System.Windows.Automation.Peers.AutomationPeer, System.Windows.Automation.Peers.AutomationPeer)+0x1a
0036E4C0 616A7C69 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.UpdateChildrenInternal(Int32)+0x341
0036E52C 616A791A PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.UpdateChildren()+0xa
0036E530 11EDC66E UNKNOWN!Microsoft.Windows.Automation.Peers.DataGridItemAutomationPeer.GetChildrenCore()+0x1e
0036E540 616A662B PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.EnsureChildren()+0x23
0036E558 616A634C PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.GetChildren()+0x2c
0036E588 616A5C34 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x18
0036E5A0 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E5B8 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E5D0 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E5E8 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E600 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E618 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E630 616A5C73 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.isDescendantOf(System.Windows.Automation.Peers.AutomationPeer)+0x57
0036E648 616A5E52 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.ValidateConnected(System.Windows.Automation.Peers.AutomationPeer)+0xaa
0036E65C 616A444E PresentationCore_ni!MS.Internal.Automation.ElementProxy.StaticWrap(System.Windows.Automation.Peers.AutomationPeer, System.Windows.Automation.Peers.AutomationPeer)+0x1a
0036E674 616A6F3E PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.ProviderFromPeer(System.Windows.Automation.Peers.AutomationPeer)+0x1e
0036E680 619DBBD1 PresentationCore_ni!System.Windows.Automation.Peers.AutomationPeer.RaiseAutomationEvent(System.Windows.Automation.Peers.AutomationEvents)+0x7ab6d5
0036E690 609783AA PresentationFramework_ni!System.Windows.Automation.Peers.SelectorAutomationPeer.RaiseSelectionEvents(System.Windows.Controls.SelectionChangedEventArgs)+0x22
0036E6B0 60C48560 PresentationFramework_ni!System.Windows.Controls.ComboBox.OnSelectionChanged(System.Windows.Controls.SelectionChangedEventArgs)+0xbef278
0036E6C4 124C17E7 UNKNOWN!UNKNOWN+0x17
0036E6EC 60061113 PresentationFramework_ni!System.Windows.Controls.Primitives.Selector.InvokeSelectionChanged(System.Collections.Generic.List`1<System.Object>, System.Collections.Generic.List`1<System.Object>)+0x4f
0036E704 6005FE17 PresentationFramework_ni!System.Windows.Controls.Primitives.Selector+SelectionChanger.End()+0xdf
0036E738 6005E325 PresentationFramework_ni!System.Windows.Controls.Primitives.Selector+SelectionChanger.SelectJustThisItem(System.Object, Boolean)+0x11d
0036E76C 60060D02 PresentationFramework_ni!System.Windows.Controls.Primitives.Selector.OnSelectedItemChanged(System.Windows.DependencyObject, System.Windows.DependencyPropertyChangedEventArgs)+0xb2
0036E798 627585EC WindowsBase_ni!Unknown+0x4c
0036E7C4 60073E40 PresentationFramework_ni!System.Windows.FrameworkElement.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs)+0x50
0036E8F4 627583BC WindowsBase_ni!Unknown+0x3c
0036E94C 6275676B WindowsBase_ni!Unknown+0x71b
0036EA0C 627594CD WindowsBase_ni!Unknown+0xad
0036EA34 600AD85A PresentationFramework_ni!System.Windows.Data.BindingExpressionBase.Invalidate(Boolean)+0x62
0036EA4C 600AD31D PresentationFramework_ni!System.Windows.Data.BindingExpression.TransferValue(System.Object, Boolean)+0x1fd
0036EAA0 600AA9D8 PresentationFramework_ni!System.Windows.Data.BindingExpression.Activate(System.Object)+0x194
0036EACC 60097C49 PresentationFramework_ni!System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt)+0x38d
0036EB74 600C3D51 PresentationFramework_ni!System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean)+0x19
0036EB80 600C3D19 PresentationFramework_ni!MS.Internal.Data.DataBindEngine+Task.Run(Boolean)+0x31
0036EB94 600C3C36 PresentationFramework_ni!MS.Internal.Data.DataBindEngine.Run(System.Object)+0xb6
0036EBB0 600C2CBA PresentationFramework_ni!MS.Internal.Data.DataBindEngine.OnLayoutUpdated(System.Object, System.EventArgs)+0x1e
0036EBC0 61271CD8 PresentationCore_ni!System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()+0x154
0036EBF8 6127159E PresentationCore_ni!System.Windows.ContextLayoutManager.UpdateLayout()+0x926
0036ECF8 61277F4D PresentationCore_ni!System.Windows.ContextLayoutManager.UpdateLayoutCallback(System.Object)+0x19
0036ECFC 61277F28 PresentationCore_ni!System.Windows.Media.MediaContext+InvokeOnRenderCallback.DoWork()+0x10
0036ED00 61277EC2 PresentationCore_ni!System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()+0x76
0036ED1C 6127785A PresentationCore_ni!System.Windows.Media.MediaContext.RenderMessageHandlerCore(System.Object)+0x8a
0036ED68 612777AA PresentationCore_ni!System.Windows.Media.MediaContext.RenderMessageHandler(System.Object)+0x6e
0036ED80 6274FE83 WindowsBase_ni!Unknown+0x53
0036EDA0 6274FE0C WindowsBase_ni!Unknown+0x9c
0036EDE8 62752C95 WindowsBase_ni!Unknown+0x8d
0036EE24 62752BF8 WindowsBase_ni!Unknown+0x38
0036EE2C 642F4D85 mscorlib_ni!System.Threading.ExecutionContext.runTryCode(System.Object)+0x51
0036F2D0 642F4C8A mscorlib_ni!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)+0x6a
0036F2E8 642F7F92 mscorlib_ni!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)+0x7e
0036F30C 642F7F04 mscorlib_ni!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)+0x2c
0036F328 62752B28 WindowsBase_ni!Unknown+0x68
0036F364 6274E7FE WindowsBase_ni!Unknown+0x15e
0036F3A8 6274E9D7 WindowsBase_ni!Unknown+0x63
0036F3F8 627500A6 WindowsBase_ni!Unknown+0xbe
0036F444 6274FFD5 WindowsBase_ni!Unknown+0x7d
0036F454 6274FE83 WindowsBase_ni!Unknown+0x53
0036F474 6274FDB2 WindowsBase_ni!Unknown+0x42
0036F4BC 6274E2CC WindowsBase_ni!Unknown+0xb4
0036F504 6274F8B8 WindowsBase_ni!Unknown+0x104*
Many threads just has a walkaround solution about the issue, Does any one know have any idea about the Root Cause of Recursive call to Automation Peer API is not valid?
I realise this is an old thread but i just had the exact same issue after reloading a project i completed some months back.
The only real change of significance was that i had installed RoboForm to trial and it had expired.
I could re-create very easily and consistently, Uninstalled it and problem is now gone.

AccessViolationException on ToolTip that faults COMCTL32.dll - .NET 4.0

We are having an issue with our Windows forms application where it is terminating due to an unhandled exception of type AccessViolationException that the stack trace is indicating occurs within the ToolTip control.
The error occurs at different times in the application, and we are currently not able to reliably reproduce it.
At this stage it is occurring only in production on Windows 7 and only for some users, but not others – even amongst users that use the application in a similar way.
It appears to be machine related and so we have done things like ensure the graphics driver is up to date.
In the event log, there are always 2 different errors logged, one relating to our application:
Application: <Application>.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
at System.Windows.Forms.NativeWindow.DefWndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.ToolTip.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.ToolTip+ToolTipNativeWindow.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG ByRef)
at System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr, Int32, Int32)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
at <Company>.Windows.Forms.<Application>.Startup.Main(System.String[])
And one relating to comctl32.dll:
Faulting application name: <Application>.exe, version: 7.13.0.2086, time stamp: 0x4ec5e710
Faulting module name: comctl32.dll, version: 5.82.7601.17514, time stamp: 0x4ce7b82c
Exception code: 0xc0000005
Fault offset: 0x00043286
Faulting process id: 0xcdc
Faulting application start time: 0x01cca96312446309
Faulting application path: C:\Program Files\<Company>\Client\<Application>.exe
Faulting module path: C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_5.82.7601.17514_none_ec83dffa859149af\comctl32.dll
Report Id: b425143c-1575-11e1-bccf-6c626d955bf1
The first stack trace changes depending on where in the workflow the error occurs, however, the top 9 items on the stack are always the same, the difference is usually a showDialog call that appears in between the Main() method and the RunMessageLoop method. E.g.:
Application: <Application>.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
at System.Windows.Forms.NativeWindow.DefWndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.ToolTip.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.ToolTip+ToolTipNativeWindow.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG ByRef)
at System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr, Int32, Int32)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
at System.Windows.Forms.Application.RunDialog(System.Windows.Forms.Form)
at System.Windows.Forms.Form.ShowDialog(System.Windows.Forms.IWin32Window)
at System.Windows.Forms.Form.ShowDialog()
at <Company>.Windows.Forms.<Application>.ApplicationForm.<EventSubscribingMethod>(System.Object, System.EventArgs)
at <Company>.<Application>.<Class1>.RaiseShowResultDialogNowEvent()
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(System.Object)
at System.Threading.ExecutionContext.runTryCode(System.Object)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.ScrollableControl.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Form.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Control+ControlNativeWindow.OnMessage(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.Control+ControlNativeWindow.WndProc(System.Windows.Forms.Message ByRef)
at System.Windows.Forms.NativeWindow.Callback(IntPtr, Int32, IntPtr, IntPtr)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG ByRef)
at System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr, Int32, Int32)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
at System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
at <Company>.Windows.Forms.<Application>.Portal.Startup.Main(System.String[])
---- Update ----
I have had a request to include some of the code from Main, I don't want to include all code, but an extract is:
<System.STAThread()> _
Public Shared Function Main(ByVal args() As String) As Integer
-- Perform startup validation, setup logging framework, etc
...
Dim appLife as new ApplicationContext(myStartupForm)
Application.Run(appLife)
Return 0
End Function
Some additional notes:
We are using the UI Process Application Block from MS Patterns and Practices
We do override WndProc in a couple of controls, including CheckBoxComboBox from code project at http://www.codeproject.com/KB/combobox/extending_combobox.aspx
Does anyone know what could be causing this?
Thanks,
According to MS, there is a known issue with the DataGrid control in certain situations, and the way to avoid this issue is to disable Tooltips for your DataGrid controls.
We will be implementing the change and rolling it out to a pilot group in the next couple of days, I'll post back with success/failure in about a week (unless of course failure happens before then).
The property to set according to MS is DataGridView.ShowCellToolTips = false;
This fixed the issue for our application.
To reproduce the issue, we needed to do the following:
Hover the mouse over a cell in our DataGridView that we knew would show a tooltip
Alt tab to another application (that will display on top of your application) before the tooltip is shown
Do not move the mouse
Alt tab back to our application
Our application crashes.
It seems that setting DataGridView.ShowCellToolTips = false on Form.Deactivate prevents the crash. It can be reset to true on Form.Activate.
The tooltip is still shown above the newly focused windows however - but I guess that's better then crashing.
Or even better:
The problem only occurs when visual styles are not enabled.
Adding Application.EnableVisualStyles() in main() before any forms are instantiated solves the problem.
more details
https://github.com/Microsoft/dotnet/issues/402
6 years later, solution is unfortunately still "use comctl v6"

Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'

In which situation following error occurs?
Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'.
UPDATE:
I got this error message while binding MyType.FindAllByProperty("col1", "foo"); to a GridView (exactly a Telerik's one: RadGrid). This error is not occuring every time, just sometimes. Here is markup of my grid:
<telerik:RadGrid ID="grdList" runat="server" AutoGenerateColumns="false" OnNeedDataSource="grdList_NeedDataSource"
OnUpdateCommand="grdList_UpdateCommand" AllowAutomaticUpdates="True" OnItemUpdated="grdList_ItemUpdated"
AllowMultiRowEdit="true">
<MasterTableView EditMode="InPlace" DataKeyNames="PageInRole_id" AllowAutomaticUpdates="true">
<Columns>
<telerik:GridBoundColumn DataField="ContainerPage.PageTitle" HeaderText="Title" UniqueName="ContainerPage.PageTitle"
ReadOnly="true" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
UPDATE2
Here is all exception message and stack trace:
Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.]
Telerik.Web.UI.GetEnumerator>d__0.MoveNext() +175
Telerik.Web.UI.GridDataTableFromEnumerable.FillDataTableFromEnumerable(IQueryable enumerable) +1285
Telerik.Web.UI.GridDataTableFromEnumerable.FillData35() +3390
Telerik.Web.UI.GridDataTableFromEnumerable.FillData() +824
Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() +28
Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +242
Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +223
Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +595
Telerik.Web.UI.GridTableView.get_ResolvedDataSource() +243
Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +42
System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +72
System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +147
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +261
Telerik.Web.UI.GridTableView.PerformSelect() +23
Telerik.Web.UI.GridTableView.DataBind() +363
Telerik.Web.UI.GridTableView.Rebind() +101
Telerik.Web.UI.GridCommandEventArgs.ExecuteCommand(Object source) +1174
Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e) +185
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
Telerik.Web.UI.GridItem.OnBubbleEvent(Object source, EventArgs e) +142
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927
This exception probably comes from the code trying to re-attach a proxied/lazy-loading entity to a session. The most likely API call to throw this exception with a newer NHibernate (I don't have problem with 2.1 but I do have problems with latest) is Session.Lock(obj, LockMode.None).
If the programmer of this component first evicts the entity from the ISession and then re-loads it (perhaps cached?) into another one by id, or performs ISession.Update this problem should go away until the NHibernate team has figured out the underlying problem.
I had a similar problem with EntityFramework 6.0.
I had migrated from an old version of EntityFramework that did not use proxies and had some code that created and attached new instances of the entity via new MyEntity();.
My solution was to use dbContext.MyEntity.Create(); instead so I only work with proxies. Something similar should be available for NHibernate if I recall correctly.
My error was:
Unable to cast object of type 'MyProject.MyEntity' to type
'System.Data.Entity.DynamicProxies.MyEntity_849E94C98E5E543D6DF5245252144E3EAC00131F811886276B6ABD991719D232'
We ran into the same issue with RadGrid having AutomaticInserts. After inserting an item it throw InvalidCastException: Unable to cast object of type 'MyDbModel.Role' to type 'System.Data.Entity.DynamicProxies.Role_...' in DataBind() at Rebind().
The issue was gone after I adapted the DataBinding to have an OrderBy().

Resources