The type initializer for threw an exception как исправить

The following is my Windows service code. When I am debugging the code, I am getting the error/ exception:

The type initializer for ‘CSMessageUtility.CSDetails’ threw an exception.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using CSMessageUtility;

namespace CS_Data_Trasmmiting_Service
{
    public partial class svcCSWinServ : ServiceBase
    {
        //private string sLogFormat;
        //private string sErrorTime;
        private Thread new_thread;
        Logger logObject = new Logger();
        private bool isenable = true;

        public svcCSWinServ()
        {
            InitializeComponent();
            logObject.append("Initialize Service " + DateTime.Now.ToString(), 70);
            CheckForAlarms();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                new_thread = new Thread(new ThreadStart(CheckForAlarms));
                new_thread.Start();
            }
            catch
            {
            }

            logObject.append("Service Started successfully " + DateTime.Now.ToString(), 70);
        }

        protected override void OnStop()
        {
            try
            {
                isenable = false;
                new_thread.Abort();
            }
            catch
            {

            }
            logObject.append("Service Stopped successfully " + DateTime.Now.ToString(), 70);
        }


        void CheckForAlarms()
        {
            try
            {
                while (true)
                {
                    //if((DateTime.Now.ToString("HH:mm") == "18:00"))
                    //{

                        logObject.append("Start Sending Data " +DateTime.Now.ToString(), 70);
                        try
                        {
                            //SendAllInfo();
                            string str = CSMessageUtility.CSDetails.createDHSMessageFormat();
                            Thread.Sleep(2000);
                            string str1 = CSMessageUtility.CSDetails.createEALMessageFormat();
                            Thread.Sleep(2000);
                            string str2 = CSMessageUtility.CSDetails.createProductStatusMessageForamt();
                            Thread.Sleep(2000);
                            string str3 = CSMessageUtility.CSDetails.createEODMessageFormat();
                            Thread.Sleep(2000);
                            string str4 = CSDetails.createProductReceiptEntryatBOSMessageFormat();
                            Thread.Sleep(2000);
                            string str5 = CSMessageUtility.CSDetails.createProductSaleMessageFormat();
                            Thread.Sleep(2000);
                            string str6 = CSMessageUtility.CSDetails.createTotalizerExceptionMessageFormat();
                            Thread.Sleep(2000);
                            //CSMessageUtility.CSDetails.createDailyCOtransferMessageFormat();
                            //Thread.Sleep(2000);

                        }
                        catch (Exception ee)
                        {
                            logObject.append(ee.Message, 70);
                        }
                        logObject.append("Finished Sending Data " +DateTime.Now.ToString(), 70);
                        Thread.Sleep(3000);
                    //}
                    //Thread.Sleep(20000);
                }
            }
            catch (Exception ex)
            {
                logObject.append("Thread Exception: "+ ex.Message + " "+ DateTime.Now.ToString(), 70);

                try
                {
                    new_thread.Abort();
                }
                catch (Exception ex1)
                {
                    logObject.append("Thread Exception: " +ex1.Message + " " + DateTime.Now.ToString(), 70);
                }

                if (isenable == true)
                {
                    new_thread = new Thread(new ThreadStart(CheckForAlarms));
                    new_thread.Start();
                }
            }
        }
    }
}

Peter Mortensen's user avatar

asked Dec 9, 2010 at 12:46

gofor.net's user avatar

2

Check the InnerException property of the TypeInitializationException; it is likely to contain information about the underlying problem, and exactly where it occurred.

answered Dec 9, 2010 at 12:51

Fredrik Mörk's user avatar

Fredrik MörkFredrik Mörk

155k29 gold badges290 silver badges343 bronze badges

4

This problem can be caused if a class tries to get value of a key in web.config or app.config which is not present there.

e.g.
The class has a static variable

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

But the web.config doesn’t contain the GoogleCalendarApplicationClientID key

The error will be thrown on any static function call or any class instance creation

shA.t's user avatar

shA.t

16.5k5 gold badges54 silver badges111 bronze badges

answered Mar 1, 2013 at 6:44

Muhammad Waqas Iqbal's user avatar

16

The type initializer for 'CSMessageUtility.CSDetails' threw an exception. means that the static constructor on that class threw an Exception — so you need to look either in the static constructor of the CSDetails class, or in the initialisation of any static members of that class.

answered Dec 9, 2010 at 12:50

Jackson Pope's user avatar

Jackson PopeJackson Pope

14.5k6 gold badges56 silver badges80 bronze badges

2

I ran into the same problem, when I was using a static methods in a Util class, just like you had used CSMessageUtility.CSDetails.

