EntLib Configuration with Project->Properties->Settings

Topics: Data Access Application Block, General discussion
Jul 3, 2007 at 3:39 PM
Edited Jul 3, 2007 at 3:41 PM
Hi,
I've started using the Enterprise Library after a long time; The last time I used, it was for .Net 1.1 and EntLib 2005 version. I realize more has changed.

In my VB 2005 projects I've gotten used to specifying the configuration elements via the GUI at Project -> Properties -> Settings. Since app.config is not used by this method, how do I use EntLib configuration tool to mention my connection strings, Database etc?

Pardon me if this has been asked before.

Thank you.
Jul 3, 2007 at 3:54 PM
Hi,

EntLib uses the standard .NET connection strings configuration, which AFAIK map to the settings of type ConnectionString, so you should be able to continue using your approach for specifying the connection strings.

About the details of how to specify configuration, the configuration tool is very similar to what you used in Entlib 2005 although the files are different; you may want to browse topic "The Enterprise Library Configuration Console" in the integrated help for details. You also have a version of the tool integrated in the VS IDE; you can access it by right clicking on the app.config file (which you will need to have in your project and that will be added for you if you use the "settings" feature.)

Hope this helps,
Fernando
Jul 3, 2007 at 4:13 PM
Hi Fernando, Thanks for such a quick response. That helped.

Please correct me if I'm wrong - in Visual Studio 2005, app.config is not added automatically when the project is created. In such a case, if I want to use EntLib configuration tool, should we manually add an app.config to the project?

Many thanks once again.
Jul 3, 2007 at 4:20 PM
Hi,

You're correct. However the app.config file will be added for you if you specify project settings.

Fernando
Aug 3, 2007 at 8:02 PM
Edited Aug 3, 2007 at 8:10 PM
First I edit the app.config with the EntLib Configuration Console; Then if I try to open it with the Code Editor, the properties I configured such as ConnectionString etc, are lost and got overwritten with something as below:

data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

....which is not what I set via the EntLib Configuration Console.

How to prevent this? Thank you. If this has been answered elsewhere, kindly help me with links.



fsimonazzi wrote:
Hi,

You're correct. However the app.config file will be added for you if you specify project settings.

Fernando

Aug 6, 2007 at 3:09 PM
Hi,

That connection string comes from the machine.config file. About why it doesn't save the information you entered, I can only say it should. Can you post the exact steps you're following?

Regards,
Fernando
Aug 9, 2007 at 7:43 PM
Edited Aug 9, 2007 at 7:47 PM
Thank you Fernando

Here are the steps :

In Visual Studio 2005,
1) Right click on my app.config for my Class Library project in Solution Explorer
2) Select Edit Enterprise Library Configuration

In EntLib Config Console,
3) Click on LocalSqlServer
4) Hit F4 to bring up it's properties window
4a) Connection String shows data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
5) Click on the dot dot dot button in Connection String
6) In the Connection Properties dialog, select the Local Sql Server and Database, and the proper authentication ( I used windows authentication)
6a) Database names get populated in the drop down
7) I set User Instance to False; if not, I get This connection cannot be tested because the specified database does not exist or is not visible to the specified user.
8) Click Test Connection - This shows Test Connection Succeeded
9) I click Save and quit the EntLib Configuration Console
10) I attempt to look at the source of app.config, but the source does not correspond to the settings I made in the previous steps. So I exit without hitting Save
11) I try to open app.config using EntLib Configuration Console again and then it has that junk connection string instead of my connection string.

Please tell me what am I doing wrong. Many Thanks.
Aug 9, 2007 at 7:56 PM
Hi,

The connection string is defined in the machine.config file, and is inherited by your app's config file. Although you can see it, and unfortunately modify it, when you edit the config file, it will still be defined in the machine config file and inherited from it.

Just create a new connection string and use it.

Regards,
Fernando
Aug 9, 2007 at 9:18 PM
Do you mean -create a new connection string and use that to replace the existing one in Machine.config?

Thanks for a quick response.


fsimonazzi wrote:
Hi,

The connection string is defined in the machine.config file, and is inherited by your app's config file. Although you can see it, and unfortunately modify it, when you edit the config file, it will still be defined in the machine config file and inherited from it.

Just create a new connection string and use it.

Regards,
Fernando

Aug 9, 2007 at 9:35 PM
Hi,

