I have my config file with below configurations:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" />
</configSections>
<dataConfiguration defaultDatabase="myConnectionString" />
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=mydatasource;Max Pool Size=100;Pooling=true; Initial Catalog=MyDB;User ID=Myuser;Password=Password;Connection Timeout=60" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
</configuration>
As you can see, I have set the default dataconfiguration to use myConnectionString as the default connection string, but in code behind (c#) how can I access this connection string without having to provide the name i.e. myConnectionString
So in below code:
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection cnn = new SqlConnection(connectionString);
SqlBulkCopy sbc = new SqlBulkCopy(cnn);
I would like to skip hardcoding the name of the connection string.
var dataConfig = (Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings)System.Configuration.ConfigurationManager.GetSection(
"dataConfiguration");
string connectionString = ConfigurationManager.ConnectionStrings[dataConfig.DefaultDatabase].ConnectionString;
That's what I can tell from typical usage of custom config sections and DatabaseSettings class.
EDIT: I have tested it in LINQPad with your exact app.config, got result:
Data Source=mydatasource;Max Pool Size=100;Pooling=true; Initial Catalog=MyDB;User ID=Myuser;Password=Password;Connection Timeout=60
Related
I need to use a different connection string than the one in the default settings value in the settings designer in order to run on my staging PC.
I have in settings.designer.cs:
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=MyServer\\MyDB;Initial Catalog=MyDB;Integrated Security=True;Pers" +
"ist Security Info=True")]
public string MyConnectionString {
get {
return ((string)(this["MyConnectionString"]));
}
}
My app.config is this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear />
<add name="MyConnectionString " connectionString=Data Source=MyServer2\\MyDB;Initial Catalog=MyDB;;Trusted_Connection=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
I want the application to use the settings in app.config but it persists in using the settings in the settings designer file.
I have tried various permutations of the following as well:
<add name="AppName.Properties.Settings.Default.MyConnectionString" connectionString=Data Source=MyServer2\\MyDB;Initial Catalog=MyDB;;Trusted_Connection=True"
providerName="System.Data.SqlClient" />
such as:
AppName.Properties.Settings.GlobalReference.Default.MyConnectionString
and:
ApplicationSettings.AppName.Properties.Settings.GlobalReference.Default.MyConnectionString
Any thoughts or ideas would be greatly appreciated.
In order for this to work, you have to have System.Configuration in your references.
you need to access the configuration Manager
System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
change your connection string name to something more simple or you'll have to use all of that
System.Configuration.ConfigurationManager.ConnectionStrings["AppName.Properties.Settings.Default.MyConnectionString"].ConnectionString;
if you want to use system properties you should add the system.reflection reference
I am a beginner and learning WPF Application. I have a simple project and in that I want to read DB Configuration string from App.Config File. But I am not able to do so. Below is my attempt:
APP.Config File:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="DBCS" connectionString="Data Source=.\;Initial Catalog=Connect;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
CS Code:
public static void GetDataFromDB()
{
//var CS = #"Data Source=.\;Initial Catalog=Connect;Integrated Security=SSPI";
// ABOVE CODE WORKS FINE
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select * from tblTenant", con);
DataSet ds = new DataSet();
da.Fill(ds);
}
}
Edit:
You need to put the connnection string in the App.config of the running WPF application and not in the DAL or any other class library.
The ConfigurationManager class reads the configuration file of the running executable.
Add "clear" to your app.config before the connections string definition. It will look like this :
<connectionStrings>
<clear/>
<add name="DBCS" connectionString="Data Source=.\;Initial Catalog=Connect;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
Try to change in the App.config:
You can add Connection string to both DAL and UI projects.
Try removing Data Source =.\ to Data Source =.
Can't find what is wrong with my connection string:
I get this exception:
System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized element. (D:\C#\learncsharp\Data access\AsyncSQL\AsyncSQL\bin\Debug\AsyncSQL.exe.Config line 2)
This is my code:
string connectionString = null;
string MovieDBContext = null;
try
{
MovieDBContext = ConfigurationManager.ConnectionStrings["MovieDBContext"].ConnectionString;
connectionString = ConfigurationManager.ConnectionStrings["ProgrammingInCSharpConnection"].ConnectionString;
}
catch (Exception e)
{
Console.WriteLine( e.ToString() );
}
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="ProgrammingInCSharpConnection"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ProgrammingInCSharp;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
What is wrong? And how to get details which element is wrong?
Make sure you have defined the section in the <configSections> element.Change your config as follows,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections />
<connectionStrings>
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
<add name="ProgrammingInCSharpConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ProgrammingInCSharp;"
/>
</connectionStrings>
</configuration>
I'm trying to use input from a windows form app to enter into a localdb, however when I send the data to the database it returns "the config system failed to initialize".
try
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["database"].ConnectionString);
SqlCommand cmd = conn.CreateCommand();person newPerson = new person(FirstNameBox.Text, phoneBox.Text, emailBox.Text, LastNameBox.Text);
cmd.CommandText = #"INSERT INTO Person (FirstName, LastName, Email,Phone)
VALUES(#FirstName, #LastName, #Email, #Phone)";
cmd.Parameters.AddWithValue("#FirstName", newPerson.getFirstName());
cmd.Parameters.AddWithValue("#LastName", newPerson.getLastName());
cmd.Parameters.AddWithValue("#Email", newPerson.getEmail());
cmd.Parameters.AddWithValue("#Phone", newPerson.getPhone());
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
if (!ValidateForm())
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
and this is the app.config part
<?xml version="1.0" encoding="utf-8" ?>
<configSections>
<connectionStrings>
<add name="database"
connectionString=" Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Matthew\Documents\Visual Studio 2012\Projects\Midterm\Midterm\Database1.mdf;Integrated Security=True"></add>
</connectionStrings>
</configSections>
<connectionStrings>
<add name="Midterm.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
The most obvious issue I'm seeing here is that your app.config is specifying a <connectionString> section, where it should be <connectionStrings> (note the s).
You may want to provide your entire app.config as there may be other syntax/configuration issues that prevent ConfigurationManager from loading your app.config.
Edit for updated app.config:
Your app.config file is incorrectly formatted. <configSections> shouldn't be the root element of the file (it should be <configuration>).
The MSDN documentation for ConfigurationManager.ConnectionStrings shows an example of what a app.config file should be formatted like.
But, in short, the <connectionStrings> element (and the other elements such as <startup>) should be a child element of <configuration>.
What your app.config should be like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
*** ADD YOUR <add> LINES HERE ***
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
I have a config file in a wpf project to store the connectionstring.
But when I try to get AppSettings and ConnectionStrings, I get null.
the WEB.config file is like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Trackboard" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:\Users\Sean\Workspace\DATABASE\Trackboard.mdf"/>
</connectionStrings>
<appSettings>
<add key="Trackboard" value="Data Source=(localdb)\v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:\Users\Sean\Workspace\DATABASE\Trackboard.mdf"/>
</appSettings>
</configuration>
I tried in several ways:
W1: ConnStr = ConfigurationManager.ConnectionStrings["Trackboard"].ConnectionString;
W2: ConnStr = ConfigurationManager.ConnectionStrings[0].ConnectionString;
W3: ConnStr = ConfigurationManager.AppSettings["Trackboard"];
W4: ConnStr = ConfigurationManager.AppSettings[0];
None of them worked.
But this one worked:
ConnStr = #"Data Source=(localdb)\v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:\Users\Sean\Workspace\DATABASE\Trackboard.mdf";
(That means I cannot use a config file, which is against my will)
I need help.
Just add an app.config and not web.config because it is not a web application.
And after that it's too simple, just add a reference to to System.Configuration and then use this.
var ConnStr = ConfigurationManager.AppSettings["Trackboard"];
This one use System.Configuration namespace
using System.Configuration;
Or add System.Configuration in reference
System.ConfigurationManager.ConnectionStrings["Trackboard"].ConnectionString;
System.ConfigurationManager.ConnectionStrings[0].ConnectionString;
I've figured it out!
I shouldn't have created a new config file. There is a default app.config file in the project.
Now everything is fine.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Trackboard.Properties.Settings.TrackboardConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\DATABASE\Trackboard.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
private static string ConnStr = ConfigurationManager.ConnectionStrings["Trackboard.Properties.Settings.TrackboardConnectionString"].ConnectionString;