The problem was that during the static initialization of the class (using the static constructor), the framework also initialize the the static variables (fields) in the class. I had a static variable that attempts to read values from app.config, and app.config was missing the respective settings, thus resulting in an un-handled exception. This resulted in getting the

«Object reference not set to an instance of an object.»

as the inner exception.

Neuron's user avatar

Neuron

5,0035 gold badges38 silver badges57 bronze badges

answered Aug 20, 2013 at 7:43

Tharaka's user avatar

TharakaTharaka

2,3351 gold badge20 silver badges22 bronze badges

Dictionary keys should be unique !

In my case, I was using a Dictionary, and I found two items in it have accidentally the same key.

Dictionary<string, string> myDictionary = new Dictionary<string, string>() {
            {"KEY1", "V1"},
            {"KEY1", "V2" },
            {"KEY3", "V3"},
        };

answered Dec 3, 2019 at 4:16

Abdulrazzaq Alzayed's user avatar

One other thing to check when these initialize errors are thrown would be to check if the target .NET version is installed on the server. You can right click the project and see what .NET version the application is targeting.

Peter Mortensen's user avatar

answered Feb 17, 2015 at 18:17

sharad shrestha's user avatar

This can happen if you have a dependency property that is registered to the wrong owner type (ownerType argument).

Notice SomeOtherControl should have been YourControl.

public partial class YourControl
{
    public bool Enabled
    {
        get { return (bool)GetValue(EnabledProperty);   }
        set { SetValue(EnabledProperty, value); }
    }
    public static readonly DependencyProperty EnabledProperty =
        DependencyProperty.Register(nameof(Enabled), typeof(bool), typeof(SomeOtherControl), new PropertyMetadata(false));
}

Neuron's user avatar

Neuron

5,0035 gold badges38 silver badges57 bronze badges

answered Aug 24, 2016 at 15:22

Adam Caviness's user avatar

0

I’ve had the same problem caused by having two of the same configuration properties (which matches the app.config):

[ConfigurationProperty("TransferTimeValidity")]

Neuron's user avatar

Neuron

5,0035 gold badges38 silver badges57 bronze badges

answered May 11, 2015 at 22:53

Tim's user avatar

TimTim

4834 silver badges9 bronze badges

Another scenario that might cause this is when you have a piece of your code that calls:

string sParam = **ConfigurationManager.AppSettings["SOME_PARAM"].ToString();

Keep in mind that you have to use the OWSTIMER.EXE.CONFIG file for configuration file settings. I had an App.config file that I was trying to read and I was getting this error because on instantiation of my job instance, I had a line in my code that was referring to Connfiguration.AppSettings & Configuration.ConnectionStrings. Just make sure that you go the path:

C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14BIN

and place your configuration settings in the OWSTIMER.EXE.CONFIG file.

David's user avatar

David

205k36 gold badges196 silver badges274 bronze badges

answered May 16, 2014 at 12:49

lionel jones's user avatar

If for whatever reason the power goes or the Visual Studio IDE crashes it can cause this problem inside your bin/debug bin/release…

Just delete the content and recompile (from personal experience when my toe hit the reset button!)

Peter Mortensen's user avatar

answered Jun 16, 2013 at 7:24

Dean's user avatar

I had a different but still related configuration.

Could be a custom configuration section that hasn’t been declared in configSections.

Just declare the section and the error should resolve itself.

Slyvain's user avatar

Slyvain

1,7323 gold badges22 silver badges27 bronze badges

answered Sep 21, 2015 at 11:58

TylerBUrquhart's user avatar

I encountered this issue due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly

answered May 5, 2016 at 12:54

ShivanandSK's user avatar

ShivanandSKShivanandSK

6496 silver badges13 bronze badges

As the Error says the initialization of the Type/Class failed. This usually occurs when there is some exception in the constructor of the class. Most common reason is you assign some value in the constructor reading from a config file and the config file is missing those values.

answered Jun 29, 2019 at 14:33

zak's user avatar

zakzak

3103 silver badges19 bronze badges

Noteworthy: I had multiple projects in my solution and I forgot to add the references/Nuget libraries. When I ran a method in the static class, which used the given libraries, it threw the exception mentioned.

answered Apr 1, 2020 at 11:13

Battle's user avatar

BattleBattle

76610 silver badges17 bronze badges

In my case I had this failing on Logger.Create inside a class library that was being used by my main (console) app. The problem was I had forgotten to add a reference to NLog.dll in my console app. Adding the reference with the correct .NET Framework library version fixed the problem.

answered Oct 30, 2015 at 16:25

live-love's user avatar

live-lovelive-love

