Is it possible use App.config's value in Connectionstring. Example is mentioned below.
<appsettings><add key="UserName" Value="abc" /></appsettings>
<connectionstring><add name="Conn" connectionString="Server=test; Database=test; Uid=UserName; Pwd=test123;" />
So as you can see that I have defined the Username in appsettings and I want to see that into the connection string
Any help is appreciated.
As I know, it's impossible.
You can use different App.config files for different configuration (Debug, Release) and set your connection string in them.
Look here or here
You can use String.Format().Just change Uid=UserName; to Uid={0};".
String connectionString = String.Format(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString, ConfigurationManager.AppSettings["UserName"].Value);
Related
Curious to know if there is a way to read in some parameters of the connectionstring within the web.config file? For example, if I had a Settings page on my website for administrators only, and one of the views within there was to show the name, providerName, and connectionString... could I do this?
<add
name="DbConnectionString"
providerName="System.Data.SqlClient"
connectionString="Data Source=yourservernamehere.net
/>
Curious to know if there is a way to read in some parameters of the connectionstring within the web.config file?
Yes.
For example, if I had a Settings page on my website for administrators only, and one of the views within there was to show the name, providerName, and connectionString... could I do this?
Yes. You can do the same:
using System.Configuration;
string yourConnectionString = ConfigurationManager.ConnectionStrings["yourConnectionStringNameInYourConfigFile"].ConnectionString;
First step was to ensure using System.Configuration is declared.
SqlConnection dbConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnectionString"].ToString());
lblDBConnName.Text = dbConn.DataSource.ToString();
I am using the entity-framework with Code First approach and I have a custom DbContext.
My connectionstring is defined in the ServiceConfiguration.Cloud.cscfg and ServiceConfiguration.Local.cscfg files.
public CustomContext()
: base("dbActivity")
{
...
When the above code executes, it tries to check my web.config and not the ServiceConfiguration file from an azure solution.
UPDATE:
Here is my connectionString in the ServiceConfiguration file:
<ConfigurationSettings>
<Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="UseDevelopmentStorage=true" />
<Setting name="dbActivity" value="Server=tcp:xxx.database.windows.net,1433;Database=ra;User ID=user;Password=password;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" />
</ConfigurationSettings>
Exception:
No connection string named 'Server=tcp:xxx.database.windows.net,1433;Database=ra;User ID=user;Password=password;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;' could be found in the application config file."
Is it possible to make it check the ServiceConfiguration.Local.cscfg instead?
Finally I found the solution. It's necessary to use the SqlConnectionStringBuilder class.
public RAActivityContext()
: base((new SqlConnectionStringBuilder(
CloudConfigurationManager.GetSetting("dbRAActivity")).ToString()))
{
}
There is an overloaded constructor that takes an actual connection string.
This should do the trick:
public CustomContext()
: base(CloudConfigurationManager.GetSetting("dbActivity"))
{
// stuff here
}
Of course, the setting contains the (full) connection string.
I don't know it you can directly load it from a different config but there is a constructor for dbcontext that takes a connection string as input.
string connectionString = LoadFromConfig();
var context = new CustomContext(connectionString );
I needed to do this, but wasn't able to change the actual DbContext constructor as it was in a shared library that was also used by projects that used an app.config. I ended out coming up with an alternative solution which was to programatically modify the app.config connection string inside the worker role itself.
See this for a way to do that: Change connection string & reload app.config at run time
The code I used was
string databaseConnectionString = CloudConfigurationManager.GetSetting("dbActivity");
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection) config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["dbActivity"].ConnectionString = databaseConnectionString;
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
For this to work you need to have an empty connection string inside the app.config for which it will overwrite
<connectionStrings>
<add name="dbActivity" connectionString="" providerName="System.Data.SqlClient" />
</connectionStrings>
I've been trying to set a connectionstring to the users programdata folder and followed the first step in the answer of this post:
%APPDATA% in connection string is not substituted for the actual folder?
Unfortunately I can't get it to work:
In the onstartup method of my WPF application I run the following:
AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
var test = AppDomain.CurrentDomain.GetData("DataDirectory");
var connection = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
Value in App.config
<add name="Conn" connectionString="data source=|DataDirectory|\mydb" providerName="System.Data.SQLite" />
result of test = "c:\programdata" => this is good
result of connectionstring ="|DataDirectory|\mydb" => this is not good
I'm expecting: "c:\programdata\mydb"
I've been looking all around... what am I doing wrong?
thanks in advance,
You are misunderstanding how it works.
Setting the DataDirectory is correct, but the actual connectionstring is not changed on file.
When you open the connection the |DataDirectory| part of the string will be replaced with your path
You just need to try and see by yourself
If you're following the answer you linked to, you seem to be missing the following from Step 2. in the link:
return connection.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
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
I've found out how to use the |DataDirectory| in the connection string to set the directory where my wpf app's database file resides, but I wish to go a little further.
As stated in the msdn SqlConnection.ConnectionString Property,
The path may be absolute or relative by using the DataDirectory substitution string. If DataDirectory is used, the database file must exist within a subdirectory of the directory pointed to by the substitution string.
Now, i want to set the full location, not just the DataDirectory, with a custom DatabaseLocation attribute which is controlled by the application and thus I won't need to handle the connection string.
In other words, my connection string will go from this:
connectionString="Data Source='|DataDirectory|\database.sdf'" providerName="System.Data.SqlServerCE.4.0"
into this:
connectionString="Data Source='|DatabaseLocation|" providerName="System.Data.SqlServerCE.4.0"
and in the code, I'll read the user configuration and set the convenient data to the proper location:
AppDomain.CurrentDomain.SetData("DatabaseLocation", someVarWithDatabaseLocation);
This way I'll not need the content of the someVarWithDatabaseLocation from the user interface to the business down to the dataaccess and create a connection string.
Is this possible, or only the |DataDirectory| magic tag is treated by the connection string builder?
Thank you
Well. There isn't.
After decompiling System.Data (sorry) and analysing the available ConnectionString constructors I saw that there is only ExpandDataDirectory and it has hardcoded to the
const string DataDirectory = "|datadirectory|";
So... only datadirectoy is handled...