Getting a ConnectionString from app.config - c#

I have a Web project which calls a library project (DataAccess) to retrieve some data from the database. I added an App.config file (Add -> New Item -> Application Configuration File) to the DataAccess project and added a connectionString section like this:
<configuration>
<connectionStrings>
<add name="local"
connectionString="Data Source=.\sql2008;Initial Catalog=myDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
In the DataAccess project, I have the BuildConnection method:
internal static SqlConnection BuildConnection()
{
string connectionString = ConfigurationManager.ConnectionStrings["local"].ToString();
return new SqlConnection(connectionString);
}
When I call the method from the Web project, it throws a null exception complaining that the "local" connection string doesn't exist. After debugging it for a while I added the same connection string to the Web.config of the Web project, and now it works fine. The problem though is that I want to isolate the DataAccess project from the Web project, in other words, I want the DataAccess project to use its own app.config file no matter who calls it. Is this even possible? Any help would be appreciated.

at runtime, there is just one config file. so the config file of the active project is only
considered. also, you cannot have a class library project as an active/startup project i.e.
say you have 4 Projects in your solution, and each of them has a config file, then when you run the application, only the active project's(the one which is your startup project) config file is recognized.
Now what can you do?
if you just want to isolate the sections of the config file, then you can have config file in each of your Projects, which in turn, are referenced in the main projects config i.e.
Web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="YourSettings.config">
<add key="KeyToOverride" value="Original" />
<add key="KeyToNotOverride" value="Standard" />
</appSettings>
<system.web>
<!-- standard web settings go here -->
</system.web>
YourSettings.config:
<appSettings>
<add key="KeyToOverride" value="Overridden" />
<add key="KeyToBeAdded" value="EntirelyNew" />
</appSettings>
read more about it here
if you want to have separate config files for your active project itself, than that's whole different story altogether.
its kind of ugly tweak, but read about it here

An app.config is used when you use in an Application. For a library project using a app config file not helps. Even you put it reference library the code will be in web server.
So this type isolation has no sense for any security issue.
But approach of putting things to the right place you are right, the problem is when you reference a dll it doesn't include the dll project's config.
If you want more :) Just read app.config in your lib project and using a code generator create a connection string object such as public static string ConnectionString = $GeneratedCode$;

Yes, it's possible.
Your app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="foo" value="bar"/>
</appSettings>
</configuration>
Your DataAccess layer:
namespace MyApp.DataAccess
{
public class DB
{
public string cfg;
public DB()
{
var asmName = System.Reflection.Assembly.GetAssembly(this.GetType()).GetName().Name;
var asmPath = System.Web.HttpContext.Current.Server.MapPath(#"bin\" + asmName + ".dll");
var cm = ConfigurationManager.OpenExeConfiguration(asmPath);
this.cfg = cm.AppSettings.Settings["foo"].Value;
}
}
}
Here's how to use it:
namespace MyApp.WebApp
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var db = new MyApp.DataAccess.DB();
Response.Write(db.cfg);
}
}
}
When you compile data access project, it'll generate a MyApp.DataAccess.dll.config out of your app.config content. Add MyApp.DataAccess.dll.config and MyApp.DataAccess.dll to your web app project and make sure to mark Copy To Output Directory to Copy if newer for MyApp.DataAccess.dll.config.

Related

ConfigurationManager ConnectionString not working

I have this project I am working on and I want to "hide" my connection string from my main class and place it to the App.Config.
While trying to access the connection string from the main class I get this error "System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null."
This is my main class code that I use to get the conn string:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString.ToString();
This is my App.Config code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnString" connectionString="Password=XXXX;Persist Security Info=True;User ID=XXXX;Initial Catalog=XXXX;Data Source=XXXX"/>
</connectionStrings>
</configuration>
Note: I have to add the app.config by myself as a new class.
Also the connection string works perfect when it's in the main class, so it's not its fault.
The WebConfig connection string should be like this:
<connectionStrings>
<add name="DBCS" connectionString="server=.;database=MVCCrud;integrated security=SSPI" providerName="Sql.Data.SqlClient" />
</connectionStrings>
The main class connection string should be like this:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
I added config, added you code and configuration and it worked.
I can't add this as a comment, as I can't post images there, that's why I am writing an answer.
So, just to make sure you added the file in a correct way:
right click your project, add -> new item:
and then just find appropriate file to add (you can make use of search text box):

C# Cannot read from App.config file in MVC

