Mysterious System.BadImageFormatException Error using MS test on VS Express 2013 when trying to create unit tests for a Grasshoppper plugin

Continuing the discussion from Unit testing plug-in code with NUnit:

Hi Menno (and other rhino developers),

I am writing a Grasshpper plugin and am trying to use MS test (since i am useing VS express 2013 i’m pretty sure this is only integratable option). At first I was running tests and geting a “System.DLLNotFoundException” on rhcommon_c.dll. Following the instructions here i copyied over the files to the output folder of my unit test dll but now i get:

System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) says that it could be a couple of things:

  1. a 32bit - 64 bit thing. I checked and all my .dlls are compling to “any cpu” so i think that is ok.
  2. “Make sure that you are not using a component that was created with a different version of the .NET Framework.” I am using .net 4.5.1 but the test .gha components i have created seem to work fine in Grasshopper itself so that doesn’t make sense to me.
  3. “Make sure that the file image is a valid managed assembly or module.” I know rhcommon_c is vaild becuase rhino won’t run without it. If it is becuase i’m not allowed to use unmanaged stuff in the environment i’m in then dosen’t RhinoCommon.dll insulate me from that?

Any suggestions would be greatly appreciated.

My guess is it is either 1 and/or 2.

First of all, Any CPU does not guarantee that there is no 32/64-bit issue. Because Rhino starts in either 32- or 64 bit mode, this will load the correct .NET framework and all other components in the correct bitness too. AnyCPU components will be JIT-compiled to the correct bitness and loaded.

If you start running things using MSTest, you need to instruct MSTest somehow that it uses the same bitness as the Rhino you linked against. So, if you linked against 64-bit Rhino, you probably have to set your project Platform Target to x64. (NOTE: there are two, easily confused, properties in the Build tab of a C# project. One is “Platform”, the other “Platform Target”. You need to set that latter property!)

Next, I’m not 100% sure that if you target .NET framework 4.5.1 that it should work flawlessly outside Rhino/Grasshopper. If the above does not fix it, try targeting framework 4.0 - that works in my case.

@dieterarn Have you solved your issue ?
I had the same problem, when tried to run unit tests using MSTest adapter.
Two types of exception were thrown System.BadImageFormatException and System.DllNotFoundException: Unable to load DLL ‘rhcommon_c’: Invalid access to memory location.

I solved the problem when switched to vstest.console.exe. This adapter is newer then MStest.exe, but also has its drawbacks. After test running, executing process vstest.executionengine.exe was not closing.