235

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
  • 28,342
  • 21
  • 95
  • 123
gofor.net
  • 3,850
  • 10
  • 37
  • 64

22 Answers22

373

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

Fredrik Mörk
  • 147,210
  • 26
  • 277
  • 333
  • 4
    thanks Fredrik Mörk i got the inner exception "Object reference not set to an instance of an object." i am checking for it – gofor.net Dec 09 '10 at 12:59
  • 2
    @gofor.net: as @Jackson Pope points out; the interesting part of your code is the method `static CSDetails` in the class `CSMessageUtility.CSDetails` (and any methods it may call). If you don't find the problem on your own, update the question with that code. – Fredrik Mörk Dec 09 '10 at 13:01
  • actually CSMessageUtility is dll reference i am using and this contains the several methodes. but when i check those methods manually i didn't get any error.it works perfectly – gofor.net Dec 09 '10 at 13:48
  • 2
    The exception isn't always valid or pointing to the right issue. For me, it tried to tell me `The input is not a valid Base-64 string as it contains a non-base 64 character` for what a function was returning to a DataTable object, but for me, there was actually an underlying issue where I was calling an `app.config` parameter by the wrong name, so a variable I was using to form my connectionstring was null. Therefore it couldn't open the `OracleConnection` in that function in order to return the DataTable. Best advice is to dive down into the underlying function that is returning the error. – vapcguy Aug 11 '16 at 19:37
199

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
  • 15,232
  • 5
  • 47
  • 95
Muhammad Waqas Iqbal
  • 3,014
  • 1
  • 16
  • 9
  • 25
    Man I would of never found that out on my own. I was relying too heavily on point breaks and, alas, they would not have saved me. Thanks bud! +1 – Lukas Apr 16 '13 at 20:34
  • 8
    I agree . . . I just had the exact same thing happen. Was pulling my hair out trying to figure it out. Many thanks! – dscarr Mar 25 '15 at 15:29
  • A good way to detect is to instantiate your static type within a static constructor, and within the constructor wrap in a try / catch block. Most the details get lost when just initializing the static property outside of a constructor. – cchamberlain Mar 25 '16 at 18:13
  • 3
    it was connection string in my case. – Musakkhir Sayyed May 04 '16 at 09:08
  • 2
    You rock man! you are a savior! The referenced project was not even debugging (stepping into) without the missing config entry. There was no clue to relate to the issue with config without steeping into that code. You saved my week after I wasted 2 days :P! – Pramod Sharma Jun 23 '16 at 10:38
  • 1
    @MuhammadWaqasIqbal That last bolded sentence is the key!!! ANY function that uses `ClientID` in this example would have this error. Great post. – vapcguy Aug 11 '16 at 19:39
  • 1
    had a typo in my app.config that I would have never noticed if not for this post. – Brian Jan 30 '17 at 00:30
  • 1
    This is actually my second time finding this page and troubleshooting this error. Apparently I never learn. I noticed this time, ANY function in the class having ANY `ConfigurationManager.AppSettings` call to ANY variable that does not exist in the web.config will cause this error - not just variables at the top of the page that do these calls. This was ridiculous to troubleshoot, as I was honing in on one function in the class, but it was really ANOTHER function that had a `ConfigurationManager.AppSettings` variable that didn't exist in the web.config! So ridiculous... – vapcguy Mar 28 '17 at 15:58
  • 1
    man. this one saved me about a year ago and here I did it again. a simple type in the app.config. I need to bookmark this one – Brian Aug 10 '17 at 06:13
  • 1
    It works for me. There was issue in reading app.config settings – Sohel Pathan Sep 06 '17 at 12:28
  • 1
    That was my case. I've been struggling for 3 hours to find where did the error come from, and the problem was a missing appSetting key in my project app.config. Thanks man! – Otman IGHOULASSEN May 31 '18 at 10:56
  • 1
    thanks, by handling static connection string , this error solved. – Saleem Kalro Jul 26 '18 at 16:02
  • My case, the static class with the static function I was calling had a private static string referencing ConfigurationManager.ConnectionStrings["my-key-name-here"].ConnectionString - which is not in the current web.config - because copied from another project. – qxotk Jun 26 '19 at 16:05
  • Thanks This is Very use full to resolve the issue . i spend more than 2 hrs .. on this Error . – Gupta Aug 19 '20 at 17:07
  • That is basically what it was for me. I saw this answer earlier and thought... I'm not using config settings. Then I realized you were referring to any variable assignment. Bang! Problem solved. Thanks. – Scooter Oct 20 '20 at 21:15
61

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.

Jackson Pope
  • 13,897
  • 6
  • 52
  • 80
  • 1
    Sure enough. I was creating a static instance of log4net logger that was causing the problem. The problem was the version of the log4net assembly in that project didn't match the version in the other projects (which I just noticed shivan specifically pointed out.) – goku_da_master May 12 '16 at 16:11
  • 1
    I had the same issue using NLog. I tend to initialize my loggers in static constructors and the mismatch between versions in differents projects caused the issue. using the same version everywhere solved the issue. – shelbypereira Oct 25 '16 at 14:42
5

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
  • 3,776
  • 3
  • 24
  • 44
Tharaka
  • 2,205
  • 1
  • 18
  • 21
3

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
  • 28,342
  • 21
  • 95
  • 123
sharad shrestha
  • 193
  • 2
  • 7
3

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

[ConfigurationProperty("TransferTimeValidity")]
Neuron
  • 3,776
  • 3
  • 24
  • 44
Tim
  • 463
  • 2
  • 8
3

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
  • 3,776
  • 3
  • 24
  • 44
Adam Caviness
  • 3,255
  • 30
  • 36
2

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 Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

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

David
  • 176,566
  • 33
  • 178
  • 245
2

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"},
        };
Abdulrazzaq Alzayed
  • 1,437
  • 1
  • 10
  • 15
1

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
  • 28,342
  • 21
  • 95
  • 123
Dean
  • 11
  • 1
1

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
  • 1,666
  • 3
  • 22
  • 27
TylerBUrquhart
  • 187
  • 2
  • 11
1

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

ShivanandSK
  • 629
  • 6
  • 13
1

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.

zak
  • 300
  • 2
  • 16
0

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.

live-love
  • 34,372
  • 16
  • 163
  • 152
0

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.

vapcguy
  • 5,607
  • 1
  • 45
  • 43
0

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
  • 1,629
  • 1
  • 26
  • 30
Gopi P
  • 381
  • 5
  • 15
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
Adam Cox
  • 2,423
  • 1
  • 22
  • 33
0

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.

Ray
  • 1
0

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\"

0

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:\Projects\My.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:\Projects\Blah.blah.blah\Program.cs:line 29 Exception caught.
Ivan
  • 3,463
  • 28
  • 26
0

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

Kirsten Greed
  • 11,170
  • 26
  • 117
  • 234
0

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.

Battle
  • 651
  • 10
  • 12