0

My DB Connection dosnt work, can someone please tell me why?

I run this from a unit test in VS 2010. Simple Assert.IsTrue(testDbConnection) and it fails. i'v also tried running it in normal mode as a web application and I get the same exception.

please note the XXXXX are ofcourse done with purpose.

web.config

  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
    <add name="DomainDatabase" connectionString="Data Source=XXXXXXXXXX;Initial Catalog=domain;Persist Security Info=True;User ID=campain_xxx;Password=XXXXXXXXX" providerName="System.Data.SqlClient" />
  </connectionStrings>

My test method

 public bool testDBConnection()
        {
            try
            {
                SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DomainDatabase"].ConnectionString);
                sqlCon.Open();
                sqlCon.Close();

                return true;
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
                return false;
            }

        } 

This gives me the exception

System.NullReferenceException: Object reference not set to an instance of an object.
Marthin
  • 6,413
  • 15
  • 58
  • 95

2 Answers2

2

As neither the tests or the web application is working, it's likely that the problem you are seeing is because the configuration is not being loaded. I suspect that the following...

ConfigurationManager.ConnectionStrings["DomainDatabase"]

...returns null. The NullReferenceException is thrown when you attempt to access the ConnectionString property on that null object (reference). I would verify that your configuration for connectionStrings matches the definition defined here:

You can verify that your settings aren't being loaded with the following test:

[TestMethod]
public void VerifyThatMyDatabaseConnectionStringExists()
{
    Assert.IsNotNull(ConfigurationManager.ConnectionStrings["DomainDatabase"]);
}

If this test fails, add an app.config to your test project with the proper configuration. You will know that you have solved this problem when ...you can take this pebble from my hand -- no wait, wrong reference -- this test passes.

Tip: This answer suggests you should write tests to verify that your settings are present to prevent madness.

Community
  • 1
  • 1
bryanbcook
  • 16,210
  • 2
  • 40
  • 69
0

Try to copy app.config file wich has connectionString into Test-project and it works!

Viktor
  • 1
  • 1