In the following code ConfigSetting is an entity and Db is my Context.
When I step into the following line in my debugger
ConfigSetting config = this.Db.ConfigSettings.FirstOrDefault(o => o.Name == kSiteGuid);
I find I am in the context SaveChanges event.
The database already exists so EF should not be trying to seed it.
The call stack is
SBD.Syrius.DataLayer.dll!SBD.Syrius.DataLayer.Context.SaveChanges() Line 338 C#
EntityFramework.dll!System.Data.Entity.Migrations.DbMigrator.SeedDatabase() + 0x9e bytes
EntityFramework.dll!System.Data.Entity.Migrations.Infrastructure.MigratorBase.SeedDatabase() + 0x40 bytes
EntityFramework.dll!System.Data.Entity.Migrations.DbMigrator.Upgrade(System.Collections.Generic.IEnumerable pendingMigrations, string targetMigrationId, string lastMigrationId) + 0x38c bytes
EntityFramework.dll!System.Data.Entity.Migrations.Infrastructure.MigratorBase.Upgrade(System.Collections.Generic.IEnumerable pendingMigrations, string targetMigrationId, string lastMigrationId) + 0x5e bytes
EntityFramework.dll!System.Data.Entity.Migrations.DbMigrator.Update(string targetMigration) + 0x547 bytes
EntityFramework.dll!System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update() + 0x34 bytes
EntityFramework.dll!System.Data.Entity.MigrateDatabaseToLatestVersion.InitializeDatabase(SBD.Syrius.DataLayer.Context context) + 0xa3 bytes
EntityFramework.dll!System.Data.Entity.Database.SetInitializerInternal.AnonymousMethod_0(System.Data.Entity.DbContext c) + 0xd0 bytes
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization.AnonymousMethod_6() + 0x55 bytes
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.PerformInitializationAction(System.Action action) + 0x74 bytes
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() + 0x17d bytes
EntityFramework.dll!System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase.AnonymousMethod__4(System.Data.Entity.Internal.InternalContext c) + 0x30 bytes
EntityFramework.dll!System.Data.Entity.Internal.RetryAction.PerformAction(System.Data.Entity.Internal.InternalContext input) + 0xa2 bytes
EntityFramework.dll!System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(System.Action action) + 0x181 bytes
EntityFramework.dll!System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() + 0xa5 bytes
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.Initialize() + 0x46 bytes
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(System.Type entityType) + 0x2d bytes
EntityFramework.dll!System.Data.Entity.Internal.Linq.InternalSet.Initialize() + 0x97 bytes
EntityFramework.dll!System.Data.Entity.Internal.Linq.InternalSet.InternalContext.get() + 0x32 bytes
EntityFramework.dll!System.Data.Entity.Infrastructure.DbQuery.System.Linq.IQueryable.Provider.get() + 0x8c bytes
System.Core.dll!System.Linq.Queryable.FirstOrDefault(System.Linq.IQueryable source, System.Linq.Expressions.Expression> predicate) + 0x55 bytes
SBD.Syrius.DataLayer.dll!SBD.Syrius.DataLayer.DataHelper.FindOrCreateSite() Line 262 + 0x1d6 bytes C#
SBD.Syrius.UI.exe!SBD.Syrius.UI.Program.Main(string[] args) Line 34 + 0x24 bytes C#
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x66 bytes
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x8d bytes
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x285 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x9 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x57 bytes
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x51 bytes
[Native to Managed Transition]
The Debugger shows
'SBD.Syrius.UI.vshost.exe' (Managed (v4.0.30319)): Loaded 'E:\EShared\Syrius6\syrius_syrius\SBD.Syrius.UI\bin\Debug\SBD.Syrius.Synchronisation.dll', Symbols loaded.
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
A first chance exception of type 'System.Data.EntityCommandExecutionException' occurred in System.Data.Entity.dll
A first chance exception of type 'System.Data.EntityCommandExecutionException' occurred in System.Data.Entity.dll
A first chance exception of type 'System.Data.EntityCommandExecutionException' occurred in System.Data.Entity.dll
Step into: Stepping over method without symbols 'System.Data.Entity.Infrastructure.DbContextInfo.CreateActivator.AnonymousMethod__0'
Step into: Stepping over method without symbols 'System.Data.Entity.Infrastructure.DbContextInfo.CreateInstance'
Step into: Stepping over method without symbols 'System.Data.Entity.Migrations.DbMigrator.SeedDatabase'
[update]
Information about the initializer
private static string _connectionString;
public Context()
: base(_connectionString )
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
}
public Context(string connString)
: base(connString)
{
_connectionString = connString;
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
}
public Context(string connString )
: base(connString)
{
_connectionString = connString;
}
For the Configuration class
namespace SBD.Syrius.DataLayer.Migrations
{
using System.Data.Entity.Migrations;
public sealed class Configuration : DbMigrationsConfiguration<SBD.Syrius.DataLayer.Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(SBD.Syrius.DataLayer.Context context)
{
}
}
}
If you look at the call stack, you can see that it's going through a database migration. This is the process that occurs when you make a change to your model, and the database structure needs to be updated.
After the migration occurs, EF then calls SeedDatabase, which allows you to add default values. At the end of SeedDatabase, it calls SaveChanges to save those changes.
This exception was called in the GenericRepository.cs for my UnitOfWork when I tried to create a new entity.
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
Easy Fix
In the Package Manager Console. Add a new migration Add-Migration SomeMeaninglessName and updated the database Update-Database.
Related
I followed this example and implemented with kafka json same sample data.
consumer sample data {"temperature" : 28,"machineName":"xyz"}
DataStream<Alert> patternStream = CEP.pattern(inputEventStream, warningPattern)
.flatSelect(new PatternFlatSelectFunction<TemperatureEvent, Alert>() {
private static final long serialVersionUID = 1L;
#Override
public void flatSelect(Map<String, List<TemperatureEvent>> event, Collector<Alert> out) throws Exception {
new Alert("Temperature Rise Detected:" + ((TemperatureEvent) event.get("first")).getTemperature()
+ " on machine name:" + ((MonitoringEvent) event.get("first")).getMachineName());
}
Now i am getting issue with ArrayList cast
Exception in thread "main" org.apache.flink.runtime.client.JobExecutionException: Job execution failed.
at org.apache.flink.runtime.jobmaster.JobResult.toJobExecutionResult(JobResult.java:146)
at org.apache.flink.runtime.minicluster.MiniCluster.executeJobBlocking(MiniCluster.java:647)
at org.apache.flink.streaming.api.environment.LocalStreamEnvironment.execute(LocalStreamEnvironment.java:123)
at Test.KafkaApp.main(KafkaApp.java:61)
Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to Test.TemperatureEvent
at Test.KafkaApp$2.flatSelect(KafkaApp.java:53)
at org.apache.flink.cep.operator.FlatSelectCepOperator.processMatchedSequences(FlatSelectCepOperator.java:66)
at org.apache.flink.cep.operator.AbstractKeyedCEPPatternOperator.processEvent(AbstractKeyedCEPPatternOperator.java:382)
at org.apache.flink.cep.operator.AbstractKeyedCEPPatternOperator.processElement(AbstractKeyedCEPPatternOperator.java:198)
at org.apache.flink.streaming.runtime.io.StreamInputProcessor.processInput(StreamInputProcessor.java:202)
at org.apache.flink.streaming.runtime.tasks.OneInputStreamTask.run(OneInputStreamTask.java:105)
at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
at org.apache.flink.runtime.taskmanager.Task.run(Task.java:704)
at java.lang.Thread.run(Unknown Source)
Your code contains two problems:
First of all flatSelect receives a Map<String, List<TemperatureEvent>>. This means that you get potentially multiple TemperatureEvents per pattern. Thus, you have to select which one you want.
You don't add any Alerts to the Collector<Alert>. A flat map function does not return values but outputs them via a Collector<Alert>
Without compiling, I think this should do the trick
DataStream<Alert> patternStream = CEP.pattern(inputEventStream, warningPattern)
.flatSelect(
new PatternFlatSelectFunction<TemperatureEvent, Alert>() {
private static final long serialVersionUID = 1L;
#Override
public void flatSelect(Map<String, List<TemperatureEvent>> event, Collector<Alert> out) throws Exception {
TemperatureEvent temperatureEvent = event.get("first").get(0);
out.collect(new Alert("Temperature Rise Detected:" + temperatureEvent.getTemperature() + " on machine name:" + temperatureEvent.getMachineName()));
}
});
By the way, the linked code from the O'Reilly repository won't compile with Flink. The PatternSelectFunction has the wrong signature.
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.
I have a Datagrid with checkbox. When an item is selected, the checkbox is checked and the row is highlighted. When I clicked the DataGridColumnHeader while there are items selected, the selected items are added again on the SelectedItems of the DataGrid. So if I currently have 2 SelectedItems, if I click the DataGridColumnHeader, the SelectedItems count would be 4 - the added items are a duplicate of the selected items.
I do not know why the SelectedItems is updated whenever I click DataGridColumnHeader. I have an IsSelected property on my Model. I tried to debug to know which is updating the selection then I got this external code below:
PresentationFramework.dll!MS.Internal.Data.PropertyPathWorker.SetValue(object item, object value) + 0x1c5 bytes
PresentationFramework.dll!System.Windows.Data.BindingExpression.UpdateSource(object value) + 0xce bytes
PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.UpdateValue() + 0xa9 bytes
PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.Dirty() + 0x7a bytes
PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.SetValue(System.Windows.DependencyObject d, System.Windows.DependencyProperty dp, object value) + 0x3e bytes
WindowsBase.dll!System.Windows.DependencyObject.SetValueCommon(System.Windows.DependencyProperty dp, object value, System.Windows.PropertyMetadata metadata, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType, bool isInternal) + 0x3b1 bytes
WindowsBase.dll!System.Windows.DependencyObject.SetCurrentValueInternal(System.Windows.DependencyProperty dp, object value) + 0x99 bytes
PresentationFramework.dll!System.Windows.Controls.Primitives.Selector.AdjustNewContainers() + 0x11d bytes
PresentationFramework.dll!System.Windows.Controls.ItemContainerGenerator.SetStatus(System.Windows.Controls.Primitives.GeneratorStatus value) + 0xb0 bytes
PresentationFramework.dll!System.Windows.Controls.ItemContainerGenerator.BatchGenerator.System.IDisposable.Dispose() + 0x22 bytes
PresentationFramework.dll!System.Windows.Controls.VirtualizingStackPanel.MeasureOverrideImpl(System.Windows.Size constraint, ref double? lastPageSafeOffset, ref System.Collections.Generic.List<double> previouslyMeasuredOffsets, bool remeasure) + 0x1e83 bytes
PresentationFramework.dll!System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(System.Windows.Size constraint) + 0x106 bytes
PresentationFramework.dll!System.Windows.Controls.Primitives.DataGridRowsPresenter.MeasureOverride(System.Windows.Size constraint) + 0x3b bytes
PresentationFramework.dll!System.Windows.FrameworkElement.MeasureCore(System.Windows.Size availableSize) + 0x313 bytes
PresentationCore.dll!System.Windows.UIElement.Measure(System.Windows.Size availableSize) + 0x521 bytes
PresentationCore.dll!System.Windows.ContextLayoutManager.UpdateLayout() + 0x569 bytes
PresentationCore.dll!System.Windows.ContextLayoutManager.UpdateLayoutCallback(object arg) + 0x22 bytes
PresentationCore.dll!System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks() + 0x96 bytes
PresentationCore.dll!System.Windows.Media.MediaContext.RenderMessageHandlerCore(object resizedCompositionTarget) + 0xdf bytes
PresentationCore.dll!System.Windows.Media.MediaContext.RenderMessageHandler(object resizedCompositionTarget) + 0x2f bytes
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) + 0x5a bytes
WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source, System.Delegate method, object args, int numArgs, System.Delegate catchHandler) + 0x47 bytes
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeImpl() + 0x281 bytes
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x285 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x9 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x57 bytes
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.Invoke() + 0x71 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.ProcessQueue() + 0x2e3 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.WndProcHook(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0xb3 bytes
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x14a bytes
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) + 0x80 bytes
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) + 0x5a bytes
WindowsBase.dll!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source, System.Delegate method, object args, int numArgs, System.Delegate catchHandler) + 0x47 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) + 0x2bc bytes
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) + 0x140 bytes
[Native to Managed Transition]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) + 0x112 bytes
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x17a bytes
PresentationFramework.dll!System.Windows.Application.Run() + 0x67 bytes
UpgradeStudio.exe!UpgradeStudio.App.Main() + 0x70 bytes C#
[Native to Managed Transition]
[Managed to Native Transition]
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x57 bytes
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x285 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x9 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x57 bytes
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x51 bytes
[Native to Managed Transition]
How can I prevent the row to be selected when I click DataGridColumnHeader? Please help me. Thanks!
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);
}
I have an interesting situation where I need to do something like this:
[Export[typeof(ICandy1)]
[Export[typeof(ICandy2)]
public class Candy : ICandy2 { ... }
where
public interface ICandy1 { ... }
public interface ICandy2 : ICandy1 { ... }
I couldn't find any posts anywhere regarding using multiple [Export] attributes, so I figured, what the hell, might as well try it.
At first glance, it actually seemed to work. I have a couple of methods that call into both interfaces of a Candy instance, and it was fine.
However, as I started to test the app, I saw that the behavior wasn't right, and when looking at the Output window, I saw that I was getting tons of COMExceptions. I couldn't track down where they were all coming from, but they always occurred when a worker thread was sleeping. I figured that it had to be from the main thread, then, but didn't know how to debug this at all. Nothing should have been going on in the GUI, and I disabled my DispatchTimers just in case -- same thing.
Even more strange than the COMExceptions was the really, really erratic behavior when stepping through code. About 30% of the time, when I single stepped, it would pop out of the method, or it would single step over two lines of code! Totally weird stuff that I am not used to seeing.
The only thing that changed between working and non-working code was the introduction of MEF through my plugin loading code. So as a test, I changed my plugin assembly to only export one interface, and I hardcoded everything in the app that relied on the other (now not-implemented) interface. And now the COMExceptions are gone, and the weird debugging behavior is gone.
Is this something people here have seen before? If MEF is not expected to allow a class to Export multiple interfaces, then shouldn't a CompositionException get raised when composing the parts? Can anyone explain why MEF would cause these weird problems???
Here's a sample of the main thread's call stack around the time of the COMException. Not sure if it means anything to anyone, but if you can suggest any ways to debug this, that would be great.
> UIAutomationProvider.dll!MS.Internal.Automation.UiaCoreProviderApi.UiaHostProviderFromHwnd(System.IntPtr hwnd) + 0x38 bytes
UIAutomationProvider.dll!System.Windows.Automation.Provider.AutomationInteropProvider.HostProviderFromHandle(System.IntPtr hwnd) + 0x2d bytes
PresentationCore.dll!MS.Internal.Automation.ElementProxy.HostRawElementProvider.get() + 0x65 bytes
[Native to Managed Transition]
[Managed to Native Transition]
UIAutomationProvider.dll!System.Windows.Automation.Provider.AutomationInteropProvider.RaiseAutomationPropertyChangedEvent(System.Windows.Automation.Provider.IRawElementProviderSimple element, System.Windows.Automation.AutomationPropertyChangedEventArgs e) + 0x2a bytes
PresentationCore.dll!System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree() + 0x2c9 bytes
PresentationCore.dll!System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree() + 0x2f8 bytes
PresentationCore.dll!System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree() + 0x2f8 bytes
PresentationCore.dll!System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree() + 0x2f8 bytes
PresentationCore.dll!System.Windows.ContextLayoutManager.fireAutomationEvents() + 0x98 bytes
PresentationCore.dll!System.Windows.ContextLayoutManager.UpdateLayout() + 0x65b bytes
PresentationCore.dll!System.Windows.ContextLayoutManager.UpdateLayoutCallback(object arg) + 0x19 bytes
PresentationCore.dll!System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork() + 0x10 bytes
PresentationCore.dll!System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks() + 0x97 bytes
PresentationCore.dll!System.Windows.Media.MediaContext.RenderMessageHandlerCore(object resizedCompositionTarget = null) + 0x80 bytes
PresentationCore.dll!System.Windows.Media.MediaContext.RenderMessageHandler(object resizedCompositionTarget) + 0x2b bytes
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback = {Method = Cannot evaluate expression because the code of the current method is optimized.}, object args = null, bool isSingleParameter = true) + 0x8a bytes
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source = {System.Windows.Threading.Dispatcher}, System.Delegate callback, object args, bool isSingleParameter, System.Delegate catchHandler = null) + 0x4a bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate callback, object args, bool isSingleParameter, System.Delegate catchHandler) + 0x44 bytes
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeImpl() + 0x5d bytes
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(object state) + 0x38 bytes
mscorlib.dll!System.Threading.ExecutionContext.runTryCode(object userData) + 0x51 bytes
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x67 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x45 bytes
WindowsBase.dll!System.Windows.Threading.DispatcherOperation.Invoke() + 0x63 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.ProcessQueue() + 0x127 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.WndProcHook(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x63 bytes
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd = 464158, int msg = 49869, System.IntPtr wParam = 0, System.IntPtr lParam = 0, ref bool handled = false) + 0xbe bytes
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) + 0x7a bytes
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback = {Method = Cannot evaluate expression because the code of the current method is optimized.}, object args = {MS.Win32.HwndSubclass.DispatcherOperationCallbackParameter}, bool isSingleParameter = true) + 0x8a bytes
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source = {System.Windows.Threading.Dispatcher}, System.Delegate callback, object args, bool isSingleParameter, System.Delegate catchHandler = null) + 0x4a bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate callback, object args, bool isSingleParameter, System.Delegate catchHandler) + 0x44 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.InvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, bool isSingleParameter) + 0x91 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority priority, System.Delegate method, object arg) + 0x40 bytes
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd = 464158, int msg = 49869, System.IntPtr wParam = 0, System.IntPtr lParam = 0) + 0xdc bytes
[Native to Managed Transition]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0xc7 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes
Dan pointed out that specifying two ExportAttributes would likely create two instances from the different ImportAttributes, but I believe it only created one instance because I put a breakpoint in the constructor for Candy and it was only hit during the lifetime of the app.
Having multiple exports on a single class is a perfectly normal use case in MEF. We do this all the time without problems.
Dan's remark is not correct. Unless you explicitly set a part creation policy on the import or export, MEF will prefer to reuse instances within a container rather than create multiple ones.
The COM exceptions you are seeing have nothing to do with MEF, as MEF itself is purely managed and doesn't use use any COM interop. You should take a look at the COM exception message and its stack trace. To make the debugger break when such an exception occurs, configure visual studio accordingly (Use the shortcut ctrl+d, e to see the relevant settings).
The erratic debugger behavior which you describe usually means that the source code and the compiled assembly do not match. Try cleaning out your bin folder, and check that the dependencies between your projects are project references rather than direct assembly references. Direct assembly reference do not properly trigger rebuilds if the source code of the dependency has changed.