I mean create a new one (right click on "Connection Strings", New\Connection String) and configure that connection string as you wish , leaving the inherited one as it is.
You can have as many connection strings as you want, and you will access them from your application by name so you don't have to reference the inherited connection string if you don't need it.

Fernando
Aug 9, 2007 at 9:48 PM
Understood. Thank you very much for the guidance. :-)
Aug 13, 2007 at 7:40 PM
Edited Aug 13, 2007 at 7:40 PM
Hi Fernando,

Sorry for not letting this topic die, but I have one more issue. Hopefully, this will be the last.


I took your advice, and added a second connection string. Then I refer to that via my code like this

Function GetEmployeeNameByZipCode(ByVal zip_code As String) As String
Dim readerData As Text.StringBuilder = New Text.StringBuilder
Dim db As Database = DatabaseFactory.CreateDatabase("myconnstr")
Dim sqlCommand As String = "Query to get employeeName where zip code = zipcode"
Dim dbcommand As DbCommand = db.GetSqlStringCommand(sqlCommand)
Using dataReader As IDataReader = db.ExecuteReader(dbcommand)
While (dataReader.Read())
readerData.Append(dataReader("EmployeeName"))
readerData.Append(Environment.NewLine)
End While
End Using
Return readerData.ToString()
End Function

It always fails at CreateDatabase line and gives me this error

The requested database myconnstr is not defined in configuration.

The connnection string is valid and present in the app.config.

My app.config looks like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<connectionStrings>
<add name="myconnstr" connectionString="Data Source=LocalHost\SQLEXPRESS;Initial Catalog=EntLibQuickStarts;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog" />
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" />
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
</configuration>


What am I missing or doing wrong? Please help me understand. Thank you for your time.


Aug 13, 2007 at 8:13 PM
Hi,

Please look at the DAAB quick start. Although it is not accessing the connection string by name from the client code (it is using the "DefaultDatabase" instead by calling the DatabaseFactory.CreateDatabase() method, but you can change it to match your usage), it will show a proper configuration file.

The configuration file looks fine though. Make sure that is the configuration file that is actually being used by your app.

Fernando
Aug 28, 2007 at 5:20 AM
How does one "Make sure that is the configuration file that is actually being used by your app"?
Aug 28, 2007 at 2:37 PM
Hi,


msvturner wrote:
How does one "Make sure that is the configuration file that is actually being used by your app"?


