Read Connection String Parameters - c#

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();

Related

Lost Session variable when use ConfigurationManager.RefreshSection()

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
}

What is the command to connect to a database(MS Access) saved anywhere on the PC without specifying the full path 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

Accessing different datasources

In my data import application I want to allow the user to import data from as much different data sources as possible.
So what is the best way and what are the classes needed to be able to connect to different data sources and then get data from them via SQL queries?
E.g.
// 1. A class I need to allow the user to select the needed data source
ConnectionDialog dlg = new ConnectionDialog();
dlg.ShowDialog();
// 2. A class I need to access the data source using the connection string built above
DataConnection con = new DataConnection(dlg.builtConnectionString);
con.doStuff("SELECT * FROM test");
Currently I'm using the Microsoft connection dialog (http://archive.msdn.microsoft.com/Connection) for the first part. But I can't figure out how to use the connection strings returned by it. An OdbcConnection won't accept it (only tested with an Micrsosoft SQL connection string generated by the dialog). Is it even possible to achieve the above or will I be forced to use different classes for the second part?
Edit: I also want the user to be able to install his own drivers for data sources. I just don't know if ODBC or OleDB or anything else is the way to go and if/how I can use the connection dialog with this.
Use wrapping to list of DB sources. Add a connection strings to web.config for each type of DB connection (MSSQL , MYSQL and Oracle) with {{name}} string and then replace this string with the catalog selected by the user.
<connectionStrings>
<add name="mssql" connectionString="Data Source=.;Initial Catalog={{name}};Integrated Security=True" />
<add name="mysql" connectionString="server=localhost;user id=root; password=PASS;database={{name}};pooling=false" />
<add name="oracle" providerName="Oracle.DataAccess.Client" connectionString="Data Source={{name}};User Id=root;Password=PASS;" />
</connectionStrings>
Now use SqlConnection and MySqlConnection and OracleConnection classes . (You will need mysqlconnector and oracleconnector for these classes).

Set the database location in the connection string thought AppDomain.CurrentDomain.SetData

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...

%APPDATA% in connection string is not substituted for the actual folder?

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);

Categories

Resources