3

I'm going to create a student information system based on a tutorial. As soon as a user wants to add a new student to the database the following exception occurs.

I tried to learn something about TypeInitializationException and I understand a little by its name.. but I can't get it totally. Besides, the exception is absent from the tutorial I'm following.. I'm new in this type of OOP programming and handling errors. I included my database connection and database access class below..

exception pic

My DB_Connection class

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace studentInformationSystem
{
    class DB_Connection
    {
        public static SqlConnection NewConnection;
        public static string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

        public static SqlConnection getConnection()
        {
            NewConnection = new SqlConnection(ConString);
            return NewConnection;
        }
    }
}

My DB_Access class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace studentInformationSystem
{
    class DB_Access
    {
        public SqlConnection conn;
        public DB_Access()
        {
            conn = DB_Connection.getConnection();
        }

        public void AddStudent(string regNo, string fName, string lName, string phoneNumber)
        {
            if(conn.State.ToString() == "Closed")
            {
                conn.Open();
            }

            SqlCommand newCommand = conn.CreateCommand();
            newCommand.Connection = conn; //why we use it..???
            newCommand.CommandType = CommandType.Text;
            newCommand.CommandText = "insert into student values('" + regNo + "','" + fName + "','" + lName + "','" + phoneNumber + "')";
            newCommand.ExecuteNonQuery();

        }
    }
}

here is my connectionString

  <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

  <configSections>

    <connectionStrings>
      <add name="ConString" connectionString="Data Source=SADID-PC\SQLEXPRESS;Initial Catalog=Test1;Integrated Security=True" 
           providerName="System.Data.sqlClient" />  
    </connectionStrings>

  </configSections>

</configuration>
7
  • 1
    You should have a look at the exception details and possibly the inner exception to better understand what went wrong. Commented Sep 19, 2013 at 11:56
  • Show us the connection string. And is that Comic Sans you're using on that form? :) Commented Sep 19, 2013 at 11:57
  • 3
    Better remove those pictures, be specific. There is nothing to do with first 2 images. Commented Sep 19, 2013 at 11:58
  • 1
    Show your connection string from config file Commented Sep 19, 2013 at 12:26
  • It is visible in your screenshot from the IntelliTrace trace. Your app.exe.config file is screwed up. Commented Sep 19, 2013 at 14:13

4 Answers 4

8

In your case:

This means that the following line fails:

public static string ConString = 
    ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

Make sure that no exception happens here! Since this line is executed as part of DB_Connection's type initialization, the exception occurs when you first access DB_Connection, which happens at DB_Connection.getConnection() - since you have no other (critical) initialization logic for DB_Connection, it basically has to be that line.

I strongly recommend moving logic like initializing ConString to a method (something like Init), so you will have more control about what happens - and much easier debugging!

Going from there, I guess ConnectionStrings["ConString"] returns null or throws an exception itself - but you will find that out easily. ;)

More general description, for people having similar problems:

Whenever TypeInitializationException is thrown, check all initialization logic of the type you are referring to for the first time in the statement where the exception is thrown.

Initialization logic includes: the type's static constructor and (like in this case) field initialization.

If at this point you still have no idea where the actual exception (that then triggers TypeInitializationException) happens, you should consider moving all (or parts of your) initialization logic to an extra static method. When you now call this method manually (before you first access the type, of course) you can benefit from your IDEs debugging abilities and will, most importantly, get the actual exception thrown at your head.

Sign up to request clarification or add additional context in comments.

Comments

3

It seems that your connection string is not valid. I don't know what's in your app.config file.

One way to do this is given bellow.

app.config

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="XYZ" 
    connectionString="Data Source=.;Initial Catalog=NameOfYourDb;Integrated Security=True"/>
  </connectionStrings>
</configuration>

Then ........

var connection = 
    System.Configuration.ConfigurationManager.ConnectionStrings["XYZ"];

And don't forget to give a reference to System.Configuration.dll

Comments

1

Assuming all that's going on is that your getConnection is creating a new Sql connection with the connection string you're holding in a dictionary. I'd guess it could be either:

  • ConString is invalid in some way
  • Your database isn't active

I'd use the debugger to check the value of ConString when the exception is thrown (check the 'locals' tab at the bottom). If you're convince that it is correct I'd guess that your Sql database isn't running or is somehow invalid. However, I don't have enough experience to say how to diagnose that.

5 Comments

all that should trigger different kinds of exception ;) but very good debugging suggestions!
@olydis actually all this problems will raise a TypeInitializationException since all of this would happen either in a static field initialization or in a static constructor
nope, NOTHING else happens during type initialization, notice that for example if ConString is invalid or something, this would result in an exception inside getConnection - there is NO static constructor for DB_Connection, so no, nothing else happens during initialization than the field init ;)
@olydis oups sorry I misread the code (thought the getConnection function was a static constructor), yep you're right
hehehe no worries, that is exactly what I first thought reading through his code - when I was already working on my answer I suddenly realized I was talking about a constructor that actually was a method :)
0

App.config file parameters are wrong If you provide like this it will work : I have tried and it got executed correctly :)

<?xml version="1.0"?>
<configuration>
  <configSections>
  </configSections>
    <connectionStrings>
      <add name ="ConString" connectionString="Data Source=SADA-PC;Initial Catalog=StudentTest;Integrated Security=True"
           providerName ="System.Data.sqlClient"/>
    </connectionStrings>
</configuration>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.