Bug 31819 - An Exception was thrown by the type initializer
Summary: An Exception was thrown by the type initializer
Status: RESOLVED FIXED
Alias: None
Product: Android
Classification: Xamarin
Component: BCL Class Libraries ()
Version: 5.1
Hardware: PC Windows
: Normal normal
Target Milestone: ---
Assignee: Radek Doulik
URL:
: 31468 ()
Depends on:
Blocks:
 
Reported: 2015-07-10 07:51 UTC by Gerard
Modified: 2015-07-21 07:40 UTC (History)
4 users (show)

Tags:
Is this bug a regression?: ---
Last known good build:


Attachments
Sample Created (272.75 KB, application/octet-stream)
2015-07-10 09:24 UTC, Rajneesh Kumar
Details


Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
RESOLVED FIXED

Description Gerard 2015-07-10 07:51:20 UTC
I'm getting "An Exception was thrown by the type initializer" exception when i run my application in release mode. Works fine in debug. I thought initially it had to do with the linker, but i have removed that and now include everything and still receiving the error.

I have posted the issue up on Xamarin Forums 

https://forums.xamarin.com/discussion/44009/an-exception-was-thrown-by-the-type-initializer

I've no idea what the issue is or what's causing the issue. The only resolution was to revert back to Xamarin 3.9.547. Since Xamarin 3.11.445 the issue arises. I have created a sample application that replicates the issue. It happens in a third party dll but that dll hasn't changed in two years. This issue wont occur in any Xamarin version before 3.9.547

There is a read me in the solution that explains where the issue occurs and what you need to replicate it. 

To replicate the issue just click the button in the sample app and view the logcat information.
Comment 1 Gerard 2015-07-10 07:59:26 UTC
I cant attach the sample application but i have posted it on the xamarin forums link

https://forums.xamarin.com/discussion/44009/an-exception-was-thrown-by-the-type-initializer
Comment 2 Rajneesh Kumar 2015-07-10 09:24:29 UTC
Created attachment 11972 [details]
Sample Created

I tried to reproduce this but not able to reproduce this. To reproduce this issue I have created the sample but is was not successful, and I have attached it to this comment.

Screencast: http://www.screencast.com/t/KbjKJo11f

I am not sure about the steps to reproduce this issue, please provide me the steps or a small sample application that demonstrate this issue. That would be very helpful to reproduce this issue at our end.

Also if possible please provide us your full environemnt info an ide, exception details.

You can get Ide logs and enfo via:

Ide logs=: Help=>Open Log Directory (Choose latest time stamp)
Info=: Help=>About=>Show details=>Copy Information.

Thanks..!

Environment Info: 

=== Xamarin Studio ===

Version 5.9.5 (build 3)
Installation UUID: ec4ffedc-4d81-4b93-a154-b605f6d19ea9
Runtime:
	Microsoft .NET 4.0.30319.0
	GTK+ 2.24.22 (MS-Windows theme)
	GTK# 2.12.26

=== Xamarin.Android ===

Version: 5.1.4 (Starter Edition)
Android SDK: E:\android-sdk
	Supported Android versions:
		2.3    (API level 10)
		4.0.3  (API level 15)
		4.1    (API level 16)
		4.2    (API level 17)
		4.3    (API level 18)
		4.4    (API level 19)
		4.4.87 (API level 20)
		5.0    (API level 21)
Java SDK: C:\Program Files\Java\jdk1.7.0_71
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)

=== Xamarin Android Player ===

Not Installed

=== Build Information ===

Release ID: 509050003
Git revision: 5716b0c7ef341fff65ce7bd750be2b9ae64a1807
Build date: 2015-06-30 15:00:26-04
Xamarin addins: 8adf470161f63b54bcfea78416e4541f6d55d7bb

=== Operating System ===

Windows 6.2.9200.0 (64-bit)
Comment 3 Gerard 2015-07-10 09:57:26 UTC
I have added the sample application in the second comment. Its not any particular third party its the NetTopology suite for reading spacial shape files.

Screen cast of showing issue 

http://www.screencast.com/t/C4YJgGrc3Q
Comment 4 Gerard 2015-07-10 10:02:52 UTC
Microsoft Visual Studio Premium 2013
Version 12.0.31101.00 Update 4
Microsoft .NET Framework
Version 4.5.51209

Installed Version: Premium

LightSwitch for Visual Studio 2013   06191-004-0456024-02797
Microsoft LightSwitch for Visual Studio 2013

