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...
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();
So, I'm writing a program that imports excel files to a database, finds matches, non matches, shows the tables, etc.
In the beginning I added manually just my database connection string, but I have to make my program let the connection string change.
In case none is inserted, it will use the last one inserted.
Behind code:
protected void BtnFazerTudo_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
connectionString = connectionString.Replace("{username}", TxtUtilizador.Text);
connectionString = connectionString.Replace("{pwd}",TxtPalavraPasse.Text);
connectionString = connectionString.Replace("{DataSource}", TxtHost.Text);
connectionString = connectionString.Replace("{Initial}", TxtBaseDeDados.Text);
Debug.Write(con);
}
Web Config:
<add name="Db" connectionString="Data Source ={DataSource} ;Initial Catalog=
{Initial};Persist Security
Info=True;User ID={username};Password={pwd}"/>
I already tried the String builder. I was able to output it in the debug window but I have no idea in how I transfer that connection made by string builder to other web forms.
The connection string you're creating needs to be stored somewhere so as all pages of your web application can access it. While there are some choices that let you pass data among pages none of them suits you mainly because (a) the connection string contains security sensitive information such as the password!!! and (b) they do not offer the level of persistence required by your scenario (unless you want the user to fill the textboxes every time he connects to your application).
Having said that, one viable option is to store the connection string in a database and retrieve it every time you need it. You can either store it as a whole string or each user data separately (i.e catalog, user id, password etc). In the latter case, you'd have to re-create the connection string every time you need it.
How you create the connection string has nothing to do with your original question. It is just about string concatenation in C# for which you can use the + or += operators, string interpolation or the String.Format, String.Concat, String.Join or StringBuilder.Append methods.
public void DatabaseConnection()
{
connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source =..\\..\\TaxApp.accdb;Persist Security Info=False");
connection.Open();
}
If you're in a language that allows you to construct the path, such as C#:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
will, by default, give you the path to c:\ProgramData folder, which is shared among all users.
So:
string AccessDbPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"YourAppFolder\\TaxApp.accdb");
Usually you don't store fixed paths in your code. This will make your application very difficult to install on your customers PCs.
Knowing this, the NET framework provides an infrastructure to store this kind of informations in external XML based file (named yourexename.exe.config when you release the application and simply app.config inside your project).
You can store there this kind of information that need to be changed on a customer by customer base.
So you app.config could have a section made in this way
<appSettings>
<add key="DatabasePath" value="C:\programdata\MyApp\Database.accdb" />
</appSettings>
Inside your program you could read and use this value using this code
string dbFile = ConfigurationManager.AppSettings["DatabasePath"].ToString();
connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data source =" + dbFile +
";Persist Security Info=False");
You could even store the whole connection string using the project properties menu and adding a new entry of type ConnectionString in the Settings page.
Again, what you type there will be stored in the app.config file in a specific section
<connectionStrings>
<add name="MyDb" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
Data source=C:\programdata\MyApp\Database.accdb;
Persist Security Info=False";/>
</connectionStrings>
and you can read it with
string myConnectionString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
See ConfigurationManager class on MSDN
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));
So here's the what's up. I just created and "published" a staff management tool in Visual C#. During development, I used a string saved in Properties.Settings.Default to connect to the database I was using for development. Now since the solution is published and ready to go, the boss wants to connect to the real staff database. I was under the impression that connection to the new database would be as simple as changing the connection string in some properties file somewhere. Unfortunately I can't seem to find the proper file/string to connect to the database I want to. Any ideas?
Thanks!
JB
Look here:
Connection Strings and Configuration Files
By using a config file you just have to change the config file connection string once your application has been deployed.
Here's a way of doing what you want:
From http://www.dreamincode.net/forums/topic/70745-connection-string-in-appconfig/
Your config file content:
<connectionStrings >
<add name="YourName"
connectionString="Provider=msdaora;Data Source=MyOracleDB;Persist Security Info=False;Integrated Security=Yes;"
providerName="System.Data.OracleClient" />
</connectionStrings>
Method to get the connection string at runtime:
public static string GetConnectionString(string strConnection)
{
//Declare a string to hold the connection string
string sReturn = new string("");
//Check to see if they provided a connection string name
if (!string.IsNullOrEmpty(strConnection))
{
//Retrieve the connection string fromt he app.config
sReturn = ConfigurationManager.ConnectionStrings(strConnection).ConnectionString;
}
else
{
//Since they didnt provide the name of the connection string
//just grab the default on from app.config
sReturn = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString;
}
//Return the connection string to the calling method
return sReturn;
}
Using the method:
string connectionString = GetConnectionString("YourName");
I've had to change the entry in the Properties.Settings text file, recompile and redeploy to get the new connectionstring to take. In the future consider reading your connection string from your .config file under either the ConnectionStrings or AppSettings node. When you store it there you simply need to change a production text file to switch your database...