0

I have a local SQL Server database (managed via Management Studio) and a local ASP.NET project. VS2017 correctly sees the database in the Server Explorer. This is also the place where I got my connection string; as recommended by a few posts on the internet. I placed the string next to the existing one (for the account management) in my web.config. The file looks like this:

<configuration>
    <connectionStrings>
        <add name="DefaultConnection" 
             connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Project-20170524124716.mdf;Initial Catalog=aspnet-Project-20170524124716;Integrated Security=True" 
             providerName="System.Data.SqlClient" />
        <add name="MyLocalDb" 
             connectionString="Data Source=MYLAPTOP;Initial Catalog=TestDb;Integrated Security=True;" 
             providerName="System.Data.SqlClient" />
    </connectionStrings>
    <!--More things-->
</configuration>

I try to access the second string like this:

string connString = ConfigurationManager.ConnectionStrings["MyLocalDb"].ConnectionString;

Which is the way it's done here, here, here and here (among almost every other post on the subject). But, when I run the code I get the following exception:

System.NullReferenceException: Object reference not set to an instance of an object.

at ProjectUnitTests.DatabaseTests.TestConnection() in ProjectUnitTests\DatabaseTests.cs:line 16

I have the reference to using System.Configuration; set here. I'm also pretty sure that the formatting on my web.config is right, given this post made my recheck it about 10 times. I've tried removing the first string, but it had no effect.

The connection string is correct. When I use it directly in my code I can access the database.

Note that the code is run from another project; I have a class library that the code is running from. The Web.config file is in another project. I've read in my long search for the answer that this could be an issue; although I can't find more sources on this.

Edit:

On request; the entire method from the Unit Tests:

[TestMethod]
public void TestConnection()
{
    //Connection tester will be called from the constructor
    Database instance = Database.Instance(); //The Database class is in a class library. When calling the instance it will get the connection string itself
    string connString = ConfigurationManager.ConnectionStrings["TicketSlothLocalDb"].ConnectionString; //Test if I was able to get the string at all. Apparently this is never possible.
    Console.WriteLine(connString); 
}

The Database class:

    private Database()
    {
        openConnection();
    }

    public static Database Instance()
    {
        _instance = _instance ?? new Database();

        return _instance;
    }

    private void openConnection()
    {
        try
        {
            string connString = ConfigurationManager.ConnectionStrings["TicketSlothLocalDb"].ConnectionString;
            conn = new SqlConnection(connString);
            conn.Open();
            openConn = true;
            testConnection(); //Function with a small SQL query inside to verify that it is able to retrieve data from the database
        }
        catch (SqlException ex)
        {
            Console.WriteLine(ex);
            Console.WriteLine("Password is incorrect");
            connectionstring = null;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Threw other exception: {0}", ex);
        }
    }

Why can't I access the web.config property here?

MagicLegend
  • 328
  • 1
  • 5
  • 22
  • 1
    *Note that the code is run from another project* - Well, there's your problem. You need to make sure your current project looks up the same web.config in which you defined your connection strings. – Koby Douek Jun 04 '17 at 10:52
  • Copy the web.config into the TestProject and change the name from web.config to app.config – Max Jun 04 '17 at 10:54
  • @KobyDouek But that should work when using the `ConfigurationManager`, that's the issue I'm having... (See: https://stackoverflow.com/questions/8422072/reading-web-config-from-class-library , https://stackoverflow.com/questions/18682078/get-connection-string-in-class-library-project-in-a-solution , https://stackoverflow.com/questions/7652757/access-web-config-from-separate-class-library ) – MagicLegend Jun 04 '17 at 10:55
  • Those links are about a class library accessing the config settings of its 'host'. If a DLL is running inside an ASP.NET project, then indeed it can access the config entries of the ASP.NET host. But your error seems to be originated from a test project - in which case the ASP.NET project is likely not the host. Instead the host is the runner for the unit test framework you are using (e.g. NUnit). See https://nunit.org/index.php?p=configFiles&r=2.5 for example. – mjwills Jun 04 '17 at 11:07
  • @mjwills Ewh, that is different. Good to know. The problem also exists in the class library that I'm using; but I stumbled upon the fact that ASP doesn't have proper logging by default, so I started using a unit test for it to see what really went wrong. What you say is that it should work in the class library, given that the ASP project is the host for it? – MagicLegend Jun 04 '17 at 11:10
  • If you are experiencing the issue in the ASP.NET project, it is crucial that you give us the actual error from that context (not the one you have included above). You may also want to put a breakpoint on the line that is giving a NullReferenceException, and check things like ConfigurationManager.ConnectionStrings.Count (and let us know what that value is). – mjwills Jun 04 '17 at 11:12
  • You may also want to try https://stackoverflow.com/questions/23930126/how-to-find-the-config-file-location-via-configurationmanager to verify that the config file location being read from is the same file that you have edited. – mjwills Jun 04 '17 at 11:14
  • @mjwills Yes, it is in a ASP.NET project (hence `web.config` instead of `app.config` and the `ASP.NET` tag :-) I try to access the data from the class library, so I don't have to give it on every instance call I make. I have absolutely no idea why, but it works now... I probably have changed something somewhere that I'm not aware of, but I can properly read the connectionstring via the `ConfigurationManager`. Thank you all for your time. – MagicLegend Jun 04 '17 at 11:23
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/145800/discussion-between-mjwills-and-magiclegend). – mjwills Jun 04 '17 at 11:24

1 Answers1

0

You need to add the database entry to the config for your unit test project. This file would be called app.config and would be in the root folder of your unit test project. When the project builds, the file will 'become' dllname.config in your bin folder (the build process should take care of this for you).

(My assumption that this is true is based on this mention in the stack trace - ProjectUnitTests).

mjwills
  • 23,389
  • 6
  • 40
  • 63
  • This code is indeed from a unit test project, but as I mentioned in my last comment I stumbled upon the error first in my class library. And the links I mentioned in the post and comments all mention that it should function from a class library, but I can't get it working. :( – MagicLegend Jun 04 '17 at 11:11
  • Can you show us the entire TestConnection method, as well as the entire method in the ASP.NET project which exhibits the error? – mjwills Jun 04 '17 at 11:16
  • Of course, but as the comments on the question indicate I apparently can't access the string from a unit test. From the class library I now am able to retrieve the connection string. I'll include the code in a edit in a min. – MagicLegend Jun 04 '17 at 11:25
  • If you follow the instructions in my answer, you should be able to see the string in a unit test (although, to be fair, you likely shouldn't be accessing a database in a unit test). – mjwills Jun 04 '17 at 11:28
  • No, I shouldn't. And I'm aware of that, but my school isn't, and requires me to make unit tests for everything. Thanks for the heads-up anyway :) The issue I'm having right now is that I can't access the string when I create a instance from the unit test. Thinking back that has been my issue, I didn't know that it ran from a different host. Thank you for your time. – MagicLegend Jun 04 '17 at 11:40