Would like to programmically change the connecton string for a database which utilizes the membership provider of asp.net within a windows application. The system.configuration namespace allows changes to the user settings, however, we would like to adjust a application setting? Does one need to write a class with utilizes XML to modify the class? Does one need to delete the current connections (can one select a connection to clear) and add a new one? Can one adjust the existing connection string?
Had to do this exact thing. This is the code that worked for me:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Create a connection string element and
// save it to the configuration file.
// Create a connection string element.
ConnectionStringSettings csSettings =
new ConnectionStringSettings("My Connection",
"LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" +
"Initial Catalog=aspnetdb", "System.Data.SqlClient");
// Get the connection strings section.
ConnectionStringsSection csSection =
config.ConnectionStrings;
// Add the new element.
csSection.ConnectionStrings.Add(csSettings);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
You can programatically open the configuration with using the System.configuration namespace:
Configuration myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Then you can access the connection strings collection at:
myConfig.ConnectionStrings.ConnectionStrings
You can modify the collection however you want, and when done call .Save() on the configuration object.
Use the ConnectionStringsSection class. The documentation even provides an example on how to create a new ConnectionString and have the framework save it to the config file without having to implement the whole XML shebang.
See here and browse down for an example.
Related
1 Run Application
2. Create Context
dbContext = new DBFirstContext();
3 Change App.config connection string for Entity FrameWork Object
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// change ConnectionString in App.Config for Entity FrameWork Object....
//.....
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
And now if I create
dbContext = new DBFirstContext();
It use sourse unchanged connectionString, as it was at starting application. If Close and then restart the application - new dbContext will be created by using modified connectionString.
PS: I don't want to passing new connection string for create new dbContext by using constructor like this:
public DBFirstContext(string sConnectionString)
: base(sConnectionString)
I need to create dbContext by using default constructor, and that it take a new (changed) connection string from the app.config without restarting the application. Is it possible?
Thank!
The App.config is read and parsed only once.
See the answer of "Darin Dimitrov" that was marked as the final answer. Why my changes of AppSettings in App.config is not taken into account in run-time? (Console Application)
I only take credit for Googling for this answer. All other credit should go to Darin.
In short: you're trying to use someting in a way it's not meant to be used. What is the reason you only want to work with the default constructor?
It is unclear why you need to change app.config or your connection string at runtime, but one way to change the connection string of your context without reconstructing it, is the following:
context.Database.Connection.ConnectionString = "connection string here";
Of course, your connection string must respect the format required by EF, so one way to construct your connection string is:
String.Format(
#"metadata=res://*/DBFirstContext.csdl|res://*/DBFirstContext.ssdl|res://*/DBFirstContext.msl;provider=System.Data.SqlClient;provider connection string='{0}'", connString);
where connString is a SQL Server connection string
my solution How to use default constructor for create context object by using connectionString from curent App.Config (App.Config were edited at run-time)
public DBFirstContext()
: base(System.Configuration.ConfigurationManager.ConnectionStrings["DBFirstContext"].ConnectionString)
{
}
Hi I am developing an application for that I am taking connection string through dynamically from user at first time run.
My app.config is
<connectionStrings>
<add name="DConnection" connectionString=""
providerName="MySql.Data.MySqlClient"/>
<add name="SConnection" connectionString=""
providerName="System.Data.SqlClient" />
</connectionStrings>
I am assigning connection string to app.config's attributes by using below methods
private void CheckingSource(string constr)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["SConnection"].ConnectionString = constr; //CONCATINATE YOUR FIELDS TOGETHER HERE
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
}
private void CheckingDestination(string constr)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["DConnection"].ConnectionString = constr; //CONCATINATE YOUR FIELDS TOGETHER HERE
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
}
Now I have to write this connection string to app.config so when user run application next time these updated connection strings should be in use.
How can we manage it? I don't have any idea as I am still fresher to app.config and it's usage.
Now I have to write this connection string to app.config so when user run application next time these updated connection strings should be in use.
You shouldn't do this, the app.config file might be deployed to somewhere like C:\Program Files\Your Application which is not writeable by normal users.
Instead, supply the connection string to whatever needs it in some way other than using ConfigurationManager.ConnectionStrings.
using (var connection = new SqlConnection(GetConnectionStringFromUser())) { ...
With specific regards to "saving" a connection string, you should look at some sort of persistence mechanism like .NET's Application Settings.
The application settings architecture supports defining strongly typed settings with either application or user scope, and persisting the settings between application sessions.
Thanks #ta.speot.is resolved the issue using application setting.
Reference link.
Application Setting
might be helpful to all needy. Cheers.. :)
I have my application and WCF service in same Solution.
I have written a property in a class(in the App) to get the ConnectionString from Web.Config of App.
Now need to access the same connection string in my WCF Service, but I have another Web.Config in my WCF Service(where all the bindings are defined). But I need to access the connection string of app.
//This is the connection string of App, where I am retrieving it in a common class.
public static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
You can access the connection string from another web.config. In asp.net project can have two web.config file in different directory.
Note : If the connection strings have the same "name", then the one in the directory will override the one in the root folder.
Add the Namespace to your class and access/read the web.config file connection string as it is. Before that Add the same Web.config file in to some other file Directory in your project.
The right answer is "Don't do it, Add the connection string the the config of the edge project"
If you insist on messing with the devil, use something similar to this (change it to your needs):
var fileMap = new ConfigurationFileMap("configFilePath");
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
var sectionGroup = configuration.GetSectionGroup("connectionStrings "); // This is the section group name, change to your needs
var section = (ClientSettingsSection)sectionGroup.Sections.Get("MyTarget.Namespace.Properties.Settings"); // This is the section name, change to your needs
var setting = section.Settings.Get("connectionStringKey "); // This is the setting name, change to your needs
return setting.Value.ValueXml.InnerText;
I'm accessing a config file thusly:
var map = new ConfigurationFileMap(configPath);
var config = ConfigurationManager.OpenMappedMachineConfiguration(map);
config.AppSettings.Settings.Add("SomeSetting", "SomeValue");
It works fine for any .exe.config file, but not for any web.config.
Note: I am not trying to access the web.config of the current application, I am attempting to modify the web.config in an arbitrary path.
(I've tried WebConfigurationManager instead of ConfigurationManager, but it gives identical results)
The exception is thrown by the AppSettings property accessor - trying to GetSection("appSettings") and cast it to an AppSettingsSection of course gievs the same exception. Either way, here it is:
System.InvalidCastException: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
I have obviously searched around, but have found only people accessing the web.config for the 'current web app' or using XmlDocument/XDocument.
My guess is .exe.config files automatically get some configSections-type information inferred which means it correctly knows how to deal with appSettings. However I have no idea why, based on the filename, it wouldn't work with web.config.
Ah. For app.config I'm using OpenExeConfiguration:
// works fine for .exe.config
var config = ConfigurationManager.OpenExeConfiguration("some-assembly-here.exe");
config.AppSettings.Settings.Add("SomeSetting", "SomeValue");
config.Save();
Here I'm using OpenMappedMachineConfiguration which appears to be for machine.config, however I can't see another way of opening an arbitrary web.config file - anyone?
My mistake - I can use OpenMappedExeConfiguration just fine when opening web.config files:
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configPath;
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
Using C#, is there are way to differentiate between ConnectionStrings in the machine.config and the web.config? I would like to iterate over the collection in the web.config but not those from the machine.config.
ASP.NET 3.5, C#
Try the code bellow or issue linq a query to find the compliment(differences) of both configs. The following yeilds true if connection string at index 0 is coming from the machine config where it also compares the connection string at index 0 otherwise yields false:
System.Configuration.ConfigurationManager.ConnectionStrings[0].Equals
(System.Configuration.ConfigurationManager.OpenMachineConfiguration()
.ConnectionStrings.ConnectionStrings[0])
have you tried
Configuration c = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");
From MSDN, also look at the System.Web.Configuration namespace.
How to: Read Connection strings from the Web.config file
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
if (connString != null)
Console.WriteLine("Northwind connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No Northwind connection string");
}
Every configuration in the Web.Config can also be put in machine.config.
You can think of Machine.Config is the base class and the Web.Config is the sub class.
So if you override any settings in Web.Config, you are basically overriding the machine configuration settings (Or asking the application to use the web.config settings)
So I think if you write connections sting in Web.Config, then from your application when you loop through the connectionstrings
ConfigurationManager.ConnectionStrings
you will be able to access only the connection strings that you have written in web.config.
Please try the <clear/> in the web.config connectionstring section. So I think that will clear the Machine.config connction strings.
For get first ConnectionString in localweb.config, use it:
var ms = System.Configuration.ConfigurationManager.OpenMachineConfiguration();
if (ConfigurationManager.ConnectionStrings.Count > ms.ConnectionStrings.ConnectionStrings.Count)
return ConfigurationManager.ConnectionStrings[ms.ConnectionStrings.ConnectionStrings.Count].ConnectionString;