47.6k22 gold badges234 silver badges201 bronze badges

Had a case like this in a WPF project. My issue was on a line that went like this:

DataTable myTable = FillTable(strMySqlQuery);

Where FillTable() returned a DataTable based on a SQL query string. If I did the «copy exception to clipboard» option, I think it was, and pasted into Notepad, I could see the message. For me, it was The input is not a valid Base-64 string as it contains a non-base 64 character.

My actual problem wasn’t that the query string had something that shouldn’t be there, like I was thinking, because string strMySqlQuery = "SELECT * FROM My_Table" was my string and thought it could be the * or _, but the actual problem was in FillTable(), where I had a call to another function, GetConnection() that returned an OracleConnection object, in order to open it and retrieve and return the DataTable. Inside GetConnection() I was getting the app.config parameters for my connection string, and I had one of them misnamed, so it was setting a null value for the service account’s password and not making the DB connection. So it’s not always where the error is exactly correct for all circumstances. Best to dive into the function where the error is and debug step-by-step and ensure all values are getting filled with what you expect.

answered Aug 11, 2016 at 19:32

vapcguy's user avatar

vapcguyvapcguy

7,0031 gold badge55 silver badges49 bronze badges

I too faced this error in two situation

  1. While performing redirection from BAL layer to DAL layer I faced this exception. Inner exception says that «Object Reference error».

  2. Web.Config file key does not match.

Hope this useful to solve your problem.

Sven 31415's user avatar

Sven 31415

1,7451 gold badge25 silver badges32 bronze badges

answered Aug 13, 2017 at 14:31

Gopi P's user avatar

Gopi PGopi P

5179 silver badges19 bronze badges

0

Similar to what Muhammad Iqbal stated.. I was in a VB.NET (may also be C#) project where I did remove a key-value pair from the App.config which was referenced by a variable global to the Sub Main() of Module Main. Therefore, the exception (and break) occurs in Module Main before the Sub Main(). If only I had a break-point on the Dim, but we don’t usually break on global variables. Perhaps a good reason not to declare globals referencing App.config? In other words, this…

An unhandled exception of type ‘System.TypeInitializationException’ occurred in Unknown Module.
The type initializer for ‘Namespace.Main’ threw an exception.

Is caused by…

App.config

<connectionStrings>
    <!--<add name="ConnectionString1" connectionString="..." />-->

Main module

Module Main
    Dim cnnString As String = ConfigurationManager.ConnectionStrings("ConnectionString1")  '<-- BREAK HERE (EXCEPTION)

    Sub Main()

        // main code

    End Main
End Module

answered Mar 22, 2018 at 18:48

Adam Cox's user avatar

Adam CoxAdam Cox

3,2611 gold badge34 silver badges45 bronze badges

In my case, I had a helper class that was static. In that class was a method to initialize a SqlCommand dependent on variables. As this was being called in several places I moved it to the helper class and called as needed, so this method was also static. Now I had a global property that was the connection string in Global.asax pointing to the connection string in web.config. Intermittently I would get «The type initializer for ‘Helper’ threw an exception». If I moved the method from the Helper class to the class where it was being called from all was good. The inner exception complained of the object being null (Helper class). What I did was add Using Helper to Global.asax and even though it was not being used by Global.asax this solved the problem.

answered May 8, 2018 at 20:00

Ray's user avatar

My Answer is also related to Config section. If you assign values from Config file at static class of C# or Module.VB of VB, you will get this error at run time.

add key=»LogPath» value=»~/Error_Log/»

Using Forward slash in Web.Config also leads to this error on Run time. I just resolved this issue by putting BackSlash

add key=»LogPath» value=»~Error_Log»

answered Jan 4, 2019 at 13:30

Mohamed Riyas's user avatar

I wrapped my line that was crashing in a try-catch block, printed out the exception, and breaked immediately after it was printed. The exception information shown had a stack trace which pointed me to the file and line of code causing the fault to occur.

enter image description here

System.TypeInitializationException: The type initializer for 'Blah.blah.blah' threw an exception. 
---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Some.Faulty.Software..cctor() in C:ProjectsMy.Faulty.File.cs:line 56
   --- End of inner exception stack trace ---
   at Blah.blah.blah(Blah.blah.blah)
   at TestApplication.Program.Main(String[] args) 
   in C:ProjectsBlah.blah.blahProgram.cs:line 29 Exception caught.

answered Feb 15, 2019 at 11:00

Ivan's user avatar

IvanIvan

4,31336 silver badges27 bronze badges

Somehow exiting Visual Studio and re-opening it solved this for me.

answered Jun 21, 2019 at 22:31

Kirsten's user avatar

KirstenKirsten

15k39 gold badges175 silver badges306 bronze badges

I have a c++/cli project and it’s a windows application. In debug mode we didn’t have any problems but after taking it to release mode this error start up. I searched and found some forum-answers but couldn’t help me solve this problem.
Please help me ….

Error :

An unhandled exception of type ‘System.TypeInitializationException’ occurred in Unknown Module.

Additional information: The type initializer for ‘Module’ threw an exception.

Updated 16-Nov-21 13:06pm


I had the same error and found that the class I was referencing was not the problem, but it had a static variable of another type declared that required another assembly to load. That assembly was built for a target platform of x86 (see Properties—>Build tab) however the main project was compiled for Any CPU. I rebuilt the older assembly for Any CPU… problem solved.

Here are some helpful steps for finding the root cause of this problem…

Click Debug—> Exceptions and check ON all the Thrown checkboxes. This will cause the debugger to stop on all first chance exceptions and will help you find the error under the Type Initializer error that you’re seeing. If it is related to another assembly, as mine was, you can use Microsoft’s Assembly Binding Log Viewer tool to help determine the problem.

Does the machine where the application is running has all the required dlls??

Maybe you are missing some interops in the local directory

I recently had the same problem, and it was because I was using Date.Parse on a missing element in the config file:

Date.Parse(System.Configuration.ConfigurationManager.AppSettings.Get(«frex»))

change your .net framework to lower ;)

