Get connectionString for current DB - c#

I'm trying to find out connectionString which would be like: TestDB.Properties.Settings.TestDBConnectionString (according to this video), but I'm working with WPF and there is no <connectionStrings> in App.config.
I looked at properties of my DB and there was Connection String such as Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=//path_to_file//TestDB.mdf;Integrated Security=True - but it's not the same type was mentioned above. And it won't work for my connection below.
I'm trying to connect like this:
public partial class MainWindow : Window
{
string connectionString;
public MainWindow()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["data_here"].ConnectionString;
}

What you are looking for are ApplicationSettings.
You could create thos via RightClick on your WPF-Project->Add-> Application Settings.
In there you can add ConnectionStrings
You could use it like this:
string con = YourProjectNamespace.Properties.Settings.Default.YourSettingsPropertyKey;
OR
you add them manually to your app.config-file:
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="NameOfConnectionString" connectionString="actualConnectionString" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
You can access them like this:
string appName = "YourAppName.exe";
Configuration config = ConfigurationManager.OpenExeConfiguration(appName);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
string x = section.ConnectionStrings["nameofyourConnectionstring"];
If you need help creating working connectionstrings visit ConnectionStrings.com

Related

ConnectionString with external file for SqlConnection

C# on VisualStudio 2017. Windows Forms Application.
Hi all. I've read on the web that is not possible to use an .udl file in which write a ConnectionString for a SqlConnection. Is that true at today? And, if yes, there is an alternative way to use an external file for a ConnectionString in SqlConnetion?
I have to run project in 5 PCs that have different connection strings, for example:
PC1) Data Source=PCNAME\SQLEXPRESS;Initial Catalog=DBNEW;User ID=sa;Password=123;
PC2) Data Source=SERVER\SQLEXPRESS;Initial Catalog=DB;User ID=sa;Password=999;
[...]
Currently I use a string inside the project
string connSQL = "Data Source=.\\SQLEXPRESS;Initial Catalog=DBNEW;Persist Security Info=True;User ID=sa;Password=123;";
that I have to change five times for the five PCs' different connection.
I've tried anyway to connect with an .udl file
string connSQL = "Data Source=.\\SQLEXPRESS;AttachDbFile=C:\\connstring.udl";
that contains this
[oledb]
; Everything after this line is an OLE DB initstring
Data Source=PCNAME\SQLEXPRESS;Initial Catalog=DBNEW;Persist Security Info=True;User ID=sa;Password=123;
but of course it doesn't works.
Any ideas for an alternative solution?
Finally I found a solution. Thanks also to MethodMan's comment I later realized that you can use an external file to compile the connectionString, that is MyProjectName.exe.config, which is saved in the same directory as the software exe, and which has the same functions and settings of the App.config.
So what I did is create a new FormConn where you manually enter data for the connectionString, overwrite them in MyProjectName.exe.config and link this file to Form1 for SQL database management. Below the code.
In the Form1.cs:
using System.Configuration;
public Form1()
{
//Check if a connectionString already exists
//To the first slot there is a system configuration so 1 = no custom connectionString
if (ConfigurationManager.ConnectionStrings.Count == 1)
{
FormConn frmConn = new FormConn();
frmConn.ShowDialog();
try
{
//Restart Form1 in the case connectionString has changed
Application.Restart();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Associates the custom connectionString to the string I will use in the code for operations that are connected to the DB.
StringSQL = ConfigurationManager.ConnectionStrings[1].ConnectionString;
}
In the FormConn.cs:
using System.Configuration;
using System.Reflections;
string appPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string appName = Environment.GetCommandLineArgs()[0];
string configFile = System.IO.Path.Combine(appPath, appName + ".config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
var sezione = (ConnectionStringsSection)config.GetSection("connectionStrings");<br>sezione.ConnectionStrings["MyProjectName.Properties.Settings.MyDataSetConnectionString"].ConnectionString = "Data Source=" + txtDataSource.Text + ";Initial Catalog=" + txtInitialCatalog.Text + ";Persist Security Info=True;User ID=" + txtUserID.Text + ";Password=" + txtPassword.Text + ";";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
this.Close();
And that's what I have inside my MyProjectName.exe.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="MyProjectName.Properties.Settings.MyDataSetConnectionString"
connectionString="Data Source=MyPcName\SQLEXPRESS;Initial Catalog=DB-1;Persist Security Info=True;User ID=sa;Password=123psw321"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
This worked for me!

Cannot access connection string in app.config by using c#

App.config file configuration 1
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=223.29.207.133;
Initial Catalog=MBV5DBLive;User ID=smsuser;Password=sms;IntegratedSecurity=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
App.config file configuration 2
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=localhost;
Initial Catalog=University;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
C# code
try
{
String constring = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
}
}
catch (Exception ex)
even if i debug when it comes to configuration manager code will jump to catch block and it will show "Object reference not set to an instance of an object."
What is the issue with above both configuration files?
Your connection string name seems like c_str not MyDBConnectionString.
And since you don't have any MyDBConnectionString in your web config, your ConfigurationManager.ConnectionStrings["MyDBConnectionString"] returns null and that's why you get NullReferenceException when you try to access ConnectionString property of a null reference.
If everything is okey other than that, this should work;
var constring = ConfigurationManager.ConnectionStrings["c_str"].ConnectionString;
using (var con = new SqlConnection(constring))
{
}

connection.open hanging/freezing. What is wrong with my connection string?

I wanted to make my connection string dynamic so I don't have to recompile my code for each new user.
my old connection string:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Storm\documents\visual studio 2015\Projects\SeaSideBlissVersion2\SeaSideBlissVersion2\ShopDb.mdf";Integrated Security=True
My config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ConnString"
connectionString="Data Source=.;Initial Catalog=ShopDB;Integrated Security=True"/>
</connectionStrings>
</configuration>
and then some code in my db class:
class DB
{
static string conn;
static SqlConnection _conn;
public DB()
{
conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
_conn = new SqlConnection(conn);
}
public void dbAddItem(string name, string measurement, string PLU)
{
string query = string.Format("INSERET INTO tblItems (ItemName, Measurement, Stock, PLUNumber) VALUES ({0}, {1}, {2}, {3})", name, measurement, 0, PLU);
_conn.Open();
SqlCommand comm = new SqlCommand(query, _conn);
comm.ExecuteNonQuery();
_conn.Close();
}
}
And used the following references:
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
When I call my dbAddItem method it seems to hang at _conn.Open()
I'm assuming there's something wrong with my connection string? I've looked it up and nothing that I found helped.
Seems The mistake was obvious, once I put my .mdf db into the debug folder it worked. It makes sense because there is no "exact" directory to look in.
It seems that you missed login info to the DB in the connection string.
Something like "uid=xxx;pwd=xxx".

Using a connection string in a app.config file in a .cs file

I've got a connection string to my database in a my app.config file. I want to using the app.config file rather than copying and pasting the string in the section i want to use it is.
My app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="|DataDirectory|\SVN .mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and my .cs file is currently like this:
private void sendToDB_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=username;" +"password=password;server=serverurl;" + "Trusted_Connection=yes;" + "database=database; " + "connection timeout=30");
}
I know that this is wrong but want to use the config file instead.
Can anyone help me in how I would go about doing this.
var connectionString=ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
Note : try to keep the name of the connectionstring simpler for readability purposes.
Also,Your assembly also needs a reference to System.Configuration.dll
If you want to access the ConnectionStrings property of your application-configuration file, you have to ...
add a reference to the System.Configuration-dll.
add this to the top of the file:
using System.Configuration;
Then you can access it in this way:
string conStr = ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
using(var con = new SqlConnection(conStr))
{
// ...
}

How can I make LINQ to SQL use a connection string which is being modified at runtime?

I'm experimenting some difficulties trying to use Connection String Builders (ADO.NET) within LINQ to SQL. Let me show you guys what I'm trying to do:
the app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="LoremIpsum"
connectionString="Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and a snippet of the form:
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["LoremIpsum"];
if (null != settings)
{
string connection = settings.ConnectionString;
SqlConnectionStringBuilder builder =
new SqlConnectionStringBuilder(connection);
// passwordTextBox being the control where joe the user actually
// enters his credentials
builder.Password = passwordTextBox.Text;
}
LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext();
// finally some rather anecdotic LINQ sentence here:
var foo = db.Table.Single(bar => bar.Table == whatever);
On the other hand checking the Immediate Window:
?builder.ConnectionString
"Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;Password=swordfish"
I'm always getting an exception: Login failed for user 'joe'. Any ideas? Thanks much in advance.
It seems like you are trying to modify the connection string that is stored in the app.config file. When you use a no argument constructor for your data context, it reads what was configured at design time.
Try injecting your modified connection string into the constructor of the DataContext:
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"];
SqlConnectionStringBuilder builder;
LINQTOSQLDataClassDataContext db;
if (null != settings)
{
string connection = settings.ConnectionString;
builder = new SqlConnectionStringBuilder(connection);
// passwordTextBox being the control where joe the user actually enters his credentials
builder.Password =passwordTextBox.Text;
db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
} }
You're forgetting to send in the connectionstring to the DataContext constructor.
Example:
LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);
You can force a DataContext to use a specific connection string with
DataContext db = new DataContext(myConnectionString);
The parameterless DataContext constructor will use a connection string from the App.config file first, then the connection string set at compile time.

Categories