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;
Related
I have a DB2 environment, to which I would like to connect with Entity Framework. To do that, I need a connection string which looks like this, in the app.config file:
<connectionStrings>
<add name="DB2Connect" connectionString="Database=my_db; UID=Username; PWD=Password;"/>
</connectionStrings>
It doesn't seem like a good idea to have a password hardcoded into the app.config file, so I would like to replace it at run time, but only temporarily! The temporary part, is what is causing me trouble. I have successfully managed to replace the connection string, with the following code, but it's no good when the password remains in the the app.config file, afterwards:
private static void SaveConnectionString(string name, string connectionString)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings[name].ConnectionString = connectionString;
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
Not sure if i am answering something different here, but if you are looking for a solution to having no/a different connection string when you build to release, you can look into:
https://marketplace.visualstudio.com/items?itemName=vscps.SlowCheetah-XMLTransforms
i have an app.config file that has a connection string for my database.
what i want to do is to connect to different databases that's why i used to this code:
connectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings[nameofConnectionString].ConnectionString = connectionString;
config.Save();
ConfigurationManager.RefreshSection(nameofConnectionString);
it works well, it changed the connection string, but the problem is that it sends me an error saying "facerec6.0.cdcol does not exist"
my default initial catalog = facerec6.0
what will i do ?
The ConnectionStringSection is just a container to store named connection strings. If you want to connect to different databases then it's best to start by storing those different connection strings in that section from the start and then determining how your application will choose which one to use at runtime.
Think of that section as just that and nothing more - it's a convenient, known place to store connection strings with a standard way to retrieve them. Other developers working on the code will know where to look for them and know how to retrieve them.
Even though it's technically possible to modify that section at runtime and save the file I wouldn't do that. If you have the same code that may use different connection strings while running in the same environment (it's not a case of one for development, one for QA, and one for production) then you could have your class depend on an interface something like this:
public interface IConnectionStringFactory
{
string GetConnectionString(Something key);
}
Where Something is a value that the class requiring the connection string can pass to the factory, and the factory can use it to determine which connection string to retrieve. That way the class that uses the connection string is insulated from that logic. It doesn't know why it uses one connection string or another. It just gets a connection string from the factory and then uses it.
If it's a case of varying connection strings by environment then that's much, much easier - you can do that with config transforms. In most cases if it's a different environment then all the connection strings will be different for each environment, so you can just replace the whole section.
<connectionStrings xdt:Transform="Replace">
<add name="connectionStringA" connectionString="...whatever..." />
</connectionStrings>
Please try this instead:
ConfigurationManager.RefreshSection("connectionStrings");
because:
<connectionStrings> <- this is the section
<add name="facerec6.0"/> <- this is the element
<add ... />
</connectionStrings>
You need to refresh the section, not the element, when using RefreshSection.
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'm newbie in C#. I want to ask, how can I separate the connection string config into a class?
Because every time I want to write code, I need to re-write the connection string and test the connection. So, I need to make a class so that every time I make a connection to the database, this class will test the connection first. Then after it works, the class will send the connection string to my coding.
Besides, if I want to change my source data, I just need to change in the class only. No need to search all my coding
So if I can make a class, how do I call and get the connection string from class?
Can it be like that?
This is my current coding for connection string in C#
FileInfo file = new FileInfo(Application.StartupPath + "\\conn.txt");
if (file.Exists)
{
StreamReader r = File.OpenText(Application.StartupPath + "\\conn.txt");
connString = r.ReadToEnd();
r.Close();
// Open SQL connection
SqlConnection openCon = new SqlConnection(connString);
try
{
Cursor = Cursors.WaitCursor;
openCon.Open();
}
catch
{
MessageBox.Show("Error to established connection\nPlease check Data Source");
openCon.Close();
Cursor = Cursors.Arrow;
}
else
{
MessageBox.Show("File config is missing");
}
}
Hope you can teach me as a newbie in C#. Thanks for the help. And sorry for bad english.
You should store connection strings in your configuration file. If you don't have a configuration file, add one by right-clicking the project and 'adding new item...' If you are writing a web app it will be a web.config file; if you are writing a client app it will be an app.config file.
You add a connection string to the configuration file in the connectionStrings node, normally at the top of the file.
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!-- add a string -->
<add name="MyConnectionString"
connectionString="Data Source=localhost; ... // etc
providerName="System.Data.SqlClient" />
</connectionStrings>
// and keep all the other configuration in the file
And then you simply refer to the configuration file using the ConfigurationManager class - you'll need to add a reference to System.Configuration if you don't already have one.
ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
You're trying to reinvent the wheel here. The .Net framework already include some simple techniques to handle this. If you're creating a Windows form project, you can store the connection string in App.Config using the connectionString attributes. If this is a web app, then you store it in web.config, here is how it would look like:
<connectionStrings>
<add name="Prod" connectionString="Server=myServer;Database=DB1;user=sa;password=myPassword;Trusted_Connection=false" providerName="SQL" />
</connectionStrings>
Then, in your code, you read the connection string from web.config as follow:
string connString = System.Configuration.ConfigurationManager.
ConnectionStrings["Prod"].ConnectionString;
You're asking a very basic question here and it indicates that you're trying to bully your way into learning c#. My advice to you is to grab a good C# book and go through it cover to cover to learn things the right way.
Instead of putting the connection string into a separate file, store it in your app.config or web.config file. .NET configuration files van contain a section that allows you to store connection strings:
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
You can retrieve this connection string using the following code:
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
I think Poster's question is pretty much valid. Although we can write connection string in Web.config or app.config once and use it in whole project, but there is a drawback of using this technique.
Connection string in web.config or app.config is never safe. These two files are ultimately like text files. There are ways to get the password from them. The security could be broken. So its better to use the connection string in a separate class file and get it in your whole project.
you could create a class which returns a sqlConnection...
public class DBConn
{
private string ConnectionString = "123456789Connection";
public SqlConnection getSqlConn()
{
return SqlConnection();
}
}
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.