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;
Related
I have a website and have multi domain point to this.
In my website code when use access to web, I use ConfigurationManager to change Connect string base every domain. Code bellow
Session["Key"] = "KeyID";
var connectionStringsSection = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
string fullConnect = "New String Connnect";
connectionStringsSection.ConnectionStrings["Name"].ConnectionString
= fullConnect;
configuration.Save();
ConfigurationManager.RefreshSection("connectionStrings");
But I lost every Session variable initialization before Connect string change (like Session["Key"]).
How can i do that but kip my Session variable?.
If you update connection string in Web.config file then session will surely destroy. To prevent this, set multiple connection strings in Web.config file and whichever connection string you want, you can manage it in .cs file.
<connectionStrings>
<add name="String1"
connectionString="CONNECTION STRING1"
providerName="System.Data.SqlClient" />
<add name="String2"
connectionString="CONNECTION STRING2"
providerName="System.Data.SqlClient" />
</connectionStrings>
You can get connection in code using "ForEach" loop.
foreach (ConnectionStringSettings cstring in System.Configuration.ConfigurationManager.ConnectionStrings)
{
//use cstring.name
}
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 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
When using WPF and entity-framework I have an APP.CONFIG that looks like the following:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=%APPDATA%\Folder\Database.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
When using this code it always throws the following error:
System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlServerCe.SqlCeException: The path is not valid. Check the directory for the database. [ Path = %APPDATA%\Folder\Database.sdf ]
When I run the path "%APPDATA%\Folder\Database.sdf" from the command prompt it works fine, and if I remove "%APPDATA% and hardcode the path it works fine - so it looks simply like the %APPDATA% is just not being substituted for the actual folder...
Thanks,
As you already reallized, %APPDATA% or any other environtment variables are not replaced with their respective value in connection strings. Environment varialbes are something related to the operating system shell. They work in command prompt because the command prompt explicitly parses the values entered and substitutes environment variables. That's not something that .NET Framwork usually performs.
To achive this, you have to manually provide the value for %APPDATA% (using Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) or Environment.GetEnvironmentVariable("APPDATA")). There are two options:
Change your connection string and use |DataDirectory|:
<connectionStrings>
<add name="DatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\Database.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
(Notice the use of |DataDirectory| in the path to the database file.)
Then provide the value for |DataDirectory| in your application's Main method:
AppDomain.CurrentDomain.SetData("DataDirectory",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
Refer to this MSDN page for more information.
Manually provide the connection string for your ObjectContext class. This way you can parse and change the connection string:
public static string GetConnectionString()
{
var conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseEntities"].ConnectionString;
return conStr.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
And later:
var db = new DatabaseEntities(GetConnectionString());
Or subclass you ObjectContext class and always use the new connection string:
public class MyDatabaseEntities : DatabaseEntities
{
public MyDatabaseEntities()
: base(GetConnectionString())
{
}
public static string GetConnectionString()
{
var conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseEntities"].ConnectionString;
return conStr.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
}
and use the new class anywhere.
I have another option. We don't need to replace anything. I am using below connection string without any replace and it's working fine.
<connectionStrings>
<add name="ProjectManagementDBEntities" connectionString="metadata=res://*/Models.ProjectManagementModels.csdl|res://*/Models.ProjectManagementModels.ssdl|res://*/Models.ProjectManagementModels.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\ProjectManagementDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
Main change is data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\ProjectManagementDB.mdf;integrated security=True;
I hope this will save someone.
You have to replace the %APPDATA% in the code with the relative path -
var connectionString = ConfigurationManager.ConnectionStrings["DatabaseEntities"]
.ConnectionString;
connectionString.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
When I add a database to a program, Visual Studio automatically creates the following connection string:
<connectionStrings>
<add name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString" connectionString="Data Source=|DataDirectory|\PlayerTeam.sdf" providerName="Microsoft.SqlServerCe.Client.3.5" />
<add name="PlayerTeamEntities" connectionString="metadata=res://*/edmPlayerTeam.csdl|res://*/edmPlayerTeam.ssdl|res://*/edmPlayerTeam.msl;provider=System.Data.SqlServerCe.3.5;provider connection string="Data Source=|DataDirectory|\PlayerTeam.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
I am trying to allow the user to select the database that they would like to open. How do I modify the connection string programmatically without losing my associated dataset and tableadapter?
Thanks in advance :)
you can use that method to call your connection string from your App.Config file to be used in the data connection or adapter
public string GetConnectionStringByName()
{
string returnValue = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Connection Name Here"];
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
when you add a new database to your project it takes the same connection Name of the existing database plus a number by default.
so you can make the connection string as a variable and add the number to it when you add a new database.
Edit
By considering you will add databases to your project grammatically, then if you added a new data base.
it will take that connection string's Name:
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString1"
as it add a number at the end of the name of the existing database
so, you can invest the method i provided, to add the specified connection string Something like that:
public string GetConnectionStringByName(int DB_Number)
{
string returnValue = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Connection Name Here"];
if (settings != null)
returnValue = settings.ConnectionString+Convert.ToString(DB_Number);
return returnValue;
}
as the DB_Number variable could be saved in an XML file in order not to be loosed and its increased each time you add database.
So, if you add a new database to the existing 1 the connection Name should be:
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString1"
and if you added another database the DB_Number will be increased by 1 to change the connection name to be :
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString2"
and enable the user to choose with connection string he wants to use.
on the other hand . if your databases added manually before the application runs.
it will be easier to Handle as what you just have to do is to save your connection string in a data structure as an array and call the wanted connection to use
that is what i figured out from your question