Dynamically Provide Username and password to Connection String - c#

I am using C# winform application using MySql as back-end database. Using App.config file, application read connection string to connect database as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionstring>
<addkey="MySQL.DB"value="server=localhost;database=mysqldbname;user=username;password=12345678;">
</add>
</connectionstring>
</configuration>
Is there any way that we can provide username and password not from App.config but from user of application, by entering username and password? so that we are able to protect sensitive data. Other information are ok to read from app.config like database name, server etc.
Ahmed

you can have appSettings
<appSettings>
<add key="ConFormat" value="server=localhost;database=mysqldbname;user={0};password={1};"/>
</appSettings>
read it and set the values
var formatString = ConfigurationManager.AppSettings["ConFormat"].ToString();
var conString = string.Format(formatString , SecureUserName, SecurePW);

If you're using raw ADO.NET then you can use a connection string builder, presumably a MySqlConnectionStringBuilder in your case. Create a new instance with the connection string from the config file, set the appropriate properties and then get the result from the ConnectionString property.
By the way, you can store passwords and other sensitive data in the config file using Protected Configuration to encrypt it.

Change the code in app.config like this
<add key="MySQL.DB"value="server=localhost;database=mysqldbname;user=&usernamefromuser;password=&passfromuser;">
Add a button for connecting and 2 textboxes for username and password
Buttons code :
//other code for mysql variables ...
string connectionStr= connStrFrom_App_Config.Replace("&usernamefromuser",texBox1.Text).Replace("&passfromuser",textBox2.Text);
//other code for connecting

Related

How do I get a list of all connection strings in app.config

In need to create an small console app, that takes two arguments:
File location for app.config file.
passkey
My problem is that the console app needs to read the connectionStrings and Encrypt it and then save the encrypted text to the config file. I have looked, but have not found any solution for it.
My app.config file could look like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="Conn1" connectionString="Data Source=Database1;Initial Catalog=DB12;User ID=User1234;Password=Qwerty123" providerName="System.Data.SqlClient" />
<add name="Conn2" connectionString="Data Source=Database2;Initial Catalog=DB12;User ID=User1234;Password=Qwerty123" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
I have the encryption part are done. I just need to in this example to read those two connectionstrings and encrypt them each. Please note that the name of the connectStrings are different every time, since the console app are triggered by TFS build server.
Basically you don't really need the name of the Connection String but the connection itself. I believe you just need to go thru them with foreach and for each iteration you can get the connectionString till the last one in the app.config.
foreach (System.Configuration.ConnectionStringSettings css in System.Configuration.ConfigurationManager.ConnectionStrings)
{
string connectionString = css.ConnectionString;
// encryption part
// rewriting the connectionString in the app.config or however you want ot be done
}
You mentioned you got the encryption part done and all you need is reading the strings.
Hope it helps!
If you donĀ“t know the name of the connection string, you could try it like this:
ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
if (connections.Count != 0)
{
//go trough all available ConnectionStrings in app.config
foreach (ConnectionStringSettings connection in connections)
{
//reading the ConnectionString
string conString = ConfigurationManager.ConnectionStrings[connection.Name].ConnectionString;
//writing the ConnectionString
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[connection.Name].ConnectionString = EncryptConfig(conString); //just call your Encryption part here instead of "EncryptConfig()"
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
}
}
Use ConfigurationManager class like
ConfigurationManager.ConnectionStrings["Conn2"].ConnectionString
came up with this to work with both app and web, note i did also need to change the values and save them to disk so couldn't just loop through
var appConfig = System.Web.HttpContext.Current == null
? ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
: System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var needsToSave = false;
foreach (var appCon in appConfig.ConnectionStrings.ConnectionStrings.Cast<ConnectionStringSettings>())
{
//do stuff
}

app.config exception SqlConnection without connection string

Here is my problem: I have a simple C# console app and I open my connection with
SqlConnection conn = new SqlConnection("Data Source=server;" + "Initial Catalog=database;" + "User id=sa;" + "Password=pass;timeout=60;");
That works fine. I added the app.config with some keys in the AppSettings. That works fine too.
But if I add a new tag to the config, the previous code gives me exception...why?!
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="template" value="value"/>
<add key="saveas" value="value"/>
</appSettings>
<tag>
</tag>
</configuration>
You cannot just add a random tag to your config file. The config file is parsed by the runtime and the runtime has to understand it.
If you want to do something with your custom tag, it might be helpful to ask a question about that (make sure you search existing questions before you do), because there are different ways to reach what you want (for example custom configuration sections). But until then, the quickest solution to make your problem go away is to simply delete the tag tag from your configuration file.
I'm not sure how you plug your connection string into your data handler. If you are using Linq, your project should have updated with the connection settings in the app.config automatically. I update my app.config during publication.
Here is a sample of what my config looks like. perhaps it will give you what you need. You can see how I added my own "tag" called ConnectivityDatabase and SysDatabase.

load config from app.config if available

