[SOLVED] TypeInitializationException accessing GraphicsAdapter.Adapters, could not load type 'SharpDX.Rectangle'

Converting VB code from XNA 3.1 to MonoGame.

Any attempt to access class GraphicsAdapter throws the exception below. For example, trying to enumerate GraphicsAdapters. On this line:

For Each adapter As GraphicsAdapter In GraphicsAdapter.Adapters

Result is an exception:

System.TypeInitializationException occurred
  HResult=-2146233036
  Message=The type initializer for 'Microsoft.Xna.Framework.Graphics.GraphicsAdapter' threw an exception.
  Source=MonoGame.Framework
  TypeName=Microsoft.Xna.Framework.Graphics.GraphicsAdapter
  StackTrace:
	   at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.get_Adapters()
	   at ...my code...
  InnerException: 
	   HResult=-2146233054
	   Message=Could not load type 'SharpDX.Rectangle' from assembly 'SharpDX, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b4dcf0f35e5521f1'.
	   Source=MonoGame.Framework
	   TypeName=SharpDX.Rectangle
	   StackTrace:
			at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.CreateAdapter(Adapter1 device, Output monitor)
			at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.PlatformInitializeAdapters(ReadOnlyCollection`1& adapters)
			at Microsoft.Xna.Framework.Graphics.GraphicsAdapter..cctor()

Note the inner exception:

Could not load type 'SharpDX.Rectangle' from assembly 'SharpDX, Version=4.0.1.0, ... 

The project references these assemblies (among others):

  • MonoGame.Framework version=3.6.0.1625
    from NuGet “MonoGame.Framework.WindowsDX”, file
    packages\MonoGame.Framework.WindowsDX.3.6.0.1625\lib\net40\MonoGame.Framework.dll
  • SharpDX version=4.0.1.0
  • SharpDX.Direct2D1 version=4.0.1.0
  • SharpDX.Direct3D9 version=4.0.1.0
  • SharpDX.DXGI version=4.0.1.0
  • SharpDX.Mathematics version=4.0.1.0

So I don’t see why it would fail this way.

What could be wrong? Not compatible with this SharpDX version?

NOTE: These are all up-to-date packages from NuGet, in Visual Studio 2015. Targeting .Net 4.5.2.


UPDATE

To prove it isn’t a problem with SharpDX, I put this line before that GraphicsAdapter line:

Dim testRect As SharpDX.Rectangle = New Rectangle()

This successfully created testRect. No Exception until attempt to access GraphicsAdapter. Also tried all the other Shared (static) properties of GraphicsAdapter, such as GraphicsAdapter.DefaultDevice. Any one fails with same exception.


SOLVED

(from teamcity) MonoGameSetup.exe v.3.7.0.994 works with SharpDX 4.0.1.

However, the list of SharpDX dlls in C:\Program Files (x86)\MonoGame\v3.0\Assemblies\Windows is missing SharpDX.Mathematics.dll; I used the NuGet version of SharpDX instead.

Can you provide some background information?

Have you successfully run MonoGame templates from scratch?

Is this your first time?

Are your system drivers in check?

What OS?

What project type?

What is your display setup? Dual Display?

Are you using a system with discrete and dedicated graphics?

Laptop? Desktop?

Something’s wrong with the SharpDX version.
First, you don’t need to reference SharpDX from your project.
Second, MG 3.6.0.1625 uses an earlier version of sharpDX, 3.x.

I suggest to remove the nuget package(s) and references to monogame & SharpDX,
install MG 3.6 from here, and then add a reference to
C:\Program Files (x86)\MonoGame\v3.0\Assemblies\Windows\MonoGame.Framework.dll

We recently upgraded to 4.0.1, but that’s on the develop version, not the 3.6 release of course.

Testing now with MG 3.6 from location you suggest, and using a MonoGame template.

Test 1: Template, unmodified - works. (window with blue client area draws).

So MonoGame by itself works fine. However, my app has DirectX calls, so I do need to reference SharpDX.


(At this point, I had not seen the SharpDX dlls installed by MonoGame installer in C:\Program Files (x86)\MonoGame\v3.0\Assemblies\Windows, so was still trying to get it to work with some NuGet install of SharpDX. Also, I wanted to see if it was possible to use a newer version of SharpDX than the one included there.)

Test 2: trying with SharpDX 3.0.0 on NuGet, as @Jjagg suggests should be compatible with MG 3.6
Add a NuGet reference to the template project. Result at Program.Main / game.Run();:

Microsoft.Xna.Framework.Graphics.NoSuitableGraphicsDeviceException was unhandled
  HResult=-2146233088
  Message=Failed to create graphics device!
  Source=MonoGame.Framework
  StackTrace:
	   at Microsoft.Xna.Framework.GraphicsDeviceManager.CreateDevice()
	   at Microsoft.Xna.Framework.GraphicsDeviceManager.Microsoft.Xna.Framework.IGraphicsDeviceManager.CreateDevice()
	   at Microsoft.Xna.Framework.Game.DoInitialize()
	   at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior)
	   at Microsoft.Xna.Framework.Game.Run()
	   at MonoGameOnDirectX.Program.Main() in c:\users\toolm\documents\visual studio 2015\Projects\MonoGameOnDirectX\Program.cs:line 18
	   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
	   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
	   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
	   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
	   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
	   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
	   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
	   at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
	   HResult=-2146233036
	   Message=The type initializer for 'Microsoft.Xna.Framework.Graphics.GraphicsAdapter' threw an exception.
	   Source=MonoGame.Framework
	   TypeName=Microsoft.Xna.Framework.Graphics.GraphicsAdapter
	   StackTrace:
			at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.get_DefaultAdapter()
			at Microsoft.Xna.Framework.GraphicsDeviceManager.PrepareGraphicsDeviceInformation(GraphicsDeviceInformation gdi)
			at Microsoft.Xna.Framework.GraphicsDeviceManager.DoPreparingDeviceSettings()
			at Microsoft.Xna.Framework.GraphicsDeviceManager.CreateDevice()
	   InnerException: 
			HResult=-2146233054
			Message=Could not load type 'SharpDX.Rectangle' from assembly 'SharpDX, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b4dcf0f35e5521f1'.
			Source=MonoGame.Framework
			TypeName=SharpDX.Rectangle
			StackTrace:
				 at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.CreateAdapter(Adapter1 device, Output monitor)
				 at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.PlatformInitializeAdapters(ReadOnlyCollection`1& adapters)
				 at Microsoft.Xna.Framework.Graphics.GraphicsAdapter..cctor()
			InnerException: 