Team Explorer for Visual Studio 2013   06191-004-0456024-02797
Microsoft Team Explorer for Visual Studio 2013

Visual Basic 2013   06191-004-0456024-02797
Microsoft Visual Basic 2013

Visual C# 2013   06191-004-0456024-02797
Microsoft Visual C# 2013

Visual C++ 2013   06191-004-0456024-02797
Microsoft Visual C++ 2013

Visual F# 2013   06191-004-0456024-02797
Microsoft Visual F# 2013

Visual Studio 2013 Code Analysis Spell Checker   06191-004-0456024-02797
Microsoft® Visual Studio® 2013 Code Analysis Spell Checker

Portions of International CorrectSpell™ spelling correction system © 1993 by Lernout & Hauspie Speech Products N.V. All rights reserved.

The American Heritage® Dictionary of the English Language, Third Edition Copyright © 1992 Houghton Mifflin Company. Electronic version licensed from Lernout & Hauspie Speech Products N.V. All rights reserved.

ASP.NET and Web Tools   12.4.51016.0
Microsoft Web Developer Tools contains the following components:
Support for creating and opening ASP.NET web projects
Browser Link: A communication channel between Visual Studio and browsers
Editor extensions for HTML, CSS, and JavaScript
Page Inspector: Inspection tool for ASP.NET web projects
Scaffolding: A framework for building and running code generators
Server Explorer extensions for Microsoft Azure Websites
Web publishing: Extensions for publishing ASP.NET web projects to hosting providers, on-premises servers, or Microsoft Azure

ASP.NET Web Frameworks and Tools 2012.2   4.1.21001.0
For additional information, visit http://go.microsoft.com/fwlink/?LinkID=309563

ASP.NET Web Frameworks and Tools 2013   5.2.21010.0
For additional information, visit http://www.asp.net/

Color Theme Designer   1.0
Designer for creating new color themes

Common Azure Tools   1.3
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

GhostDoc   4.9.14093.0
GhostDoc automatically generates XML documentation comments.

JetBrains ReSharper 8.2   Full Edition build 8.2.0.2160 on 2014-03-20T18:53:08
JetBrains ReSharper 8.2 package for Microsoft Visual Studio. For more information about ReSharper, visit http://www.jetbrains.com/resharper/. Copyright © 2003–2015 JetBrains, Inc.

Microsoft Azure HDInsight HQL Service   1.0.0000.0
Language service for Hive query

Microsoft Azure HDInsight Tools for Visual Studio   1.0.0000.0
An integrated development environment for HDInsight application development.

Microsoft Azure Mobile Services Tools   1.3
Microsoft Azure Mobile Services Tools

Microsoft Azure Tools   2.5
Microsoft Azure Tools for Microsoft Visual Studio 2013 - v2.5.21104.1601

Microsoft Team Foundation Server 2013 Power Tools   12.0
Power Tools that extend the Team Foundation Server integration with Visual Studio.

Microsoft Visual Studio Process Editor   1.0
Process Editor for Microsoft Visual Studio Team Foundation Server

NuGet Package Manager   2.8.50926.663
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

Office Developer Tools for Visual Studio 2013 ENU   12.0.30626
Microsoft Office Developer Tools for Visual Studio 2013 ENU

PowerShell Tools   1.3
Provides file classification services using PowerShell

PreEmptive Analytics Visualizer   1.2
Microsoft Visual Studio extension to visualize aggregated summaries from the PreEmptive Analytics product.

Release Management for Visual Studio Package   1.0
Release Management for Visual Studio

SAPReferenceManager   1.0
Manages References to Shared Projects

SQL Server Data Tools   12.0.41012.0
Microsoft SQL Server Data Tools

TFS Source Control Explorer Extension   1.0
Visual Studio Extension for Team Foundation Server Source Control Explorer

Windows Azure Tools   2.3
Windows Azure Tools for Microsoft Visual Studio 2013 - v2.3.20320.1602

Windows Phone 8.1 SDK Integration   1.0
This package integrates the tools for the Windows Phone 8.1 SDK into the menus and controls of Visual Studio.

Workflow Manager Tools 1.0   1.0
This package contains the necessary Visual Studio integration components for Workflow Manager.

Xamarin   3.11.666.0 (ebae43a)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin.Android   5.1.4.16 (5f55a9ef61c11b6ce0890bc91e4c71b1b92be214)
Visual Studio plugin to enable development for Xamarin.Android.

Xamarin.Forms Intellisense   1.0
Provides intellisense for Xamarin.Forms in the XML editor.