In my case (so many different cases where this shows up) I was initializing some static fields in their declaration, like this:

public class MyHelperClass
{
    readonly static SolidColorBrush BlueBrush = new SolidColorBrush(Colors.Blue);
    
    public static void ApplyBrush()
    { 
      
    }
}

When I moved the initialization into a static constructor, the exception was no longer thrown:

public class MyHelperClass
{
  readonly static SolidColorBrush BlueBrush;
  
  static MyHelperClass
  {
    BlueBrush = new SolidColorBrush(Colors.Blue);
  }
}
look the repository container in unity.config
<pre><pre lang="xml">
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <alias type="App.Core.Interfaces.IRepositoryConfiguration, App.Core" alias="IRepositoryConfiguration" />
  <alias type="App.Repository.Mappings.SqlServer.SqlRepositoryConfigurer, App.Repository.Mappings.SqlServer" alias="SqlRepositoryConfigurer" />

  <container name="RepositoryContainer">
    <register type="IRepositoryConfiguration" mapTo="SqlRepositoryConfigurer" >
      <lifetime type="singleton"/>
    </register>
  </container>
</unity>
</pre></pre>

I was making an assignment in a constructor that didn’t have an error handling.

fileInfo = My.Computer.FileSystem.GetFileInfo(logDirLoc & logFileName)
writer = fileInfo.AppendText()

When I removed it the issue was solved.

tip: I looked through the error details and saw that a file couldn’t be found. That was it.

I faced the Same error that is «System.TypeInitializationException». This error is raised due to Static constructor .

Actually in my case i am accessing some value from the App.config and assigning that value in a static variable . The error is because of the App.config file . That means the app.config file is not well formed (I just missed some tag on app.config ). After putting the missing tag it works fine.

The type initializer for ‘Module’ threw an exception.
Just Run IISRESET

I had this problem also, but my solution wasn’t any of these. It was because I had an unmanaged class with a virtual function that returned a managed pointer.

class A
{
    virtual ManagedType^ Foo();
};

Apparently the C++/CLI runtime can’t handle this. Removing the virtual fixed the problem (luckily for me the virtual wasn’t needed in my case).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

This guide will walk you through the process of resolving the ‘Type Initializer for Gdip Threw an Exception’ error commonly encountered in .NET applications that use the System.Drawing namespace. By following the steps in this guide, you’ll be able to identify the cause of the error and implement the appropriate solution.

Table of Contents

  • Understanding the Error
  • Common Causes and Solutions
  • Missing or Incorrectly Installed libgdiplus Library
  • Environment Variable Issues
  • Incorrect Runtime Configuration
  • FAQs

Understanding the Error

The ‘Type Initializer for Gdip Threw an Exception’ error typically occurs during the instantiation of a GDI+ object, such as a Bitmap or Graphics object, in a .NET application. GDI+ is a graphics library used by System.Drawing to provide 2D vector graphics, imaging, and typography functionality.

The error message usually looks like this:

System.TypeInitializationException: The type initializer for 'Gdip' threw an exception.
---> System.DllNotFoundException: Unable to load DLL 'libgdiplus': The specified module could not be found.

This error indicates that there’s an issue with the underlying GDI+ library (libgdiplus on non-Windows platforms) that the .NET application relies on.

