Trevor Daniel
Trevor Daniel

Reputation: 3954

Class Library Connection String Confusion

I have managed to confuse myself... not difficult, I know, and am looking for some guidance...

I have written a dll which I am now starting to use in my Winforms UI.

This is a follow on question to this:

Class Libray Connection String - How to change?

As told in that post, I have added the identical connection string settings from the app.config in the dll to my App.config in my UI.

In my UI, I have a text box where the user can enter the connection string and hit "Save", which runs the following code:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString = txtConnectionString.Text;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

Which seems to update the string in the file correctly.

But, and this is where the previous posting confuses me...

That setting only gets read when the software starts. Somehow I need to change the setting which Belogix has explained I should do like this:

var connectionString = "Data Source=MegaServer;Initial Catalog=MyDb; .. etc ..";
using (var db = new MyDataContext(connectionString))
{
   // This will connect to MegaServer...
}

But, I am calling functions in my dll like this:

List<Page> pages = Database.getlistOfPagesToScan();

How do I tell that call to start using the newly saved connection string from the UI's App.config?

Can anyone shed any light?

Thanks

Upvotes: 0

Views: 81

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156918

You should get the connection string from the settings in the dll. Your answer is actually in the question you post.

Use this:

var connectionString = config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString;

You can also use this:

string s = Properties.Settings.Default.ConnectionStr;
Console.WriteLine("Connection string from main app: " + s);

//
// When setting access modifier on Class library to `public`
//
s = ClassLibrary1.Properties.Settings.Default.ConnectionStr;
Console.WriteLine("Connection string from dll: " + s);

Upvotes: 1

mwrichardson
mwrichardson

Reputation: 1348

Assuming you are using ConfigurationManager to retrieve the application connection strings, try:

ConfigurationManager.RefreshSection("connectionStrings");

Upvotes: 0

Related Questions