Xamarin.iOS   8.10.2.0 (67b390d0d1bd741582cf7b7fd3ffea08583a3f83)
Visual Studio extension to enable development for Xamarin.iOS.

Xamarin.iOS Unified Migration   1.0
Automated migration for Xamarin iOS Classic projects to Unified

Xamarin.TestCloud.Integration   1.0
Early preview of Xamarin Test Cloud integration
Comment 5 Jonathan Pryor 2015-07-10 12:11:54 UTC
A complete, *textual*, stack trace of the error would always be appreciated.

As would a working sample; Attachment #11972 [details] can't find SQLite.

Fortunately the forums thread has a repro.

Please, when investigating any exception, don't use Exception.Message (as you do in MainActivity.CallWhatIWantToBreak()). Use Exception.ToString(). The stack trace is tremendously useful and important.

When I run the repro on the thread, it fails for me, but not with a TypeIinitializationException:

> 07-10 11:58:12.047 13391 13391 E SAMPLE APP Error: Could not find file "/storage/emulated/0/ShapeFile/roads.dbf"

Using Exception.ToString() is far more useful:

> SAMPLE APP Error: System.IO.FileNotFoundException: Could not find file "/storage/emulated/0/ShapeFile/roads.dbf"
> SAMPLE APP Error:   at NetTopologySuite.IO.DbaseFileReader..ctor (System.String filename) [0x00000] in <filename unknown>:0 
> SAMPLE APP Error:   at NetTopologySuite.IO.ShapefileDataReader..ctor (System.String filename, IGeometryFactory geometryFactory) [0x00000] in <filename unknown>:0 
> SAMPLE APP Error:   at AndroidClassLib.ShapeFileManager.LoadShapeFile (System.String shapeFileName) [0x00000] in <filename unknown>:0 
> SAMPLE APP Error:   at Compass.Tessera.Core.TileGenerator.Setup (System.String basePath, System.String shapeFile, Boolean force) [0x00000] in <filename unknown>:0 
> SAMPLE APP Error:   at SampleApp.MainActivity.CallWhatIWantToBreak () [0x00000] in <filename unknown>:0 

I assume there's some extra steps that must be taken to install roads.dbf?

Additionally, I see that you're explicitly referencing /storage paths:

TileGenerator.cs:
> shapeFileManager.LoadShapeFile("/storage/emulated/0/ShapeFile/roads.shp");

Don't Do That™. The number after "emulated" is the user id (Android has multiple user support), so using "emulated/0" will prevent all additional users from running the app properly.

Please use the proper APIs, e.g. Context.GetExternalFilesDir().

Finally, what device are you running this on? The forum thread's error is that android.app.AppOpsManager can't be found. That type was added in API-19; are you running on an earlier device?
Comment 6 Gerard 2015-07-10 12:33:47 UTC
The shape file should be located in the shape file and placed in a directory that the SampleFileManager.LoadShapeFile reads.

//To replicate the issue you must have the shape file in the correct directory. 

SampleApp/ShapeFile

Sorry for any misunderstanding. 

I ran the app on a genymotion emulator running API- 18, but i've tried this on emulators and tablets higher that API - 19

A textual version of the error

System.TypeInitializationException: An exception was thrown by the type initializer for NetTopologySuite.IO.DbaseFileHeader ---> System.ArgumentNullException: Argument cannot be null.
Parameter name: key
at System.ThrowHelper.ThrowArgumentNullException (ExceptionArgument argument) [0x00000] in <filename unknown>:0 
at System.Collections.Generic.Dictionary`2[System.Text.Encoding,System.Byte].FindEntry (System.Text.Encoding key) [0x00000] in <filename unknown>:0 
 at System.Collections.Generic.Dictionary`2[System.Text.Encoding,System.Byte].ContainsKey (System.Text.Encoding key) [0x00000] in <filename unknown>:0 
at NetTopologySuite.IO.DbaseFileHeader.AddLdidEncodingPair (Byte ldid, System.Text.Encoding encToAdd) [0x00000] in <filename unknown>:0 
at NetTopologySuite.IO.DbaseFileHeader.AddLdidEncodingPair (Byte ldid, Int32 codePage) [0x00000] in <filename unknown>:0 
at NetTopologySuite.IO.DbaseFileHeader..cctor () [0x00000] in <filename unknown>:0 
 --- End of inner exception stack trace ---
