Autofac couldn't resolve dependency on TeamCity - c#

I have a such code (It's a part of unit tests executed by nunit-console):
class MyClass
{
[DI(Type = typeof(MyClass))]
public IMyClass MyClassProperty {get;set;}
}
By reflection i'm scanning such classes and then register in Autofac:
// Register MyClass as IMyClass
autofacBuilder.RegisterType(diAttribute.Type).As(propertyInfo.PropertyType);
After that i need to resolve this property in the same way - by reflection:
autofacContainer.Resolve(propertyInfo.PropertyType) // it contains IMyClass
When I'm launching this code locally it works well.
But doesn't work on TeamCity. Fails with error:
Error: 'Autofac.Core.DependencyResolutionException: An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Common Language Runtime detected an invalid program. (See inner exception for details.) ---> System.InvalidProgramException: Common Language Runtime detected an invalid program.

There are a lot of questions on StackOverflow about this exception. It's not an Autofac problem, it's a JIT compiler problem. A quick Google search on the exception yields a lot of info.
InvalidProgramException / Common Language Runtime detected an invalid program
Common Language Runtime detected an invalid program?
You even see projects like NewtonSoft.Json running into the issue.
The exception itself means "a program contains invalid Microsoft intermediate language (MSIL) or metadata; generally this indicates a bug in the compiler that generated the program."
Microsoft has a KB article on troubleshooting the issue. Whenever folks have resolved it, as far as I've seen, it's always one of two fixes:
A change to the compilation options. For example, some people running encryption/obfuscation sorts of tools find turning them off helps; others find turning off compiler optimization fixes it. (The KB article has some tips.)
Making sure things are patched to the latest versions. I've run into other similar situations myself where things work great on my machine but not on the build server; or vice versa. Almost invariably it's because I have my machine all patched up but the build server has been languishing unpatched; or someone just patched up the build server and I haven't installed my patches yet.
I'd recommend starting with the patches since that's usually the simplest fix. Use Windows Update to make sure both you and the build server have the latest .NET updates. If that doesn't fix it, check out some of the troubleshooting tips in the articles and questions above.

Related

Fatal error. Internal CLR error. (0x80131506) on String.Format() [duplicate]

The exception code C0000005 is thrown from mscorwks.dll when the application is run on Windows Server 2008 R2 launched using test complete. Other platforms (Windows XP, Server 2003 R2, Windows 7 32-bit and 64-bit) do not present this exception.
The event log from a single execution has many of the following event with event ID 1023 raised by the .NET Runtime:
.NET Runtime version 2.0.50727.4952 - Fatal Execution Engine Error (7383851A) (80131506)
The application itself makes use of a SOAP interface generated by Visual Studio from a WSDL file, a COM object with an embedded interop, and is targeting .NET 4.
sfc /scannow was run and found no problems with system files on the affected system.
What troubleshooting can be done to identify a solution?
Fatal Engine Execution Error and an access violation are both symptoms of the same problem. FEEE is raised when the .NET garbage collector detects that the internal structure of the garbage collected heap is destroyed. An access violation is a hardware exception, raised by the processor when it is asked to access memory with an invalid address. A common cause of an AV is heap corruption.
These kind of mishaps are very commonly caused by unmanaged code. It is also quite common for unmanaged code to have latent memory management bugs that can go unnoticed for a long time. The kind of damage the bug can do tends to be quite random. Just running it on another operating system which has a different memory allocation pattern can be enough to trigger the bomb.
You have an excellent candidate for the source of the trouble. You'll need to work with the COM server vendor or author to chase the bug.
A 0xC0000005 is an exception code wrapping a Win32 error which means "Access Denied." Given that you are using COM interop and are getting an ExecutionEngineException (in COM, COR_E_EXECUTIONENGINE; 0x80131506), my guess is that either it's a NULL pointer in the COM component or a faulty ComImport directive in your .NET code.
This error is caused by flaws in the way that TestComplete 7 interacts with the heap in mixed managed/unmanaged applications. Instead of using the TestedApp.Run method using the following block of code, modified for you choice of scripting language, presented in VBScript:
Dim oScript, command
Set oScript = CreateObject("WScript.Shell")
command = "%comspec% /c " & PATH_TO_EXE & " " & Args
oScript.Run command, 10, True
The relevant MSDN article is Run Method (Windows Script Host).
TestComplete 7 (including the latest update 7.52) supports .NET Framework 4 only up to version .NET 4 Beta 2. It does not support the release version of the Framework, so this may be the reason of the problem.
Try building the application targeting .NET 2.0. This should resolve the problem.
To test .NET 4 applications, you will need to use TestComplete 8.

KeyVaultClient throws FatalExecutionEngineError on debug randomly

When I debug ASP.NET MVC application, KeyVaultClient throws randomly exception:
Managed Debugging Assistant 'FatalExecutionEngineError' : 'The runtime has encountered a fatal error. The address of the error was at 0x59eab403, on thread 0x6098. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.'
I use:
nuget Microsoft.Azure.KeyVault 3.0.3
Visual Studio 2019 Professional 16.1.4
Microsoft.AspNet.WebApi 5.2.3
don't have Managed Compatibility Mode
I got familiar with this question and nothing helpful happens.
Edit
After enabling Managed Compatibility Mode I get slightly different error:
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in 'C:\Program Files (x86)\IIS Express\iisexpress.exe'.
Additional Information: The runtime has encountered a fatal error. The address of the error was at 0x6c0db403, on thread 0x54a8. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
occurred
From https://devblogs.microsoft.com/devops/switching-to-managed-compatibility-mode-in-visual-studio-2013/
New managed debug engine that provides us the ability to more rapidly add new features compared to the older implementation. This can be seen by the number of features introduced in Visual Studio 2013 after only a single year including Managed Return Values, .NET 64-bit Edit and Continue, Async Callstacks Enhancements, and Improved Tasks Window to name a few. Unfortunately, there are still a couple scenarios that are not supported yet with the new debug engine, so in these cases you will have to switch back to the legacy engine.
Error which you are getting is because of the issue which is not supported by new debug engine.
Please try below setting and see if you still get the same error.
To switch back to the legacy debug engine globally, select Tools/ Options
then check Use Managed Compatibility Mode on the Debugging / General tab.
The global option will force the legacy engine to be used for any launch or attach.
Hope it helps.

SimpleITK Windows Universal App - does not build in release, strange behaviour in debugging and TypeLoadException

TL;DR version: Could not load type 'System.Runtime.InteropServices.HandleRef while trying to use SimpleITK on Universal Windows App.
So, right now I have to make simple school project using SimpleITK, and, I got interested in new Universal Windows Applications. I am using Visual Studio 2015 Enterprise.
So, I created a sample project, added references to SimpleITKManaged, copy&pasted SimpleITKNative to obj/Debug catalog and tried to do some tutorials. However, I learned that mixing two new technologies together may be a bad idea.
The ITK libraries I use seem not to work with Universal Windows App. After putting this snippet anywhere in the code, I can not get to debug the method. Code is not hitting breakpoint at the beggining of the method. What is inside is not important, as any type from SimpleITK is causing code to fail.
private void TestMethod()
{//breakpoint here
ImageFileReader reader = new ImageFileReader();
reader.SetFileName(FileName);
var image = reader.Execute();
}
The exception seems to be thrown before code gets to method, probably at level of XAML. I tried first implementing a call as ICommand, then as event handler in the code behind, with no differences. The exception is also not too helpful:
Could not load type 'System.Runtime.InteropServices.HandleRef' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
Neither is StackTrace:
at Pomwjo.Universal.MainPage.ButtonBase_OnClick(Object sender, RoutedEventArgs e)
The same libraries work well in WPF. I tried both x64 and x86 libraries, with the same problem. The build target and library architecture are matching. I'm using SimpleITK C# x86 wrapper 0.9.0, compiled with .NET v2.0.50727, using ITK 4.7.2. I got them pre-built from Sourceforge. Just after that, I found a 0.9.1 version, which I downloaded and tried to use it, to no avail.
Next step was ok, I'm a pro programmer - I'll build it myself!. I will spare describing what it is to build a huge library, let's just say it didn't work either.
Any ideas, how to fix this problem?
EDIT 1
I just realized, that if code is unreachable, it doesn't complain. Well, at least that is working as expected. But, what is even stranger, this snippet fails only if condition is met:
if (new Random().Next(1, 10)%2 == 0)
WrapperMethod(); //inside is snippet from above.
else return;
Also, when building in release, I get this error:
1>C:\Program Files (x86)\MSBuild\Microsoft\.NetNative\x64\ilc\IlcInternals.targets(791,7): error : MCG0024: MCG0024:UnresolvableTypeReference Unresolvable type reference 'System.Runtime.InteropServices.HandleRef' in 'Assembly(Name=mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)' found. Check the references in your build system. A reference is either missing or an assembly is missing an expected type.
When this question was first written, it was impossible to use simpleITK in Universal Apps because it lacked some of classes required for it to work - including System.Runtime.InteropServices.HandleRef.
Also, because all apps are run in sandbox, my guess (educated, but still guess) is that it is downright impossible to use native C++ code which is used by SimpleITK. This link describes a way to import native code into app, however this would require quite a bit of tinkering around ITK libraries itself - which was not a point in my project.

Problems Registering Oracle.DataAccess as SQLCLR assembly in MS SQL Server 2012

EDIT 3.5 (Meant to put Item 3 below in the last update, but overlooked. Alas...)
Looking at how the assembly registration fails for my problem and looking at what limited info I am able to infer from ProcExplorer traces leads me to make some conclusions on a few things. No solutions, just a few inferences
1. Microsoft wants to, at some point, allow for Framework 2.0 assemblies to be loaded. I make this inference on the basis that if they were exclusively bound to the notion of precluding them, validation could fail with an immediate check on an assembly's framework metadata. The failure would be analagous to to load 4.0 assemblies in 2008R2 - with stern and specific errors to the contrary, saying Thou Shalt Not Do.
2. If I perform an upgrade to a 2008R2 database that contains a 2.0 assembly, the assembly is loaded and functions from it will fire in a SQL 2012 database. So the ability to execute 2.0 based assemblies is very much present. Getting them past the loader is the trick - hence reinforcing my belief that it won't surprise me to discover a patch or SP that suddenly enables 2.0 framework assemblies in the CLR.
3. I believe that, either through deliberate change or bug, some of the validation semantics implied by PERMISSION_ SET = UNSAFE have changed in SQL2012. My experience leads me to believe that prior versions of SQL Server's CLR Verifier performed the equivalent of a PEVERIFY /MD when PERMISSION_SET = UNSAFE is specified (not checking for things like unmanaged pointers), and PEVERIFY /IL when it is not. It appears to me, however, that in SQL 2012, the CLR Verifier performs a PEVERIFY /IL regardless of the UNSAFE permission flag. I would love to find if someone could verify this theory*
EDIT2
After continued research to this problem, I have not yet found a solution short of retrofitting the project to use the now-deprecated System.Data.OracleClient provider Microsoft created some years ago. Also, further research and emails leads me to believe there's at least one or two "battery not included" notices about changes to assembly validation between SQL 2008R2 and SQL 2012 - and this assembly seems to point precisely to that. More than a few blog posts on SQLCLR assembly registration issues have led to assertions that nothing in the validation process changed, yet registering the same assembly between two databases has generated an otherwise inexplicable problem. I cannot find how SQLServer validates an assembly so at the moment, I continue to search for a solution a bit (well, entirely) in the dark...*
There exists a long-standing SQLCLR project within our MS SQL Server database that makes various critical queries to an Oracle database. This project has been working well for about six years now, having been migrated from a 32-bit assembly in SQL 2005 and into a 64-bit assembly for MS SQL Server 2008 R2.
Despite the fact that the MS SQL 2012 Upgrade Advisor pointed out only general issues with SQLCLR migration regarding certain geographic types, I had a sneaking, ugly suspicion this migration might be truly problematic. Sure enough, I've found that migrating this project into SQL Server 2012 is now presenting what I fear is an intractable problem.
When attempting to register this same 64-bit Oracle.DataAccess.dll (2.112.1.0) that has been living now happily in SQL Server 2008R2 (and its ancestors) for some time, the database now advises that the assembly "fails verification". Edit: My understanding has always been that an assembly granted UNSAFE permissions does not go through validation checking. Is this not correct?
An excerpt of the error response follows:
[ : Oracle.DataAccess.Client.OracleDatabase::Startup][mdToken=0x6000021][offset 0x00000048][found unmanaged pointer][expected readonly address of value 'Oracle.DataAccess.Client.OpoConValCtx'] Unexpected type on the stack.
[ : Oracle.DataAccess.Client.OracleDatabase::Startup][mdToken=0x6000021][offset 0x00000080][found unmanaged pointer][expected unmanaged pointer] Unexpected type on the stack.
[ : Oracle.DataAccess.Client.OracleDatabase::Startup][mdToken=0x6000021][offset 0x000000E3][found unmanaged pointer][expected readonly address of value 'Oracle.DataAccess.Client.OpoConValCtx'] Unexpected type on the stack.
[ : Oracle.DataAccess.Client.OracleDatabase::Startup][mdToken=0x6000021][offset 0x0000011B][found unmanaged pointer][expected unmanaged pointer] Unexpected type on the stack.
[ : Oracle.DataAccess.Client.OracleDatabase::Shutdown][mdToken=0x6000023][offset 0x0000003C][found unmanaged pointer][expected readonly address of value 'Oracle.DataAccess.Client.OpoConValCtx'] Unexpected type on the stack.
[ : Oracle.DataAccess.Client.OracleDatabase::Shutdown][mdToken=0x6000023][offset 0x00000073][found unmanaged pointer][expected unmanaged pointer] Unexpected type on the stack.
[ : Oracle.DataAccess.Client.OracleTransaction::Commit][mdToken=0x600002f][offset 0x0000008F][found unmanaged pointer][expected readonly address of value 'Oracle.DataAccess.Client.OpoTxnValCtx'] Unexpected type on the stack.
[ : Oracle.DataAccess.Client.OracleTransaction::Commit][mdToken=0x600002f][offset 0x000000A6][found unmanaged pointer][expected unmanaged pointer] Unexpected type on the stack.
[ : Oracle.DataAccess.Client.OracleTransaction::Dispose][mdToken=0x6000034][offset 0x0000001E][found unmanaged pointer][expected Native Int] ...
Realizing that SQLCLR in 2012 now uses .NET 4.0, I thought perhaps version 4.0 of the same DLL might solve the problem. So I downloaded the 64-bit version of ODAC 12.1.0.1, which provided the 4.0 specific version of the library. Yet similar (but not identical) assembly creation/validation failures were seen - particularly regarding "unmanaged pointer types cannot be verified."
I then tried to use managed code versions of Oracle.DataAccess (Oracle.ManagedDataAccess), and that assembly depends upon a secondary assembly that also fails registration due to it not being a "pure" PE format assembly (which subsequent research has led me to believe it has a disallowed mixture of MSIL and assembly). So that, to me, means the managed code version can never be loaded in the SQLCLR.
So I am left, at this point, with questions and few answers. What, exactly, has changed about assembly validation between 2005/2008/2008R2 and 2012 that will now prevent a given assembly from validating? Are there any options or solutions possible to get Oracle.DataAccess to register? Failing that will make getting the project reconfigured/retargeted to .NET 4.0 moot. Eliminating this component from our system would be a monumental headache, so any solutions or suggestions would be greatly appreciated.
Indeed, SQL Server 2012 works with .NET Framework 4.0, and only that. There's no way you can load multiple versions of the CLR in SQL Server. This is by design. SQL Server 2012 does also not allow mixed assemblies to be loaded anymore.
What you can do is create a separate (web)service that contains the current .NET 2.0 functionality. Then call methods on that service from a pure .NET 4.0 CLR assembly that you create. I think this is the most likely solution there is to your problem.

System.IO.FileNotFoundException was unhandled Message=“The specified module could not be found. (Exception from HRESULT: 0x8007007E)”

I'm looking at code that is new-to-me. I have c++ code in a project called UI, with a number of dependencies, which builds correctly and doesn't return any errors. In the same solution in Visual Studio 2008, I have created a new C# windows forms project and added a reference to the dll generated by the UI project, and added a "using" statement. What I want to do is raise one of the dialogs that are defined in the UI project, so I have code like
UIDialog uIDialog = new UIDialog();
uIDialog.Show();
which builds.
When I run my project in debug, when it gets to the "new" part, I get the exception above - with no information as to what the missing module is.
Is there any way to find out what the missing module is, without digging through the code in the UI project?
(I'm trying to rephrase this question so that it doesn't get closed. If someone could give the definitive answer of "No, there isn't" I'd find that very helpful. Thanks also to those who closed the previous version.)
Edit:
System.IO.FileNotFoundException occurred
Message="The specified module could not be found.
(Exception from HRESULT: 0x8007007E)"
Source="ui"
StackTrace:
at ui.UIDialog.Startup()
at ui.UIDialog..ctor() in c:\..\ui\UIDialog.h:line 61
InnerException:
That's the problem, there's no useful information anywhere obvious!
It's not a 32/64 bit problem - before getting here, I had the typical "BadImageFormatException", so to get past that I forced everything to be 32bit.
You could use the MSIL Disassembler on the referenced dll and check the manifest for all the dependencies of the dll. The disassembler is part of the Windows SDK tools.
Or there is always DependencyWalker, though I haven't used it in years.
You can turn on Fusion logging to see what the loader is doing and find out what's missing.

Categories