Reputation: 71
Studio 2010 C# application accessing LUW DBs. I am receiving an error when building my DB Conncetion settings in the code behind file rather than using the web.config. We have a third party product where passwords are stored and retrieved.
The old web.config file method currently establishs DB connection as follows:
In the web.config file:
<add name="myDBConnect" connectionString="Database=mydbname;User
ID=myuserid;Password=abcxyz" providerName="IBM.Data.DB2"/>
In the code behind file the following is executed to open the DB connection:
ConnectionStringSettings settings = WebConfigurationManager.ConnectionStrings["myDBConnect"];
ConnectionString = settings.ConnectionString;
ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings;
if ((settings != null))
{
foreach (ConnectionStringSettings cs in settings)
{
returnValue = cs.ProviderName;
}
}
The above logic works fine - but I am now trying to dynamically build the connection string after retrieving the appropriate password from our third party product as follows:
(Note: connPW is the password retrieved from thrid party product)
ConnectionStringSettings settings = "Database=" + mydbname + ";User ID=" + myuserid + ";Password=" + connPW + " providerName=IBM.Data.DB2";
This line of code receives the following error: "Cannot implicitly convert type 'string' to 'System.Configuration.ConnctionStringSettings'
Can someone please suggest how I can get past this error when defining settings. Thanks
Upvotes: 2
Views: 7900
Reputation: 852
Try this...
ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString = "your connection string";
IF you the above code the system will throw an error " Configuration is Read Only" since the configuration is Read Only
we can do it by this method
var settings = ConfigurationManager.ConnectionStrings["ConnectionStringName"];
var Reset = typeof(ConfigurationElement).GetField(
"_bReadOnly",
BindingFlags.Instance | BindingFlags.NonPublic);
Reset .SetValue(settings, false);
settings.ConnectionString = "Data Source=Something";
Upvotes: 1
Reputation: 6674
It's giving that error to you because you are settings a String object equal to a ConnectionStringSettings object, of course. If you would like to use ConnectionStringSettings
, you just need to use the ConnectionStringSettings(string name, string connectionString, string providerName)
constructor.
ConnectionStringSettings settings = new ConnectionStringSettings("name", "Database=" + mydbname + ";User ID=" + myuserid + ";Password=" + connPW, "IBM.Data.DB2");
Upvotes: 1
Reputation: 887225
You don't need a ConnectionStringSettings
; you should connect to the string directly.
You should also use DbConnectionStringBuilder
fix fix the injection vulnerabilities in your code.
Upvotes: 3