Why do I get an Invalid Operation Exception (non STA thread?) running this MSpec test on TeamCity? - .net-4.0

As part of the migration of my app to .NET 4, I'm struggling to get some of the WPF unit tests working again with TeamCity.
On all the tests that are somehow using a WPF control (a ListItem for example), I get an exception I didn't get before:
System.InvalidOperationException: The calling thread must be STA, because many UI components require this.
I understand what it means, and after checking, it turns out that my thread is indeed MTA, not STA.
My problem is that I have no idea on how to fix this, and where this problem could be coming from...
Is it a setting on TeamCity? MSpec?
Again, it worked before I switched to .NET 4.
I tried many different solutions, but nothing worked.
I'm also a bit puzzled by the fact that no-one reported this before (with my specific stack of TeamCity + MSpec + WPF test), which might mean I'm doing something very wrong somewhere.
If you have a clue, please let me know!
Full exception:
System.InvalidOperationException: The calling thread must be STA, because many UI components require this.
at System.Windows.Input.InputManager..ctor()
at System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
at System.Windows.Input.KeyboardNavigation..ctor()
at System.Windows.FrameworkElement.EnsureFrameworkServices()
at System.Windows.FrameworkElement..ctor()
at System.Windows.Controls.Control..ctor()
at MyCompany.Dashboard.Client.Plugins.Common.Controls.Grids.CashflowGrid.ViewModel.ConfigureViewModel.CreateItem(String name) in d:\Program Files\JetBrains\BuildAgent2\work\6dd9af6ae2f9bbb9\Code\Src\MyCompany\Dashboard\Client\Plugins\Common\Controls\Grids\CashflowGrid\ViewModel\ConfigureViewModel.cs:line 171
at MyCompany.Dashboard.Client.Plugins.Common.Controls.Grids.CashflowGrid.ViewModel.ConfigureViewModel.Initialise(Type type, IList`1 currentSelection, Action`1 selectionChangedCallback) in d:\Program Files\JetBrains\BuildAgent2\work\6dd9af6ae2f9bbb9\Code\Src\MyCompany\Dashboard\Client\Plugins\Common\Controls\Grids\CashflowGrid\ViewModel\ConfigureViewModel.cs:line 37
at UnitTests.Plugins.Common.Controls.Grids.CashflowGrid.ViewModel.when_some_items_are_selected_on_the_chosen_list.<.ctor>b__1() in d:\Program Files\JetBrains\BuildAgent2\work\6dd9af6ae2f9bbb9\Code\Src\UnitTests.Plugins.Common\Controls\Grids\CashflowGrid\ViewModel\ConfigureViewModelTests.cs:line 82
For this exception, the code is simply trying to instantiate a ListBoxItem, nothing fancy, but doing that on a MTA thread breaks it.
What I tried:
Setting the current thread to STA
Thread.CurrentThread.SetApartmentState(ApartmentState.STA)
It of course doesn't work because it's only possible before the thread starts
Run the code in a separate thread that was initialised as STA:
very complex since, due to the nature of MSpec, different methods are called at different time so you can't run EVERYTHING under the same thread. More precisely, you can't run the "Establish context" on the same thread as the "Because of" statement.
Use the STAThread attribute... yes but where? never worked anywhere I
tried
Example of a failing test:
public class StaTestExample
{
Establish context = () => _control = new ListBox();
It should_not_be_null = () => _control.ShouldNotBeNull();
protected static Control _control;
}

