Reputation: 1985
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..
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>
Upvotes: 3
Views: 3769
Reputation: 1
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>
Upvotes: 0
Reputation: 3320
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.
Upvotes: 8
Reputation: 10422
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
Upvotes: 3
Reputation: 1234
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:
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.
Upvotes: 1