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
Related
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!
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))
{
}
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".
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.