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!
Related
I store the connection string, username, password in a connectionString.config file. Is there a way to decrypt all of these values and then connect as I would normally if the values weren't encrypted?
All suggestions welcome as I'm not sure where to go from here as I didn't find the Microsoft docs very helpful.
connectionString.config
<connectionStrings>
<add name="as400"
connectionString="DataSource=AgIrRzkARUJsQBUYXKCPpH8MdqtQ5Sd+lt4kyBEZBY=; userid=tRGgY7PERBTg2WPPzVerIlMP93kmQbTSuKsJKyDHFU=; password=kMxEGU75lJ1VD5OaaujnLzleR/7ZQDco3kddfwTOvI=;"/>
</connectionStrings>
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<appSettings file="AppSettings.config"/>
<connectionStrings configSource="connectionStrings.config"/>
</configuration>
application code
//Open connection to the iSeries
iDB2Connection cn = new iDB2Connection();
cn.ConnectionString = ConfigurationManager.ConnectionStrings[database].ConnectionString;
In order to make SQL connection, you need to first decrypt connection string, below code will guide you in right direction.
DataSet dsConnection = new DataSet();
dsConnection.ReadXml(System.Web.Hosting.HostingEnvironment.MapPath("~/ConnectionString.Config.xml"));
String connection = dsConnection.Tables[0].Rows[0]["connectionstring"].ToString();
SqlConnectionStringBuilder DBConfig = new SqlConnectionStringBuilder(connection);
string ConnectionString = "Data Source=" + Decrypt(DBConfig.DataSource) + ";Initial Catalog=" + Decrypt(DBConfig.InitialCatalog) + ";User ID=" + Decrypt(DBConfig.UserID) + ";Password=" + Decrypt(DBConfig.Password);
iDB2Connection cn = new iDB2Connection();
cn.ConnectionString = ConnectionString;
First you need to create Decrypt function for AES encryption, then you can call that function like the above code.
Thanks,
Selvakumar S
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 to add this C# code connection string in app.config file for windows forms application program ?
i see examples of adding access db but i need to add excel file data , so can't find previous question on excel file connection in app.config.
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx" + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";
Try this in web config file-
<connectionStrings>
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0'" />
<add name="ConnStrName" connectionString="Data Source=database;Initial Catalog=database-name;Persist Security Info=True;User ID=your username;Password=your password" />
</connectionStrings>
i solved this myself .
app.config settings :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MSIDConn"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0'"
providerName="System.Data.OleDb" />
</connectionStrings>
</configuration>
added these 2 lines in Form1.cs
using System.Data.OleDb;
using System.Configuration;
in button click event :
private void button1_Click(object sender, EventArgs e)
{
string excelconn = ConfigurationManager.ConnectionStrings["MSIDConn"].ConnectionString;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = excelconn;
OleDbCommand command9 = new OleDbCommand
(
"SELECT P1, P2, P3 " +
" FROM [PE_Actual$] ", conn
);
DataSet ds9 = new DataSet();
OleDbDataAdapter adaptor9 = new OleDbDataAdapter(command9);
adaptor9.Fill(ds9, "testtable");
dataGridView1.DataSource = ds9.Tables[0].DefaultView;
}
Usually they sit in a section on their own:
<connectionStrings>
<add name="myConnectionName" providerName="myProvider" connectionString="Data Source=D:\MISD_report.xlsx;Extended Properties=Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0" />
</connectionStrings>
I do not know what the providerName for OLE/ Excel is or what name to use so the provider finds the correct connection string.
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SQLiteConnection connString = new SQLiteConnection(connectionString);
using (var command = connString.CreateCommand())
{
try
{
connString.SetPassword(ConfigurationManager.AppSettings["password1"]);
connString.Open();
connString.ChangePassword((String)null);
connString.ChangePassword(ConfigurationManager.AppSettings["password2"]);
connString.Close();
connString.Dispose();
}
catch (Exception e)
{
Console.Write(e.Message + "\n" + e.StackTrace);
}
}
I'm trying to test SQLite by having a simple console application. I'm using an app.config file to read passwords and connection string from. The code is able to set the password the very first time it runs but if I open the connection and try to change password by calling ChangePassWord() method, the password is not changed. I also try to set password to null and then reset it to some new password, but that doesn't work either.
The error is
File Opened that is not a database file. File is encrypted or is not a database
Some other people have the same problem: ChangePassword method problem.
I'm not 100% sure. But for some reason reading the connection string from the app.config could have some bearing on it. I took out the connection string and decided to hardcode it like so
SQLiteConnection connString = new SQLiteConnection("data source=\".\\SomeDatabase\"");
before was like so:
<connectionStrings>
<add name="connection"
connectionString="data source=".\SomeDatabase""
providerName="System.Data.SQLite" />
</connectionStrings>
Hope this helps somebody
Somethings like :
if(Request["connectionToUse"] + "" == "constr1")
// use a connection string 1
else
// use a connection string 2
is it possible on .NET?
Have two connection strings in your web.config and simply reference the one you want to use:
<connectionStrings>
<add
name="conn1" connectionString="..."
providerName="System.Data.SqlClient"
/>
<add
name="conn2" connectionString="..."
providerName="System.Data.SqlClient"
/>
</connectionStrings>
if(Request["connectionToUse"] + "" == "constr1")
return ConfigurationManager.ConnectionStrings["conn1"];
else
return ConfigurationManager.ConnectionStrings["conn2"];
Update:
I don't recommend writing to your web.config based on passed in parameters - not only does this look like it can cause a security issue (especially if you simply use the passed in parameters).
Any changes to the web.config will reset the application, causing all users of it to drop - the application pool restarts when the file changes.
EDIT: This is probably a very bad idea, as said by Oded, but if you really want to then :
modify the webconfig based on the request parameter look at the following example:
string strDevConnection = #"Data Source=DEVELOPMENT\SQLEXPRESS;Initial Catalog=sqlDB;Persist Security Info=True;User ID= ;Password= ";
string strLiveConnection = #"Data Source=PRODUCTION\SQLEXPRESS;Initial Catalog=sqlDB;User id= ;password= ";
Configuration myWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (Request["connectionToUse"] + "" == "constr1")
{
myWebConfig.ConnectionStrings.ConnectionStrings["constr1"].ConnectionString = strDevConnection; //constr1 is the name of the current connectionstring in the web.config
}
else
{
myWebConfig.ConnectionStrings.ConnectionStrings["constr2"].ConnectionString = strLiveConnection;
}
myWebConfig.Save(); //Save the changes to web config