I have an MVC project and am trying to store my API keys in a separate config file which I will ignore when pushing the code to Git. According to MSDN I should be able to store them in an App.config like like so
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="APIKey" value="APIKeyValue" />
</appSettings>
</configuration>
I should then be able to read from the file by creating a method in a model
public class KeyTest
{
public string KeyTestCall()
{
string testkey = ConfigurationManager.AppSettings.Get("APIKey");
return testkey;
}
}
and then invoke the method in my controller to assign the value from my App.config file (just so I know I'm getting the value).
public void Testing()
{
KeyTest k = new KeyTest();
ViewBag.x = k;
}
At no point will the code break for a breakpoint, the build will succeed and I can't tell if I'm getting the value or not. Any help is much appreciated. Thanks!
For a web application such as an MVC app, it's a Web.config file, not an App.config
In addition to above (re: web.config vs app.config) if you want to remove "secrets" from source control, this is one way to do it:
In web.config
<?xml version="1.0" encoding="utf-8"?>
<cofiguration>
....
<appSettings file="AppKeys.config">
<add key="SomeOtherSettingThatHasNoSecrets" value="foo" />
...
Then in a separte AppKeys.config file (you can name this whatever.config, sample as named in the above), that you don't add to Git/source control:
<appSettings>
<add key="SomeSecretKey" value="the secret" />
...
Note that AppKeys.config doesn't have an XML declaration.
Hth.

Can't get web.config transform to work

I have an ASP.Net application. I created the transforms for the Web.config file to produce Web.Debug.config and Web.Release.config. Unfortunately, I can't get the code to read these transforms at run time. Here's a snippet of the code that's reading the .config file:
protected void Page_Load(object sender, EventArgs e)
{
Logger logger = LogManager.GetCurrentClassLogger();
string config = ConfigurationManager.AppSettings["Configuration"];
Label1.Text = string.Format("Configuration application string = \"{0}\"", config);
Here is a snippet from the original Web.config file:
<configuration>
<appSettings>
<add key="Configuration" value="Default"/>
</appSettings>
Here's the corresponding snippet from the Web.Release.config file:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings xdt:Transform="Replace">
<add key="Configuration" value="Release"/>
</appSettings>
When I preview the transform, all is good (i.e., I see that the value of "Configuration" is "Release"). However, when I build, publish, and run it, I get the default value.
I read elsewhere that the transforms don't work on the build but rather on the publish, but I'm publishing to C:\inetpub\wwwroot. And when I look at the Web.config file there it does say "Release". Why isn't it showing up when I run my program? (This is Windows 7 Professional and VS2013.)

How to get connection string from app.config in another class library project?

how do I get the connection string from app.config in another "class library project"
in the same class library I can use this code :
DAL.Properties.Settings.Default.BayrueConnectionString;
but the issue is that I cannot get it from my web app.
thanks
I think there is no more elegant way than this. Add a static helper method to your class library which returns it.
public sealed class Helper
{
private Helper()
{
}
public static string GetBayrueConnectionString()
{
return DAL.Properties.Settings.Default.BayrueConnectionString;
}
}
Add reference to System.Configuration.
Use System.Configuration.ConfigurationManager.ConnectionStrings["DAL.Properties.Settings.BayrueConnectionString"]
First, create a new ConnectionStrings.config file in the project you'd like to reference.
ConnectionStrings.config:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication-20130625013234;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication-20130625013234.mdf" />
</connectionStrings>
Next, unload your DAL project. Once unloaded, right click > Edit DAL.csproj.
Add the following element to the .csproj with the Include="{the ConnectionStrings.config you'd like to reference}":
<ItemGroup>
<Content Include="..\ConnectionStrings.config" />
</ItemGroup>
Reload your project. This should add a ConnectionStrings.config file, shown above, to your project. Notice that both will open the same file. Now edit the app.config to reference the newly created .config file that was just added to your DAL:
<connectionStrings configSource="ConnectionStrings.config" />

Read AppSettings from a secondary webconfig

I created a second web config and placed it in a folder:
~/Configuration/OtherConnections.config
My config file looks like:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="serverurl" value="http://serverUrl" />
<add key="UserName" value="myUser" />
<add key="Password" value="XXXXXXX" />
</appSettings>
</configuration>
When I attempt to read the value from one of the items like:
string connectionInfo = ConfigurationManager.AppSettings["UserName"];
I do not get a value back. Is this because the web config is in a folder, or is there something else going on in this web app?
I do not get a value back. Is this because the web config is in a folder ... ?
No, not the folder but the filename. You can use ~/Configuration/Web.config but then you have to explicity open it:
var config = WebConfigurationManager.OpenWebConfiguration("~/Configuration");
And then to read from it:
string url = config.AppSettings.Settings["serverurl"].Value;
Note that you cannot specify (and thus not change) the actual web.config file name. Just the folder.
you can have only one web.config file for each web folder
There are tow options anyway:
In the IIS Manager you need to configure the sub folder as a new application. It uses the web.config file from the running app.
Another option is using a single config file and adding a <location> section to segment the file to act differently for some folders or files. (which I would suggest more info here)
You can access multiple config files by using WebConfigurationmanager method. add namespace:
using System.Web.Configuration;
So, to access the appSettings of
../SomeProjectFolder/Environment/Web.config, you can do:
var config = WebConfigurationManager.OpenWebConfiguration("~/SomeProjectFolder/Environment/");
string username = config.AppSettings.Settings["username"].Value;
Hope this helps.

Categories