It now works.
But the problem is we just can't explain it. And it still fails on a different build server, but we don't care about this one.
In case someone gets that problem, here what we did:
Disabling test coverage
Disabling the MSPec task: the build goes green
Re-enabling coverage and MSpec: it works...
The odd thing is that exact process was applied on a different build server (an old one we don't use anymore), and it still fails.
There's nothing else we could think of that changed.
So it's a bit of a mystery... I hope it won't come back to bite us!

Related

What Has Happened to My VS2022 Development Environment

Hi there something weird has happended to intellisense in my VS2022 development environment. For example, if I refer to an object or enumerator, intellisense offers me a list of properties/methods completely unrelated to the object I am working with, the required properties are listed, its just that they are buried amongst completely unrelated stuff.
In addition, and probably related, when I put in exception handling as in for example:
Try
Catch ex as exception
End Try
When I type 'as' a whole raft of what appears to be boilerplate code gets dumped in place of the code that I am writing, I then have to execute an undo to get back to the original code.
Can someone clarify what is happening here and perhaps suggest a solution.
Kind Regards
Paul J.

procrun server crashes after few seconds

I have a web application, using Spring-Boot. There is now a need for this application to use a custom dll (in house build dll file). There is nothing wrong with this dll, as we use it on our other applications, and have no problems with it.
To load the library in this new web application I'm writing, I have added the dll file to the procrun directory. This directory is on the library path, so that makes sense.
During startup I put in code to immediately load the dll, and also test some of its functionality. This works fine.
However, I have a timer, that schedules the execution of some functions, which may or may not include function calls to the dll.
At some point, about 10 minutes or so into execution, the service unexpected and seemingly without any valid reason, stops.
Although I try/catch exceptions at the appropriate logical places in code, there are no relevant log entries printed.
The Event Log shows something that reminds me of a null pointer exception:
Another bread crumb is that the event log will print something about the dll_unload. (see picture)
I need some help figuring out why the service is failing/stopping.
Kind Regards.
EDIT: After about three days of debugging and scratching my head, I came upon a forum thread that explained that this problem has something to do with the manner in which the system releases the memory during garbage collection. It seems that the dll in question was being unloaded by the garbage collector, even though it could still be called at some time later - which of course was the cause of the service falling over.
To solve the problem, I put in a timer that would call a method in the dll at three minute intervals (on my system this would not impact performance). I know this solution is a hack, but it works for me.

Suddenly seeing lots of first chance exceptions in the output window of my ASP.NET MVC app

All of a sudden, I'm seeing floods of first chance exceptions in the VS.NET Output window.
There are 3 of us working on the project. We've all updated our code to the latest in SVN and I'm the only one seeing all the exceptions, so the issue is not our app, but I suspect, some setting that I accidentally triggered in VS.NET.
If I right click the Output window, "Exception Messages" is checked. It always has been and is for my co-workers, so that's not the issue.
I cannot see any options in Tools/Options/Debugging that could be responsible. I suspect I probably just accidentally hit some accelerator key combo that did it. These appear to be perfectly normal first chance exceptions (like setting a property in a dynamic object for the first time causing a RuntimeBindingException). The app seems to operate just fine. But the flood of messages is annoying and makes debug output hard to follow.
By far the most common exception is an ArgumentException with the message, "A property with the name 'UriTemplateMatchResults' already exists."
We use WCF very heavily (but no REST) and have a number of WCF services that our app communicates with, so I'm assuming that's just standard WCF stuff because the calls are all working fine.
Can anyone think of anything I might have done?
I discovered the source of the problem. As I suspected, it was something I had accidentally done, but I'm not sure when or exactly how. Hopefully this solution will help others.
The solution was Tools/Options/Debugging in the General section, I had somehow unchecked Enable Just My Code. I'm not sure how I unchecked it. That fixed the problem.

vb.net Run on crash

My program runs for about 10 hours during the night, sometimes I wake up to see that it has crashed (for whatever reason). It is usually a "Program Name" has stopped working, and the only button there is to close the program. I have tried watching and waiting for it to crash but the problem seems very hard to reproduce (and I can't watch it 24/7). I have used try and catch statements in my program in potentially problematic areas and told the program to dump to a text file if it catches an exception. But this isn't good enough it seems.
TLDR: Is it possible to tell my program to run a particular function when an exception has been detected in the program in general (without specifics) so that I can dump the stacktrace to a text file and investigate later?
Is it possible to tell my program to run a particular function when an exception has been detected...
Yes, but the specifics depend on the platform that you are using:
If you have a Console application, put a big Try ... Catch around Sub Main.
If you use WPF, add an event handler to AppDomain's or Dispatcher's UnhandledException event. Specifics can be found in the following question:
WPF global exception handler
In you use WinForms, you can also wrap Sub Main (which might be auto-generated) or attach to AppDomain.UnhandledException, see here for details:
WinForms Global Exception Handling?
For completeness, global exception handling in web applications is done in global.asax's Application_Error method:
How to catch unhandled exceptions in an asp.net application?
It's generally not a good idea to do this. You could, however, look at AppDomain.UnhandledException. This is pretty much restricted to one domain, and you'll also receive (potentially) notifications for all unhandled exceptions unrelated to your program.
This is usually used for class libraries, but I think with a bit of fiddle, you might get it to work.

Unreleased DirectShow CSource filter makes program crash at process shutdown

I'm developing a DirectShow CSource capture filter. It works fine, but when I close the program that is using the filter (in this case I'm testing with VLC, but the same happens with other programs), the program crashes (if I'm debugging it in Visual Studio then a breakpoint is triggered).
I've been hunting down this problem for some time now and found that both, my source filter and my source stream are not being released; this is, their reference counter is 1 at the end of the program, DllCanUnloadNow() function reports that there are 2 objects still in use, and, when CoUninitialize() is invoked, the program crashes.
I'm pretty sure that the reference counters are being handled correctly since I'm using the base classes implementation. The only unusual thing in my software that I can think of is that I'm using my own version of DllGetClassObject(): I configured the .DEF file to have MyDllGetClassObject() exported instead of DllGetClassObject() so I could insert some code before invoking the default implementation. I don't think this is a problem since I've checked that the reference counter of all objects I return at the end of MyDllGetClassObject() is 1.
I guess I'm missing something about the lifecycle of the filter, but can't figure out what (this is the very first capture filter I'm developing). Any suggestion?
Thank you in advance,
Guillermo
I finally figured out what was going on. The static method InitializeInstance in my source filter is invoked with bLoading == false and rclsid == <the GUID of my filter> at process shutdown. That seems to be the appropriate place to release that remaining reference counter from the filter instance.
I got the key idea of how important is to release all COM objects before CoUninitialize some time ago from another post on StackOverflow entitled DirectShow code crashes after exit (PushSourceDesktop sample). All I needed was just a little bit more knowledge on DirectShow filters lifecycle.
Anyway, thank you for your efforts, Roman, I know how vague this thread sounded from the beginning :)