at NetTopologySuite.IO.DbaseFileReader.GetHeader () [0x00000] in <filename unknown>:0 
at NetTopologySuite.IO.ShapefileDataReader..ctor (System.String filename, IGeometryFactory geometryFactory) [0x00000] in <filename unknown>:0 
at AndroidClassLib.ShapeFileManager.LoadShapeFile (System.String shapeFileName) [0x00000] in <filename unknown>:0
Comment 7 Rajneesh Kumar 2015-07-13 09:05:50 UTC
@ Gerard Thanks a lot for providing the sample application.

I have checked this issue with the sample provided in comment 1. I observed that I am getting different exception but not that one that is described in bug description.

Screencast: http://www.screencast.com/t/zpidHehb

Please let me know that is this the same behavior you are facing at your end or still I am missing something to reproduce this issue.? 

Thanks..!

Build Output:https://gist.githubusercontent.com/Rajneesh360Logica/bfde3c5f37415f7905fa/raw/gistfile1.txt
Exception Details(Android device monitor): 
https://gist.github.com/Rajneesh360Logica/9d29a7164e634f04f30d

Environment Info:
Microsoft Visual Studio Professional 2013
Version 12.0.31101.00 Update 4
Microsoft .NET Framework
Version 4.5.50938

Installed Version: Professional

LightSwitch for Visual Studio 2013   06177-004-0446016-02381
Microsoft LightSwitch for Visual Studio 2013

Team Explorer for Visual Studio 2013   06177-004-0446016-02381
Microsoft Team Explorer for Visual Studio 2013

Visual Basic 2013   06177-004-0446016-02381
Microsoft Visual Basic 2013

Visual C# 2013   06177-004-0446016-02381
Microsoft Visual C# 2013

Visual C++ 2013   06177-004-0446016-02381
Microsoft Visual C++ 2013

Visual F# 2013   06177-004-0446016-02381
Microsoft Visual F# 2013

Visual Studio 2013 Code Analysis Spell Checker   06177-004-0446016-02381
Microsoft® Visual Studio® 2013 Code Analysis Spell Checker

Portions of International CorrectSpell™ spelling correction system © 1993 by Lernout & Hauspie Speech Products N.V. All rights reserved.

The American Heritage® Dictionary of the English Language, Third Edition Copyright © 1992 Houghton Mifflin Company. Electronic version licensed from Lernout & Hauspie Speech Products N.V. All rights reserved.

Windows Phone SDK 8.0 - ENU   06177-004-0446016-02381
Windows Phone SDK 8.0 - ENU

Application Insights Tools for Visual Studio Package   1.0
Application Insights Tools for Visual Studio

ASP.NET and Web Tools   12.4.51016.0
Microsoft Web Developer Tools contains the following components:
Support for creating and opening ASP.NET web projects
Browser Link: A communication channel between Visual Studio and browsers
Editor extensions for HTML, CSS, and JavaScript
Page Inspector: Inspection tool for ASP.NET web projects
Scaffolding: A framework for building and running code generators
Server Explorer extensions for Microsoft Azure Websites
Web publishing: Extensions for publishing ASP.NET web projects to hosting providers, on-premises servers, or Microsoft Azure

ASP.NET Web Frameworks and Tools 2012.2   4.1.21001.0
For additional information, visit http://go.microsoft.com/fwlink/?LinkID=309563

ASP.NET Web Frameworks and Tools 2013   5.2.21010.0
For additional information, visit http://www.asp.net/

Common Azure Tools   1.3
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Microsoft Advertising SDK for Windows Phone   
Microsoft Advertising SDK for Windows Phone
Build 

Microsoft Azure Mobile Services Tools   1.3
Microsoft Azure Mobile Services Tools

NuGet Package Manager   2.8.50926.663
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

Office Developer Tools for Visual Studio 2013 ENU   12.0.30626
Microsoft Office Developer Tools for Visual Studio 2013 ENU

PowerShell Tools   1.3
Provides file classification services using PowerShell

PreEmptive Analytics Visualizer   1.2
Microsoft Visual Studio extension to visualize aggregated summaries from the PreEmptive Analytics product.

SQL Server Data Tools   12.0.41012.0
Microsoft SQL Server Data Tools

Windows Phone 8.1 SDK Integration   1.0
This package integrates the tools for the Windows Phone 8.1 SDK into the menus and controls of Visual Studio.

Workflow Manager Tools 1.0   1.0
This package contains the necessary Visual Studio integration components for Workflow Manager.

Xamarin   3.11.666.0 (ebae43a)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin.Android   5.1.4.16 (5f55a9ef61c11b6ce0890bc91e4c71b1b92be214)
Visual Studio plugin to enable development for Xamarin.Android.

