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 =.
Related
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
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;
I am working on asp.net c# project, for connection I used:
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
but I want to get this connection string to get configure and be like this, so can any one help how to create this kind of connection.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Demo :
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Based on your question:
<connectionStrings>
<add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Refer links:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
Retrive connection string from web.config file:
write the below code in your file where you want;
string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;
SqlConnection con = new SqlConnection(connstring);
or you can go in your way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Note:
The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)
string connectionstring="DataSource=severname;InitialCatlog=databasename;Uid=; password=;"
SqlConnection con=new SqlConnection(connectionstring)
add this in web.config file
<configuration>
<appSettings>
<add key="ConnectionString" value="Your connection string which contains database id and password"/>
</appSettings>
</configuration>
.cs file
public ConnectionObjects()
{
string connectionstring= ConfigurationManager.AppSettings["ConnectionString"].ToString();
}
Hope this helps.
Add this in your web.config file
<connectionStrings>
<add name="itmall"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-
02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Add this connection string tag in web.config file:
<connectionStrings>
<add name="itmall"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
And use it like you mentioned. :)
It occurs when IIS is not being connected to SQL SERVER. For a solution, see this screenshot:
In windows forms application there is no web.config. So how can i declare the single connection string? And how can I call it in another pages?
In App.config page
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="CONSTRING" connectionString="Data Source=SQL-PC;Initial Catalog=DATABASE;Integrated Security=True"/>
</connectionStrings>
</configuration>
In Form I call this connectin string.
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace Sample {
public partial class Sample: Form
{
public string conn = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
}
Now there is error shows. ConfigurationManager does not exist in this current context. How can I solve it?
ConfigurationManager class resides in System.Configuration assembly. And to make your code work you need to add reference to System.Configuration assembly to the project.
You can declare various connections string in App.config and use use:
var conString =System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"];
string strConnString = conString.ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand(String.Format("SELECT * FROM Table;"), con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
And declare a connection string in App.config:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=database;Integrated Security=True; MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
App.config is what you are looking for.
How to add configurations to windows forms.
Also use Configuration Manager to get your configurations.
you don't need any configuration file add below code in your connection string
static string ConStr = "Data Source=DataSourceName;Initial Catalog=DatabaseName;Integrated Security=True";
SqlConnection con = new SqlConnection(ConStr);
place this code before namespace
using System.Configuration;
Add reference to System.Configuration assembly to the project.
Then use below code in c# form page
var conString = System.Configuration.ConfigurationManager.ConnectionStrings["CONSTRING"];
string strConnString = conString.ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
Your app.config connectionstring should be like this.
<connectionStrings>
<add name="CONSTRING" connectionString="Data Source=MONAIT-PC;Initial Catalog=CMS;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
By using connection two ways: 1. Sql Server Authentication
2. Windows Authentication
{Sql Server Authentication}
<connection string>
<add name="somename" connectionstring="database=databasename;data source=servername;uid=somename;pwd=somename(or)numbers">
</connection string>
{Windows Server Authentication}
<connection string>
<add name="somename" connectionstring="database=databasename;data source=servername; integrated security = true">
</connection string>
In Windows form application there is Application config file in that you can add connection string and you can call that file to all page of that application.
You can right click to solution explorer and then add new Item and add App.Config file and in that there is tag for connection string same as in web application.