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
}
Related
I have my connection string set up in the app config but I can not get it to find that connectionstring or even see that the connection name currency is in the collection.
I tried to add a version.
I have tried to adding the provider name to the string.
I have moved it in and out and in again of the path where the database and solution are located.
I have carefully made sure that I was pointed to the right location on my computer.
<connectionStrings>
<!-- CHANGE THIS to match where your solution and sqlite database are -->
<add name="currency" connectionString="Data Source=F:\CurrencyExercise\currency.db" />
</connectionStrings>
And then the code that calls the above.
public BaseDataAccess(string connectionName = "currency")
{
_connectionName = connectionName;
Connection = new SQLiteConnection(ConfigurationManager.ConnectionStrings[_connectionName].ConnectionString);
Connection.Open();
}
I would expect the code to actually pull back a SQLiteConnection object rather than erroring out.
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
}
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);
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;
I am developing an asp.net application which I have hosted on an IIS server. To open a connection I use:
SqlConnection con = new SqlConnection("Server = INLD50045747A\\SQLEXPRESS;
Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
con.Open();
Is it possible to store this connection string somewhere so that I don't need to write in every aspx.cs file? I am using MSSQL database.
I'm facing an issue which says:
The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached
I read somewhere which asks me to increase the maximum connection pool to 100. Will it affect the performance of my application?
You probably aren't closing your open connections propertly.
Increasing the "pool size" is like putting a bigger bucket under a waterfall - it will help, but barely.
Try and locate areas where something like this is happening:
con.Open();
Ensure that if it's not in a try/catch, that it is in one, and that it includes a finally statement.
try {
con.Open();
//several other data base releated
//activities
} catch (Exception ex) {
// do something
} finally {
con.Close();
}
Also, to avoid having to use the finally block, you can just wrap the SqlConnection in a using statement.
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["yourKey"].ConnectionString))
{
// write your code here
}
In regards to your question about connection string, yes store it in your web.config
<connectionStrings>
<add name="name" connectionString="Data Source=;Initial Catalog=;User ID=sa;password=;Persist Security Info=True;Connection TimeOut=20; Pooling=true;Max Pool Size=500;Min Pool Size=1" providerName="System.Data.SqlClient"/>
</connectionStrings>
Store it in the web.config file, in the connectionStrings section:
<connectionStrings>
<add name="name"
connectionString="Data Source=;Initial Catalog=;User ID=sa;password=;Persist Security Info=True;Connection TimeOut=20; Pooling=true;Max Pool Size=500;Min Pool Size=1"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And then you will be able to access this in your code...
ConfigurationManager.ConnectionStrings["name"].ConnectionString
you can do using also
it will automatically disposes the object
if you use "using" there is no need of con.close and all
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["yourKey"].ConnectionString))
{
// write your code here
}
Store the connection string in the web.config files. you can find numerous examples. Check this for the properties. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.71%29.aspx
Thanks
Shankar
Use the Help of Both
try
{
con.Open();
}
catch(Exception ex)
{
if(con.State== ConnectionState.Open)
con.Close();
}
finally
{
con.Close();
}
and also add the Connection String in Web.Config, under Configuration. This will help you.
Yes, store it in the web.config file but make sure that if there is an error it doesn't display the content of the web.config file to the user (thus showing the world your password.)
If you use that same connection string in a lot of applications you could consider writing a service to provide the connection strings, that way you only have to change them in one place.
The best option is to use typed settings.
Open your project properties.
Go to Settings tab.
Add new setting, for example MainConnectionString, select setting type (ConnectionString). In the value insert your connection string or hit '...' button to bring a dialog to build connection string.
Now you can reference your connection string in the code like this:
Settings.Default.MainConnectionString
If you open your config file you will see
<configuration>
<connectionStrings>
<add name="WebApplication1.Properties.Settings.MainConnectionString"
connectionString="Data Source=localhost;Initial Catalog=AdventureWorks;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
You can have this connection string
specified:
for one web site in its own web.config.
for a group of web sites
for all web sites on a box: in machine scope web.config.
for all application on a box: in the machine.config.
This can be convenient if you have a lot of applications that connect to the same db and are installed on one box. If db location changes you update just one file machine.config, instead of going to each application's config file.