Getting connectionstring from web.config when in a dll

  • Thread starter Thread starter Andy B.
  • Start date Start date
A

Andy B.

I have a web application project called Website. I have a dll project called
Categories in the same solution in vs2008. How do I get code in the
Categories project to access connection strings in the Website.web.config
file?
 
Here is some exact code I have in my "lower layers".
It "sees" the web.config file.

If you're just asking about syntax, then here it is:



private static readonly string MYKEY = "SomeKeyInTheConfigFile";



private int DetermineSomeIntValue()
{
int returnValue = 0;

if (null != System.Configuration.ConfigurationManager.AppSettings[MYKEY])
{
returnValue =
Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings[MYKEY]);
}


return returnValue;



}



Don't forget the reference to system.configuration under "Add References"
 
Ok, I didn't see you're talking about connection strings.
Here you go:



c#

ConnectionStringSettingsCollection connectionStrings =
ConfigurationManager.ConnectionStrings;

foreach (ConnectionStringSettings c in connectionStrings)
{
string connectionStringName = c.Name;
string connectionString = c.ConnectionString;
string providerName = c.ProviderName;

Console.Writeline(connectionStringName);
}



vb.NET



Dim connectionStrings As ConnectionStringSettingsCollection =
ConfigurationManager.ConnectionStrings

Dim connection As ConnectionStringSettings
For Each connection In connectionStrings



Dim connectionStringName As String = connection.Name
Dim connectionString As String = connection.ConnectionString
Dim providerName As String = connection.ProviderName

Debug.Print(connectionStringName)
Next connection
 
I'm using a SqlDataReader to do data access. I use an SqlConnection object
for the connection. So, I can do just like I do in the web application in
the dll and do something like:

dim SqlConnection as new
SqlConnection(ConfigurationManager.ConnectionStrings("eternityrecordsonlineConnectionString").ToString())
 
Correct.

You're using the indexer on the ConfigurationManager.ConnectionStrings
collection.


I would invite you to look at the EnterpriseLibrary.Data as well, it greatly
simplifies DataAccess to very "lean" code.




public IDataReader GetSingleEmployeeReader ( int employeeKey )
{

IDataReader returnReader = null;
try
{
Database db = base.GetDatabase (); // Encapsulated call to
get the Microsoft.Practices.EnterpriseLibrary.Data.Database object
DbCommand dbCommand =
db.GetSqlStringCommand("dbo.uspEmployeeGetSingleByEmployeeKey");
db.AddInParameter(dbCommand, "@EmployeeKey", DbType.Int32,
employeeKey);
returnReader = db.ExecuteReader(dbCommand);
return returnReader;

}
finally
{
}

}
 
I looked at it but my dev computer doesn't have xp pro or later on it so I'm
kind of stuck with the native .net objects.
 
Back
Top