Common Causes and Solutions

Missing or Incorrectly Installed libgdiplus Library

One of the most common causes of this error is a missing or improperly installed libgdiplus library, especially on non-Windows platforms such as Linux and macOS.

To fix this issue, follow these steps:

For Linux:

Update your package lists:

sudo apt-get update

Install the libgdiplus package:

sudo apt-get install -y libgdiplus

Install the libc6-dev package (required for some distributions):

sudo apt-get install -y libc6-dev

For macOS:

Install Homebrew if you haven’t already: Homebrew Installation

Install the mono-libgdiplus package:

brew install mono-libgdiplus

After installing the required packages, restart your application and check if the error persists.

Environment Variable Issues

Another possible cause of this error is an incorrect or missing environment variable. Ensure that the LD_LIBRARY_PATH environment variable includes the path to the libgdiplus library.

To set the LD_LIBRARY_PATH variable, follow these steps:

Find the path to the libgdiplus library:

find /usr -name libgdiplus.so

Export the LD_LIBRARY_PATH variable with the path to the libgdiplus library:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/libgdiplus

Restart your application and check if the error persists.

Incorrect Runtime Configuration

If you’re still encountering the error after trying the above solutions, check your application’s runtime configuration. Ensure that you’re using the correct runtime for your application and that all dependencies are properly installed.

FAQs

Q1: Can I use System.Drawing in a cross-platform application?

Yes, you can use System.Drawing in a cross-platform application. However, you’ll need to ensure that the libgdiplus library is installed and configured correctly on each platform.

Q2: Is there an alternative to System.Drawing for cross-platform applications?

Yes, you can use the ImageSharp library as an alternative to System.Drawing for cross-platform applications. ImageSharp is a fully managed, modern, and open-source image processing library.

Q3: How do I know if libgdiplus is installed on my system?

You can use the find command to locate the libgdiplus library on your system:

find /usr -name libgdiplus.so

Q4: Can I use GDI+ in a web application?

While it’s possible to use GDI+ in a web application, it’s not recommended due to potential performance and scalability issues. Instead, consider using an alternative library such as ImageSharp or SkiaSharp.

Q5: What is the difference between GDI+ and libgdiplus?

GDI+ is a Windows-based graphics library used by System.Drawing to provide 2D vector graphics, imaging, and typography functionality. libgdiplus is an open-source implementation of the GDI+ API for non-Windows platforms, such as Linux and macOS.

  • Remove From My Forums
  • Question

  • Hi All

    I have .Net solution with bunch of c++ and c# projects with .In Debug mode the application  is working fine.When I build the solution in release mode and try to run the application I am getting the strange error «The the type initializer  for <Module> threw an excpetion  The C++ Module failed to load during   native initialization».The problem with it is not throwing any error in debug mode,It was happening only in release mode,Can any aware of this problem?

Answers

  • Sounds like your release build isn’t copying all the files it needs to run.  Verify that all the binaries that are needed are in the appropriate directory.  The output directory for debug is different than for release.

    Hope this helps,
    Michael Taylor — 11/23/05

I just dealt with this on a client computer. The problem was that the machine.config files for .NET Framework 4.x had both been corrupted (they had somehow become zero-length files).

Deleting the files is insufficient.

It worked to simply replace the zero length files with the code below, but I used the «known good» versions in order to ensure that there weren’t any long-term side-effects.

This is the minimum required content for the machine.config files:

<?xml version="1.0" encoding="UTF-8"?>
<configuration />

Replacing these two files with «known good» copies of machine.config from the same version resolved this for me and didn’t leave me worrying that some unknown issue would crop up later.

After fixing or replacing the machine.config files a reboot is required.

The Windows machine.config file is located one of the following folders:

%Windows%Microsoft.NETFrameworkv{version}CONFIG
%Windows%Microsoft.NETFramework64v{version}CONFIG

There may also be corrupted machine.config files for individual applications under their *mono{version} folders, though I would be much more hesitant to replace them without using a copy from the same application and application version on the same platform and CPU architecture.

In any case, on Windows, you can find the specific defective files by searching for zero-length files under the Windows folder named machine.config. This command will do that for you.

forfiles /P %windows% /S /M machine.config /C "cmd /c if @isdir==FALSE if @fsize EQU 0 echo @path"

Понравилась статья? Поделить с друзьями:
  • Одна воспитывала сына как исправить ошибки свои
  • Как найти всех монстров в undertale геноцид
  • Как найти любой биом майнкрафт
  • Как найти косинус угла 145
  • Как правильно составить акт об уничтожении документов образец