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.. :)
Related
I am trying to move my 2 database connection strings to environment variables for security reasons. Everything works fine when I include the 2 connection strings on web.config like so:
<connectionStrings>
<clear />
<add name="DefaultConnection" connectionString="Data Source=xxxxxx" providerName="System.Data.SqlClient" />
<add name="RDSContext" connectionString="Data Source=xxxxxx" providerName="System.Data.SqlClient" />
</connectionStrings>
I then removed the 2 connection strings from web.config and created 2 environment variables as follows:
setx CUSTOMCONNSTR_DefaultConnection "Data Source=xxxxx"
setx CUSTOMCONNSTR_RDSContext "Data Source=xxxxx"
Although I now get the following error when I startup IIS and visit the web app
Server Error in '/' Application.
Cannot attach the file 'C:\Users\xxx\xxx\App_Data\BookingSystem.Models.RDSContext.mdf' as database 'BookingSystem.Models.RDSContext'.
Can anyone tell me what I am doing incorrect?
Simply naming your environment variable in a certain way doesn't mean that MVC will pick them up. You may be assuming a little more magic is happening than there actually is.
When you do ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString you're only retrieving the connection string from your web.config file, or machine.config if you happened to have defined it there. There's nothing there to tell your app to grab it from anywhere else.
Instead, you might consider creating a class to represent your configuration:
public class MyApplicationDatabaseConfiguration
{
public string ConnectionString { get; set; }
}
Any class that needs to obtain this connection string can do so by depending on an instance of that MyApplicationDatabaseConfiguration.
public class MyDatabaseRepository
{
readonly MyApplicationDatabaseConfiguration _dbConfig;
public MyDatabaseRepository(MyApplicationDatabaseConfiguration dbConfig)
{
_dbConfig = dbConfig;
}
public void DoSomethingWithTheDatabase()
{
using(var connection = new SqlConnection(_dbConfig.Connectionstring))
{
//now you can use the connection
}
}
}
Then you can load your config however you like. Ex:
MyApplicationDatabaseConfiguration dbConfig = new MyApplicationDatabaseConfiguration();
dbConfig.ConnectionString = Environment.GetEnvironmentVariable("MyApplication_MyConnectionString");
Now the MyDatabaseRepository doesn't care how you load the database config, it simply says "I need the database config". This is extremely powerful, it allows you to change out the configuration by simply changing a line of code. Need to change back to using web.config? It's as simple as dbConfig.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
Microsoft has taken this one step further in Microsoft.Extensions.Configuration library, which is meant for .NET Core but targeted to .NET Standard, so you can use it in your .NET Framework library if you'd like.
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.
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();
}
}
We've recently changed the name of the SQL DataBase our WebApp is using. Now, each of the DataTableAdapters will update to the new ConnectionString.
Our setup is as follows:
1) Interface (WebSite Project)
2) Business Logic (Class Library Project)
3) Data Access (Class Library Project) ---> Contains many DataSet classes
The app.config of the Data Access project contains the only connection string. When creating each of the DataTableAdapters, the wizard points to it correctly. Now, we've had to change the ConnectionString, and all of the existing DataTableAdapters (about ~60) will not work.
Simply changing the ConnectionString has not worked. What am I missing?
Thanks
Make sure the connection string name in your config is the same as the one in the Settings File. Because in the generated code, when it initialzed the connectionstring it setting the connection string as follow :
private void InitConnection() {
this._connection = new global::System.Data.SqlClient.SqlConnection();
this._connection.ConnectionString = global::ConsoleApplication4.Properties.Settings.Default.MyConnectionString;
}
Make sure that in your app config the name of your connectionString is the same. for example
<connectionStrings>
<add name="ConsoleApplication4.Properties.Settings.MyConnectionString"
connectionString="Data Source=MyServer;Initial Catalog=MyDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
The problem was in the Settings.Designer.cs file. Its an auto-generated file that did not update after the normal updating/clean/build process.
Thanks Everyone :-)