Investigating, I see that installing the SharpDX 3.0.0 created this app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
	<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
	  <dependentAssembly>
		<assemblyIdentity name="SharpDX" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
		<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
	  </dependentAssembly>
	</assemblyBinding>
  </runtime>
</configuration>

Additional experimentation with my original project, removing a similar bindingRedirect I got a load failure - was looking for SharpDX 2.6.3. (Reference from the NuGet MonoGame 3.6.0.1625).

It appears that MG uses SharpDX 2.6.3 -
I confirmed that using SharpDX 2.6.3, that error is not received.
It appears that the latest released MonoGame 3.6.0.1625 is not compatible with any SharpDX 3.0.0+

I would prefer not to use a version that old; I’ve got DirectX calls that aren’t included in that.

Is there anywhere I can obtain a built version from the development branch?
If not, I’ll try to build it myself.

You can download a build from teamcity: http://teamcity.monogame.net/viewLog.html?buildId=56483&tab=artifacts&buildTypeId=MonoGame_PackagingWindows

Thank you.

SOLVED - Indeed, teamcity MonoGameSetup.exe v.3.7.0.994 works with SharpDX 4.0.1 (from NuGet), both when adding SharpDX reference to a template project, and in my original application.

NOTE: As a convenience, it would be good to add SharpDX.Mathematics.dll to the dlls in
C:\Program Files (x86)\MonoGame\v3.0\Assemblies\Windows, and similar locations.

How/where would I file this as a suggestion?

Why is that? We don’t need the Mathematics assembly, so we omit it to reduce the nr and size of dependencies.

OK, that makes sense.

Here is the reason I suggested including Mathematics:

I only ran into this problem because I was trying to manually install SharpDX separately from MonoGame.
It might make sense for most people to instead use the SharpDX dlls as supplied with MonoGame.

I see that MonoGame already includes a lot of SharpDX dlls; I assumed Mathematics is considered one of the essential ones because it defines the Raw types (passed to DirectX), as contrasted with the corresponding “convenient” types used in most code. E.g. SharpDX.Vector3 <=> RawVector3.
I wasn’t able to get far in SharpDX coding without those raw types.

Bottom line: if you leave it out, then anyone who is doing coding directly to SharpDX might have to do what I did: discover what version of SharpDX is compatible with the MonoGame they are using, and download that, rather than use the SharpDX dlls included with MonoGame.

But if most people use MonoGame by itself, and don’t reference SharpDX, then it makes sense to omit it. (Or if my need for the Raw types is somehow unusual…) [It is strange that these essential Raw types are stuck in a separate dll, that is another 216 KB.]


UPDATE

It looks like I only needed Raw types because I did not realize I could use higher level equivalents. E.g. SharpDX.RectangleF instead of RawRectangleF.
This was an easy mistake to make: intellisense says a call needs a “RawRectangleF”, so naturally that is what I provided. That required including Mathematics.
I see that SharpDX has type conversions that automatically convert its high-level types to the raw types.

HOWEVER, even after converting all my references, so no longer using any “Raw” types,
still need Mathematics, because the higher level types (e.g. Vector3, RectangleF, Color4) are also defined there.


How can MonoGame run on SharpDX without SharpDX.Mathematics.dll being installed on the pc?

Those “essential” types are defined in that Mathematics dll, even though they are in namespace SharpDX.

They are not essential, because everything you need is exposed in SharpDX.Mathematics.Interop.

What puzzles me is that MonoGame on SharpDX must surely be using types that are (now) defined in the SharpDX.Mathematics.dll. Even types such as SharpDX.Color4 are defined in that dll. Doesn’t that mean that the next release of MonoGame will need to include SharpDX.Mathematics.dll? [3.7.0.994 does not]

It looks like MonoGame through 3.6.x was using SharpDX 2.6.3 - i think back then SharpDX.Color4 was defined in SharpDX.dll, but in newer builds is moved to SharpDX.Mathematics.dll, even though it is still in SharpDX namespace.

I’m not even remotely an expert on this; just wanted to mention this, in case it turns out to be important to the next release. If somehow my understanding of the situation is wrong, then disregard.

SharpDx has variants of those types included in the core assembly to keep things more lightweight. If you look inside MG source code you’ll see it uses SharpDX.Mathematics.Interop.RawColor4 and friends from the SharpDX assembly.