Reference to connectionstring in settings - c#

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" />

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

Reading connection string from external config file

I have created a console application and an app.config file and Connections.config file.
The app.config file has a connectionstring property source pointing to the Connections.config
When I tried to read the connection string in the application, I get a ConfigurationErrorException
This is my main method.
static void Main(string[] args)
{
var settings = ConfigurationManager.ConnectionStrings;
if (settings != null)
{
foreach (ConnectionStringSettings setting in settings)
{
Console.WriteLine(setting.ConnectionString);
}
}
}
App.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings configSource="Connections.config"></connectionStrings>
</configuration>
Connections.config file
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
Here I observed two things.
First: If I specify configSource I am unable to read the connection string (throwing exception.)
Second: If I put same connection string in App.config file and tried to read then the code is working but getting two connection string (which supposed to be return only one which is empty string)
The first connection string is sqlexpress connection string like this
data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
second connection string it returning is empty string (This is expected).
I want to read connection string from external file like in my scenario. How to do that? What am I missing here?
MSDN says:
Do not include any additional elements, sections, or attributes.
You need to remove the XML encoding.
Edit
Also, you need to set the properties of your config file to Copy to Output Directory = Copy if newer or Copy always.
Edit 2
To build on what Dave said, you add the clear element to your external file. Your final Connections.config file should look exactly like this:
<connectionStrings>
<clear/>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
Your Connections.config file should be as shown below without the xml header
<connectionStrings>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
Also for it to correctly locate the file in your console application, please set the Copy to Output Directory to Copy Always or Copy If Newer.
That first connection string you are getting is inherited from the machine.config. This is described in the MSDN documentation. http://msdn.microsoft.com/en-us/library/bf7sd233(v=vs.90).aspx
You can use the Clear tag in your config file to remove inherited connection strings.
http://msdn.microsoft.com/en-us/library/ayb15wz8(v=vs.90).aspx
<connectionStrings>
<clear/>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
There is a nice article on MSDN: https://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx.
Quote from the article:
To store connection strings in an external configuration file, create
a separate file that contains only the connectionStrings section. Do
not include any additional elements, sections, or attributes. This
example shows the syntax for an external configuration file.
<connectionStrings>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
Hope this helps people who run into this question later.

Database in two folder, bin->debug, release

I am adding my database in both bin->Debug and bin->Release folder.
When I create a setup file, I am getting the primary output from configuration manager->release.
Is there a way I could have the DB set up at only one place (not both Debug and Release folder)
This is the connection string:
<add name="myConnString" connectionString="Data Source=Test.sqlite; InitialCatalog = Test.sqlite;Compress=True;Version=3"
providerName="System.Data.Sqlite" />
Thank u
Why don't you create a 'data' folder at the same level than the bin folder? This way the database location never changes, and you can use InitialCatalog =../../data/Test.sqlite
Place it in the main Project path:
<add name="myConnString" connectionString="Data Source=Test.sqlite; InitialCatalog = ..\..\Test.sqlite;Compress=True;Version=3"
providerName="System.Data.Sqlite" />

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");

Where to store and how to access a connection string

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"]

Categories