Sunday, November 17, 2013

You cannot read from App.config in a supporting project. Boo hoo.

I have just come to a painful realization that makes a lot of the silly stuff I've tried and failed finally make sense. The trick I use here when reading from App.config in a unit test project will not work if you are attempting to read from App.config in a project that is not the UI project or first project to load (the bootstrapper project or the project you have "Set As Startup Project") in a Visual Studio solution but is instead a project that is inherited from somewhere downstream. You will get an error like this:

The key 'YOURNAMEHERE' does not exist in the appSettings configuration section.

 
 

I think the expectation is that I would just put the key I needed in Web.config (or its "first project" counterpart) in lieu of needing a different configuration file in another project. Perhaps this is a perfectly legitimate expectation. So, what is my problem? In the infrastructure project of an onion architecture implementation wouldn't it be cool to keep a configuration file THERE in lieu of summoning specifications out of the Web.config in a different project? All of the external dependencies are in the infrastructure project and not the UI project. Why should the connection string to the database be kept in the UI project when that is not the project that needs it? Beyond any debate about whether or not my logic herein makes good sense, I would like to offer that I have found a workaround. One may publish (Build Action is Content and Copy to Output Directory is Copy always) a .txt file from the infrastructure project to bin folder upon every build and scrape it like so:

private string[] ReadFromFlatFile()
{
   string path = System.AppDomain.CurrentDomain.BaseDirectory;
   path = path + "bin\\ApplicationNotes.txt";
   string text = System.IO.File.ReadAllText(path);
   return text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}

 
 

Your solution may be more elegant than mine above obviously.

 
 

Addendum 9/24/2018: What is above really shows off how to split a string with a string instead of a char. For example, this test would pass:

string copy = "Dirty dwarves dwell in dirty dwellings like dweebs.";
string[] parts = copy.Split(new string[] { "dw" }, StringSplitOptions.None);
Assert.AreEqual(parts.Length, 5);
Assert.AreEqual(parts[0], "Dirty ");
Assert.AreEqual(parts[1], "arves ");
Assert.AreEqual(parts[2], "ell in dirty ");
Assert.AreEqual(parts[3], "ellings like ");
Assert.AreEqual(parts[4], "eebs.");

No comments:

Post a Comment