A deployment problem could prevent your correct configuration file from being used when your application runs (e.g. the app.config project item doesn't have the a appropriate build action). If you're debugging your application then look at the exe name.config file in the bin\Debug folder for the project.

Fernando
Aug 28, 2007 at 11:46 PM
I am using WCF so I have a service project with a web.config in its project folder (not in bin folder); I also have a client project (console app) with an App.config in the project folder. There is no "config" file in the client's bin/Debug folder. Seems you may have him on an issue. Could it be a Vista permissions issue?
Aug 29, 2007 at 2:48 AM
Edited Aug 29, 2007 at 2:49 AM
Not sure what to tell you, this usually "just works". Pump up logging for the build process (Tools/Options, Projects and solutions/Build and run, MSBuild project build verbosity -> detailed), and rebuild. You should see something like this in the output window for the "Build" page, copying the config file.

Target _CopyAppConfigFile:
Building target "_CopyAppConfigFile" completely.
Output file "bin\Debug\ConsoleApplication11.exe.config" does not exist.
Task "Copy"
Copying file from "App.config" to "bin\Debug\ConsoleApplication11.exe.config".
Command:
copy /y "App.config" "bin\Debug\ConsoleApplication11.exe.config"
Done executing task "Copy".

Fernando
Sep 3, 2007 at 10:47 AM
Not sure if it helps... From the verbose build script, I get the following. It seems it is not finding what it needs :( Any ideas?

Task "CreateProperty" skipped, due to false condition; ('$(AppConfig)'=='' and '%(RelativeDir)%(Filename)%(Extension)'=='App.Config') was evaluated as (''=='' and 'Properties\Settings.settings'=='App.Config').
Task "CreateProperty" skipped, due to false condition; ('$(AppConfig)'=='' and '%(RelativeDir)%(Filename)%(Extension)'=='App.Config') was evaluated as (''=='' and 'web.config'=='App.Config').
Task "CreateProperty" skipped, due to false condition; ('$(AppConfig)'=='' and '%(RelativeDir)%(Filename)%(Extension)'=='App.Config') was evaluated as (''=='' and 'ProductsService.svc'=='App.Config').
Task "CreateProperty" skipped, due to false condition; ('$(AppConfig)'=='' and '%(Filename)%(Extension)'=='App.Config') was evaluated as (''=='' and 'Settings.settings'=='App.Config').
Task "CreateProperty" skipped, due to false condition; ('$(AppConfig)'=='' and '%(Filename)%(Extension)'=='App.Config') was evaluated as (''=='' and 'web.config'=='App.Config').
Task "CreateProperty" skipped, due to false condition; ('$(AppConfig)'=='' and '%(Filename)%(Extension)'=='App.Config') was evaluated as (''=='' and 'ProductsService.svc'=='App.Config').
Sep 3, 2007 at 3:22 PM
Hi,

Don't you get any entry for task CopyAppConfigFile when you build the client?

Fernando
Sep 6, 2007 at 5:07 AM
It does create the ProductsService.dll.config file. It contains the correct DB connection string:

<connectionStrings>
<add name="AdventureWorksConnection" connectionString="Data Source=_MyServer_;Initial Catalog=AdventureWorks;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

When I run the code, this line belows throws the exception listed after it:

Database dbAdventureWorks = DatabaseFactory.CreateDatabase("AdventureWorksConnection");


The requested database AdventureWorksConnection is not defined in configuration.

This is SOOOOO fustrating - thankd for the help. I am setting up a WinXP VPC on my machine to see if it is a Vista or permissions issue.
Sep 6, 2007 at 6:27 AM
Edited Sep 6, 2007 at 6:31 AM
I am using Enterprise Library 3.1 Exception Handling Application block for logging exceptions to a flat file using Flat File Trace Listener. In my local system, its logging the exception properly but when I moved to production, its not working. I tried to give permissions to the folder of the file path. But its not working. Do u have any idea?
Here i am providing the web.config code:

<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="Trace" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add fileName="D:\trace.log" header="----------------------------------------"
footer="----------------------------------------" formatter="Text Formatter"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
traceOutputOptions="Callstack" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="FlatFile TraceListener" />
<add source="Enterprise Library Logging" formatter="Text Formatter"
log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Formatted EventLog TraceListener" />
</listeners>
<formatters>
<add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</add>
<add switchValue="All" name="Trace">
<listeners>
<add name="FlatFile TraceListener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
<add name="SPS Exception Policy">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow" name="Exception">
<exceptionHandlers>
<add logCategory="Trace" eventId="100" severity="Error" title="SPS Exception Logging"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
priority="0" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
Sep 6, 2007 at 6:43 AM
Hi,
I am using EntLib 3.1 Data Access Applicaiton Block for my Data Layer.I am encrypting the connection string using Ent Lib Configuration tool, using the "'RsaProtectedConfigurationProvider'". It is working in my local machine. But when i deployed in production, i am getting the following error.
Failed to decrypt using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: The RSA key container could not be opened.
Please help.

Thanks in advance,
Sudheer



Sep 6, 2007 at 1:42 PM
Hi Sudheer,

Please start new threads for questions unrelated to the original post.

Thanks,
Fernando
Sep 6, 2007 at 1:49 PM
Hi msvturner,

I'm sorry for your frustration, but it's the .NET framework that manages which configuration file is used for what and EntLib won't change this behavior unless explicitly indicated (and even there is onyl so much EntLib will do). Having code in your library project that uses EntLib and you have a config file defined in that library project doesn't mean that the configuration file will be used when executing that code.

I'm confused about your scenario: you initially mentioned a web.config for your WCF service and an app.config for your client, but now there's a ProductsService.dll.config file. Exactly how is your solution organized?

Regards,
Fernando
Oct 11, 2007 at 10:36 PM
Edited Oct 11, 2007 at 10:39 PM
I am having the same problem trying to use the Data Access App Block.

here is how my solution is organized:
  • A project named "xyz.TestSuite"
----> TestDataAccess.cs
----> App.config (which is properly modified into "xyzTestSuite.dll.config")

  • I then use the NUnit GUI to run my test which is using the DatabaseFactory.CreateDatabase() method

  • I have put the "xyzTestSuite.dll.config" file in the folder that the NUnit .exe file is located (C:\Program Files\NUnit 2.4.3\bin)
  • I have put the "xyzTestSuite.dll.config" file in the \xzy.TestSuite\bin\Debug folder
  • I have put the "xyzTestSuite.dll.config" file in the \xyz.TestSuite\obj\Debug folder

--> i have tried every combination of placing the xyzTestSuite.dll.config file in each folder individually, then all at once, and then 2 at a time, and nothing works. I keep getting the "The requested database XYZ is not defined in configuration"

The following is my config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" />
</configSections>
<connectionStrings>
<add
name="XYZ"
providerName="System.Data.SqlClient"
connectionString="server=(local);database=XYZ;Integrated Security=true" />
</connectionStrings>
<dataConfiguration defaultDatabase="XYZ"/>
</configuration>


This is incredibly frustrating. Any help is appreciated! Why use the App Block if it takes longer to set it up than it does to write your own Data Access Layer? Seriously, there must be a simple way to explain how to set this up.
Oct 12, 2007 at 3:05 PM
Hi,

This is a problem with how a specific test runner configures the AppDomain it uses to run the tests, not with the DAAB. If the configuration is not accesible is little entlib can do.

Actually, the connection strings section is owned by the .NET framework. You can write a test that doesn't involve the DAAB and just does ConfigurationManager.ConnectionStrings"XYZ". If it is able to get the connection string, so should the DAAB.

You can try querying the app domain's setup information in your test to get the configuration file location. It should be in the folder where the assembly under test resides, but it doesn't seem to work as you describe it.

Fernando
Oct 12, 2007 at 3:26 PM
It looks like this new version of the runner uses ProjectName.config as the configuration file name, so unless your NUnit project file is named xyzTestSuite.dll.nunit you will need to change the configuration file's name...

Fernando
Oct 15, 2007 at 5:17 AM
Hi Fernando,

Thanks for the help. The trick w/ the NUnit for .Net 2.0 is that you need to have a *.config file in the same directory as the *.nunit file

Example:
  • XYZ.TestSuite.dll.nunit
  • XYZ.TestSuite.dll.config
Oct 22, 2007 at 10:46 PM
Hi,

Thanks for the update. Can you provide a link to this information so it gets documented?

Thanks!
Fernando
Dec 30, 2009 at 12:43 PM
Edited Dec 30, 2009 at 12:47 PM

Hi,

I got the same "The requested database xxx is not defined in configuration." Exception. I found a solution:

My initial settings:

2 projects:

- DataLayer dll

- Asp.net web app

When I called DatabaseFactory.CreateDatabase(connection string) I got the exception. My connection string was defined in a app.config file in the dll project as well as in the web app. I dived a bit deeper into the exception and found out, that it was complaining, that the provided connection string was not defined in the "ConnectionSettings.config". So I went create it. The error stills happened. Then I switched to the parameterless constructor of DatabaseFactory.CreateDatabase. The Exception I got was the same, but it turned out, that the inner Exception was now complaining about a missing provider name in the config file(s by now). I filled the provider name in the connection string tags and everything works fine now, except, that I still can't call the Factory method with a provided connectiong string. I can only use the parameterless constructor.

I hope that helps and I may get an answer why I can't call the constructor with a parameter. Why do I have to define a ConnectionSettings.config anyway?

Cheers, Steve

Jun 15, 2010 at 6:20 PM
Very strangely. I opened the file in C:\Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin\EntLibConfig.exe and when I looked through the tree, the "name" was not the name of what I hand edited it (and SAVED it) to be. <connectionStrings> <add name="XYZ" providerName="System.Data.SqlClient" connectionString="server=(local);database=XYZ;Integrated Security=true" /> </connectionStrings> My original looked like the above. <connectionStrings> <add name="ABC" providerName="System.Data.SqlClient" connectionString="server=(local);database=XYZ;Integrated Security=true" /> </connectionStrings> So I hand edited the file in notepad and changed "XYZ to ABC". My code then failed: Database dbAdventureWorks = DatabaseFactory.CreateDatabase("ABC"); I triple checked that the file had saved. (I closed all instances and reopened in notepad, and there was the "ABC"). When I opened it EntLibConfig.exe, it showed up there as "XYZ". (<???? bizarre). I renamed it through EntLibConfig.exe, and went back to VS200x. The "the file has been changed..reload?" message came up. The file looked exactly the same .........but now this code Database dbAdventureWorks = DatabaseFactory.CreateDatabase("ABC"); worked. I have no idea....but I'm posting this on a off chance it helps someone. Basically, use EntLibConfig.exe to make sure the name is what you think it is.