I have three web applications that all access the same database. There is a lot of duplicated code there, so I'd like to move all the common stuff into a new project that each three application can just reference.
Firstly, I assume that a Class Library is the best thing to use to achieve this? Secondly, where in a Class Library would I store the connection string settings that previously would have been inside web.config?
In ASP.NET I am currently doing the following:
Web.config
<connectionStrings>
<clear/>
<add name="A" connectionString="Persist Security Info=False; User ID=user; Password=pass; Initial Catalog=myDb; Data Source=localhost; Connection Timeout=60" providerName="System.Data.SqlClient"/>
<add name="B" connectionString="Persist Security Info=False; User ID=user2; Password=pass2; Initial Catalog=myDb; Data Source=localhost; Connection Timeout=60" providerName="System.Data.SqlClient"/>
</connectionStrings>
ASP.NET Pages
Dim conn as New SqlConnection(ConfigurationManager.ConnectionStrings("A").ConnectionString)
I've searched for an answer, but can only find answers for accessing a web.config file from within a separate project, which is different.
You have to add an app.config file for configuration. But when reading from a class library, to have to use the app.config situated on the entry point executable project.
Imagine the following projects:
-ClassLibrary.dll (with)
- Class1.vb
- Class2.vb
- SettingsReader.vb
-ConsoleProgram.exe (with)
- Program.vb
- App.Config
Is ConsoleProgram the project where you must put your appSettings (in app.config), and then you can read them using the SettingsReader from the class library.
If you really want to read settings from your dll assembly, you could insert an app.config and set that file as "Embedded resource", so you can read the file using the Assembly.
Something like this:
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyApp.App.Config";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}