Im new to C# .net programming and sorry if I ask stupid question.
I have setup my programs to load setting from database instead off app.config.
However, I want it to replace the setting from app.config if only the setting available in it.
For example, the setting that will load from database is
IP_address = 192.168.0.111
folder_path = /share
pc_name = pc_dev
username = developer
password = developer123
then in app.config I will insert this value
IP_address = 192.168.0.222
the program will then change the IP_address value that it load from database to the value that I insert in app.config
is there anyway to do this?
Thank you
Easiest way is to use your app.config's appSettings. Add a reference to System.Configuration.
Then your app config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ipAddress" value="192.168.0.222"/>
</appSettings>
</configuration>
Then in your code, get the value from the config by using this:
string ipAddFromConfig = System.Configuration.ConfigurationManager.AppSettings["ipAddress"]; // get the value from the appsettings.
Then you can replace the value that you got from your DB.

How to store connection string in WinForms application?

I have an application that consists of two forms. One form displays data returned from the database in fields and the other form opens a windows that allows the user to select which database to get the data from.
Currently, the application doesn't store the user's choice of database. I want to store what the currently selected connection string is each time the user selects the database they want to use in form2.
What is the best way to do this? If I made an instance of an object of a static class to store this information, would that persist the data for use on each form?
You should have an app.config configuration file, and in there, define a <connectionStrings> section:
<configuration>
<connectionStrings>
<add name="YourNameHere"
connectionString="server=.;database=AdventureWorks;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>
You then add a reference to System.Configuration to your project, and then you can easily retrieve those connection strings:
string connStr = ConfigurationManager.ConnectionStrings["YourNameHere"].ConnectionString;
using(SqlConnection connection = new SqlConnection(connStr))
{
// do something here....
}
You could store the connection string in App.config and retrieve it like this:
string connStr = ConfigurationSettings.AppSettings["ConnectionString"];
public SqlConnection conn = new SqlConnection(connStr);
Example App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=./SQLEXPRESS;Initial Catalog=DB;Integrated Security=SSPI;" providerName="Microsoft.SqlClient" />
</connectionStrings>
</configuration>
I would be tempted to use Application Settings for this purpose.
http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx
This is a recommended place to keep your connection strings :-)
Though there are built-in .NET capabilites to store user related information (via Registry, config files, settings etc.) they seem to be too heavy.
I would recommend to use plain text file and keep it in user folder:
var userPath = Environment.GetFolderPath(Environment
.SpecialFolder.ApplicationData);
var filename = Path.Combine(userPath, "mysettings");
// Read connection string
var connectionString = File.ReadAllText(filename);
// Write connection string
File.WriteAllText(filename, connectionString);
Also note that hardly users will have fun working with connection strings. They would prefer to specify database name, server, username etc. using separate form fields. To map those fields to connection string you may use SqlConnectionStringBuilder class (if you are working with MSSQL Server):
// to connection string
var connectionStringBuilder1 = new SqlConnectionStringBuilder();
connectionStringBuilder1.DataSource = "server";
connectionStringBuilder1.InitialCatalog = "database";
var connectionString = connectionStringBuilder1.ConnectionString;
// from connection string
var connectionStringBuilder2 = new SqlConnectionStringBuilder(connectionString);
var serverName = connectionStringBuilder2.DataSource;
var databaseName = connectionStringBuilder2.InitialCatalog;

How to obtain app.config of a different application and modify it

I have two windows application. eg ., FormA and FormB
The app.config of FormA is as below
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="company" value="DSRC"/>
</appSettings>
<connectionStrings>
<add name="test" connectionString="Testing Connection String"/>
</connectionStrings>
</configuration>
Now I have another application named as Form B.
I want to retrieve both appsettings and connectionstrings of Form A into Form B.
Further I should be able to modify both of these appsettings and connection strings and save it into the Form A.
I know how to retrieve the appsettings , and connection strings of the same application and modify.
But how do I obtain of some other application and modify the same.
Kindly do let me know.
Actually I have 4 windows services running under one setup., one webservice and one wcf service and one application.
All these have different app.configs, comprising of different appsettings and different connection strings.
I am supposed to create a windows application that will retrieve each of these settings and then save it accordingly.
I tried upto this level
ExeConfigurationFileMap filename= new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = #"D:\Home\FormA\FormA\bin\Debug\FormA.exe.config";
Configuration config =
ConfigurationManager.OpenMappedExeConfiguration(filename,
ConfigurationUserLevel.None);
But then just got struck, I just do not know how to proceed further (Sounds dumb right !)
Can anyone help me proceed down the way.
Regards
cmrhema
Basically, you need to open the configuration for that other executable something like this:
// full path to other EXE, including EXE extension - but *NOT* .config !!
string otherExePath = #"C:\........\OtherApp\bin\Debug\OtherApp.exe";
Configuration otherConfig =
ConfigurationManager.OpenExeConfiguration(otherExePath);
and then you can access all the settings on the new otherConfig configuration:
string otherSetting = otherConfig.AppSettings.Settings["TestSetting1"].Value;
and you can also save it back (provided you have the necessary permissions to that directory).
otherConfig.Save():
ExeConfigurationFileMap fileMap2
= new ExeConfigurationFileMap();
fileMap2.ExeConfigFilename = #"OtherFile";
Configuration config2 =
ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
ConnectionStringSettings newSettings =
config.ConnectionStrings.ConnectionStrings["oldSConString"];
ConnectionStringsSection csSection
= config2.ConnectionStrings;
csSection.ConnectionStrings.Add(newSettings);
config2.Save(ConfigurationSaveMode.Modified);
VS2005 C# Programmatically change connection string contained in app.config

Categories

Resources