Where to store and how to access a connection string - c#

Where to add the connection string in a C# project? Like this string?
<connectionStrings>
<add name="strConn"
connectionString="Data Source=abc;Password=pass;User ID=user"
providerName="Oracle.DataAccess.Client">
</add>
</connectionStrings>
And how can I call it from my program.cs file?

This will be added in the configuration file. If it is an ASP.NET application, then this would be the web.config file. If it is a Winforms/Console application this would be the app.config file.
To call it from the application, you'd have to use the System.Configuration namespace like so:
using System.Configuration;
string YourConnectionString =
ConfigurationManager.ConnectionStrings["yourConnStringName"].ConnectionString;
Where "yourConnStringName" is the name of your connectionString in your config file.

The connection string like the one you posted is placed in a configuration file called app.config and whenever you want to get a connectionstring you can get it like:
string strConn = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString;
see this

Add it to your app.config under <configuration> and to call it from your program.cs use:
ConfigurationSettings.AppSettings["strConn"]

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):

Getting a ConnectionString from app.config

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.

Reading Connection string from application Config file

I am trying to read a connection string from the application configuration file.
But keep receiving an error:
The name ConfigurationManager does in exit in current context.
After googling the error, I added ConfigurationManager to my project. But I still get the same error.
My code:
string sqlConStr = ConfigurationManager.ConnectionStrings["AppConnectionString"].ToString();`
My application config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="AppConnectionString" connectionString="SERVER=1894; Database=db; UID=loss; PWD=where;encrypt=no;enlist=false" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Ensure you have referenced System.configuration.
Then make sure you either import the correct namespace
using System.Configuration;
or use the full typename
string sqlConStr = System.Configuration.ConfigurationManager.ConnectionStrings["AppConnectionString"].ToString();
Try using ConnectionString
var connection = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;

Moving multiple app.config's to something more global

We have several c# selenium test suites that are run on several servers by several testers.
I want to simplify the settings if possible. Currently we have multiple c# selenium projects each with their own app.config. When I want to change the server, I need to change each and every app.config. My app.config currently looks something like this:
<connectionStrings>
<add name="Company"
connectionString="Data Source=func3_db1;Initial Catalog=CompanyProduction;Integrated Security=SSPI;"/>
<add name="CompanyProductionEntities"
connectionString="metadata=res://*/DataAccess.CompanyEntities.csdl|res://*/DataAccess.CompanyEntities.ssdl|res://*/DataAccess.CompanyEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=func3_db1;initial catalog=CompanyProduction;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
We also have some settings in Windows Environment variables. It's kind of an obscure way of doing it but it works pretty well. To access these settings, we just do something like this:
var value = Environment.GetEnvironmentVariable(varName, EnvironmentVariableTarget.User);
So, we have a variable called "CompanyTestBrowser" which can be set to "Firefox" or "Chrome" or "IE".
I like environment variables because the powershell scripts that run all of our selenium tests can easily alter the variables whenever they need to.
However, I can't seem to pull those DB strings out of this app.config. How can I move them into something that can be a bit more global & dynamic. Ideally I only have to set in 1 single place? Ideally, I could move them into environment variables like the other or a config file that sits outside the c# project.
Thanks!
My advise would be, have the connection strings maintained in a xml file in a networklocation ex. \machine-name\DBConnectionString.config as below format
<connectionStrings>
<add name="Company"
connectionString="Data Source=func3_db1;Initial Catalog=CompanyProduction;Integrated Security=SSPI;"/>
<add name="CompanyProductionEntities"
connectionString="metadata=res://*/DataAccess.CompanyEntities.csdl|res://*/DataAccess.CompanyEntities.ssdl|res://*/DataAccess.CompanyEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=func3_db1;initial catalog=CompanyProduction;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
At your application startup routine, read \machine-name\DBConnectionString.config file and update application config file using the below code snippet,
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Create a connection string element and
// save it to the configuration file.
//Read the \\machine-name\DBConnectionString.config file
// Create a connection string element.
ConnectionStringSettings csSettings =
new ConnectionStringSettings("My Connection",
"LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" +
"Initial Catalog=aspnetdb", "System.Data.SqlClient");
// Get the connection strings section.
ConnectionStringsSection csSection =
config.ConnectionStrings;
// Add the new element.
csSection.ConnectionStrings.Add(csSettings);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
Hope this helps.
You could add a key to app.config which has a path to an XML file which has all the common settings in it and then write a new ConfigurationManager class to first try to pull out a value from app.config and if not found, open the XML file and look for it in there
Something like this:
<appSettings>
<add key="ConfigFileSettings" value="\\MyServer\CommonSetting\settings.xml"/>
I used the accepted solution above. This is my exact code (which is only slightly different than above).
This solutions effectively keeps my current app.config file. All other settings in that app.config file are kept, except I "override" the "connectionString" part with my custom one.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
System.Console.WriteLine("Starting to write app.config stuff");
//Change the Admin's app.config where name=companyProductionEntities
config.ConnectionStrings.ConnectionStrings["companyProductionEntities"].ConnectionString =
string.Format(#"metadata=res://*/DataAccess.companyEntities.csdl|res://*/DataAccess.companyEntities.ssdl|res://*/DataAccess.companyEntities.msl;provider=System.Data.SqlClient;provider connection string=';data source={0};initial catalog=companyProduction;integrated security=True;multipleactiveresultsets=True;App=EntityFramework';", SeleniumConfiguration.SimpleDatabaseConnectionString);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

Reference to connectionstring in settings

This is for a Windows Application.
In a class I want to referee to my connectionstring called freighthelper which is located in the settings.settings file in my project. How do I do this?
I have tried with this without success.
_connection.ConnectionString = FreightHelper.Properties.Settings.Default.freighthelper;
Why do you need to store your connection string in a settings file? It is usually put in the config file and retrieved like this: http://msdn.microsoft.com/en-us/library/ms254494%28VS.80%29.aspx
try this: _connection.ConnectionString=Settings.Default. freighthelper; to read form a setting files.
NOte: connection string better to place in App.confing
E.g:
<connectionStrings>
<add name="Name" connectionString="Data Source=Instance Name;Integrated Security=True;MultipleActiveResultSets=True;"
providerName="System.Data.EntityClient" />

Categories