Xamarin.Forms Intellisense   1.0
Provides intellisense for Xamarin.Forms in the XML editor.

Xamarin.iOS   8.10.2.0 (67b390d0d1bd741582cf7b7fd3ffea08583a3f83)
Visual Studio extension to enable development for Xamarin.iOS.

Xamarin.iOS Unified Migration   1.0
Automated migration for Xamarin iOS Classic projects to Unified

Xamarin.TestCloud.Integration   1.0
Early preview of Xamarin Test Cloud integration
Comment 8 Gerard 2015-07-13 10:04:15 UTC
@ Rajneesh

I haven't experienced that issue before. The exception is only thrown in the ShapeFileManager in the AndroidClassLib project. line 56. I catch it on line 104 and its logged. so in log cat the tag should be "Gerard Error".
Comment 9 Jonathan Pryor 2015-07-14 14:13:35 UTC
(Formatting for legibility)

> A textual version of the error
> 
>   System.TypeInitializationException: An exception was thrown by the type initializer for NetTopologySuite.IO.DbaseFileHeader --->
>   System.ArgumentNullException: Argument cannot be null.
>   Parameter name: key
>      at System.ThrowHelper.ThrowArgumentNullException (ExceptionArgument argument) [0x00000] in <filename unknown>:0 
>      at System.Collections.Generic.Dictionary`2[System.Text.Encoding,System.Byte].FindEntry(System.Text.Encoding key) [0x00000] in <filename unknown>:0 
>      at System.Collections.Generic.Dictionary`2[System.Text.Encoding,System.Byte].ContainsKey(System.Text.Encoding key) [0x00000] in <filename unknown>:0 
>      at NetTopologySuite.IO.DbaseFileHeader.AddLdidEncodingPair (Byte ldid, System.Text.Encoding encToAdd) [0x00000] in <filename unknown>:0 
>      at NetTopologySuite.IO.DbaseFileHeader.AddLdidEncodingPair (Byte ldid, Int32 codePage) [0x00000] in <filename unknown>:0 
>      at NetTopologySuite.IO.DbaseFileHeader..cctor () [0x00000] in <filename unknown>:0 
>      --- End of inner exception stack trace ---
>      at NetTopologySuite.IO.DbaseFileReader.GetHeader () [0x00000] in <filename unknown>:0 
>      at NetTopologySuite.IO.ShapefileDataReader..ctor (System.String filename, IGeometryFactory geometryFactory) [0x00000] in <filename unknown>:0 
>      at AndroidClassLib.ShapeFileManager.LoadShapeFile (System.String shapeFileName) [0x00000] in <filename unknown>:0

Thank you for the stack trace.

As per the stack trace, you're getting a TypeInitializationException because a "something" invokes ShapeFileManager.LoadShapeFile(), which creates a ShapefileDataReader instance, which hits the DbaseFileHeader static constructor, which eventually attempts to add a null key to a Dictionary.

Dictionary<TKey, TValue>.Add() doesn't like null key values, so it throws, which causes the static constructor to throw, which causes the TypeInitializationException.

Why is the DbaseFileHeader static constructor failing on Release builds but not Debug builds?

Look at the Dictionary type:

> System.Collections.Generic.Dictionary`2[System.Text.Encoding,System.Byte]

It's using System.Text.Encoding as a dictionary key.

This implies that the type requires an Encoding instance that Release apps don't have:

http://developer.xamarin.com/guides/android/under_the_hood/build_process/#Internationalization_Support

You could include all supported internationalization assemblies (see above), or you can determine which Encodings the DbaseFileHeader type requires and ensure that it is available.
Comment 10 Gerard 2015-07-15 07:52:53 UTC
@ Jonathan thanks, including all encodings fixed the problem. I'm not sure why this changed from Xamarin Android version 3.9.547 as i have always just included the West encoding. Any ways, its resolved. Thanks a mil for your help

With the linker turned on it was still causing issues so i had to include the supported encodings in the skip liking process 

I18N.CJK;I18N.MidEast;I18N.Other;I18N.Rare;I18N.West;I18N;

Thanks
Comment 11 Radek Doulik 2015-07-15 11:07:18 UTC
I will look into why it doesn't work anymore.
Comment 12 Dominic N [MSFT] 2015-07-16 14:26:38 UTC
*** Bug 31468 has been marked as a duplicate of this bug. ***
Comment 13 Radek Doulik 2015-07-21 07:40:06 UTC
I tried to replicate it, but it seems to run OK, so it is presumably already fixed.