How do I change the connection string for Enterprise Library 5.0 in my code?

Topics: Logging Application Block
May 2, 2012 at 5:34 PM

I followed the example in "Logging Application Block Hands-on-lab for Enterprise Library" (5.0).  This is working now.  I am able to log to the event log and to the database.
 
My question is this ...  The connection string for the logging is being picked up in the Web.config file.  For my application we have a method for getting the connection string from another config file.  This process is used throughout our company.  What I want to do is to set the configuration string in my code and not pick it up from the web.config file.  I have scoured the internet and have not found an example of anyone doing this.
 
In the lab, this is the statement that gets the writer to write to the log.

Private writer As LogWriter = EnterpriseLibraryContainer.Current.GetInstance(Of LogWriter)()


This is currently getting the connection string from the Web.Config (and App.Config) files.  How do I attach a connection string to the LogWriter in my code?
 

I would like to be able to do something like ...

Private writer As LogWriter = EnterpriseLibraryContainer.Current.GetInstance(Of LogWriter)()
LogWriter.ConnectionString = "blablabla"
LogWriter.Open
...
Log log log
....
LogWriter.Close


Anyone have any ideas?

May 2, 2012 at 11:00 PM

If you want to set the configuration values at runtime I would recommend using the Fluent Configuration to configure Enterprise Library.

For your example it might look something like this:

        Dim connectionString As String = GetConnectionStringFromSomeExternalSystemOrLocation()

        Dim builder = New ConfigurationSourceBuilder()
        builder.ConfigureData() _
            .ForDatabaseNamed("MyDatabase") _
              .AsDefault() _
              .ThatIs.ASqlDatabase() _
              .WithConnectionString(connectionString)

        builder.ConfigureLogging() _
            .WithOptions _
              .DoNotRevertImpersonation() _
            .LogToCategoryNamed("General") _
              .WithOptions _
                .SetAsDefaultCategory() _
              .SendTo.Database("Database Trace Listener") _
                .UseDatabase("MyDatabase") _
                  .FormatWith(New FormatterBuilder() _
                    .TextFormatterNamed("Text Formatter") _
                      .UsingTemplate("Timestamp: {timestamp}...{newline})}"))

        Dim configSource = New DictionaryConfigurationSource()
        builder.UpdateConfigurationWithReplace(configSource)
        EnterpriseLibraryContainer.Current = 
            EnterpriseLibraryContainer.CreateDefaultContainer(configSource)

        Dim logger = EnterpriseLibraryContainer.Current.GetInstance(Of LogWriter)()
        logger.Write("Test", "General")

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

May 9, 2012 at 9:57 PM

Thanks Randy,

   After a bit of tweaking, that worked.

 

 Dim builder = New Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceBuilder()
            builder.ConfigureData() _
                .ForDatabaseNamed("CenCred") _
                  .AsDefault() _
                  .ThatIs.ASqlDatabase() _
                  .WithConnectionString(ConnectionStringWrite)

            builder.ConfigureLogging() _
                .WithOptions _
                .DoNotRevertImpersonation() _
                .LogToCategoryNamed("General") _
                .WithOptions _
                .SetAsDefaultCategory() _
                    .SendTo.Database("Database Trace Listener") _
                    .WithWriteLogStoredProcedure("Logging.WriteLog") _
                    .WithAddCategoryStoredProcedure("Logging.AddCategory") _
                    .WithTraceOptions(TraceOptions.LogicalOperationStack Or TraceOptions.DateTime Or TraceOptions.Timestamp Or TraceOptions.ProcessId Or TraceOptions.ThreadId Or TraceOptions.Callstack) _
                    .UseDatabase("CenCred") _
                    .FormatWith(New FormatterBuilder() _
                        .TextFormatterNamed("Text Formatter") _
                        .UsingTemplate("Timestamp: {timestamp}{newline}, Message: {message}{newline}, Category: {category}{newline}, Priority: {priority}{newline}, EventId: {eventid}{newline}, Severity: {severity}{newline}, Title:{title}{newline}, Machine: {localMachine}{newline}, App Domain: {localAppDomain}{newline}, ProcessId: {localProcessId}{newline}, Process Name: {localProcessName}{newline}, Thread Name: {threadName}{newline}, Win32 ThreadId:{win32ThreadId}{newline}, Extended Properties: {dictionary({key} - {value}{newline})}"))

            Dim configSource = New DictionaryConfigurationSource()
            builder.UpdateConfigurationWithReplace(configSource)
            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource)

            writer = EnterpriseLibraryContainer.Current.GetInstance(Of LogWriter)()
Sep 29, 2012 at 9:40 PM

I am using code similar to above but getting this exception

            string connectionString = "Initial Catalog=Logging;Data Source=serverName;Integrated Security=SSPI;";

            
            var builder = new ConfigurationSourceBuilder();            
            builder.ConfigureData()
                .ForDatabaseNamed("serverName")
                .AsDefault()
                .ThatIs.ASqlDatabase()
                .WithConnectionString(connectionString);
            
            builder.ConfigureLogging()
                .WithOptions
                .DoNotRevertImpersonation()
                .LogToCategoryNamed("General")
                .WithOptions
                .SetAsDefaultCategory()
                .SendTo.Database("Database Trace Listener")
                .UseDatabase("serverName");            

            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);

 

 

The type ExceptionPolicyImpl has multiple constructors of length 2. Unable to disambiguate.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The type ExceptionPolicyImpl has multiple constructors of length 2. Unable to disambiguate.

Source Error:

Line 42:                 SetConnectionString();
Line 43: 
Line 44:                 Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex, "Policy");
Line 45:             }
Line 46:             base.OnException(filterContext);


Any ideas? thank you

Sep 30, 2012 at 3:28 PM

You need to configure exception handling.  See Using the Fluent Configuration API.

Please start a new thread for any other issues, thanks.

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Sep 30, 2012 at 3:36 PM

I did discover that that I cannot use Fluent + the config file approach.  At least after I removed the configuration in the .config file things seemed to work better.

Our connection strings are encrypted and I must decrypt via code and then pass into the ent lib blocks for usage.  Using Fluent API was able to set the database connection strings (for logging).

Is it possible to do the following (kinda same question, just phrased differently)

1) Have config file setting logging and exception information and set only the connection string via fluent api? (so far, i have found that if i want logging or exception to use my runtime connection string I have to set up the database, logging and exception handling options all via fluent api).  Is it possible to leave configuration for logging and exception management in the config file and ONLY configure the connection string via fluent api?

2) If I need to pass in a connection string, must i configure anything that uses that connection string via fluent api?

3) Is it possible to have settings in the config file use a connection string that is configured runtime?

 

thx

Sep 30, 2012 at 4:12 PM

Dyardy,

   In your example you have  “.UseDatabase("serverName");”  Did you mean “Servername”?  This should be the database name.
 
 

Thank you,

Russell Nesbitt <><

From: dyardy [email removed]
Sent: Saturday, September 29, 2012 3:31 PM
To: rnes1961@hotmail.com
Subject: Re: How do I change the connection string for Enterprise Library 5.0 in my code? [entlib:354260]

From: dyardy

I am using code similar to above but getting this exception

            string connectionString = "Initial Catalog=Logging;Data Source=serverName;Integrated Security=SSPI;";
 
            
            var builder = new ConfigurationSourceBuilder();            
            builder.ConfigureData()
                .ForDatabaseNamed("serverName")
                .AsDefault()
                .ThatIs.ASqlDatabase()
                .WithConnectionString(connectionString);
            
            builder.ConfigureLogging()
                .WithOptions
                .DoNotRevertImpersonation()
                .LogToCategoryNamed("General")
                .WithOptions
                .SetAsDefaultCategory()
                .SendTo.Database("Database Trace Listener")
                .UseDatabase("serverName");            
 
            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
 

The type ExceptionPolicyImpl has multiple constructors of length 2. Unable to disambiguate.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The type ExceptionPolicyImpl has multiple constructors of length 2. Unable to disambiguate.

Source Error:

Line 42:                 SetConnectionString();
Line 43: 
Line 44:                 Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex, "Policy");
Line 45:             }
Line 46:             base.OnException(filterContext);

Any ideas? thank you

Sep 30, 2012 at 4:17 PM

The issue and the cause of the exception was that I had both web.config configuration for ent lib as well as fluent api configuration.  Once I removed the web.config ent lib configuration things were better.  Servername is not the name of the database.  I found this to be the name of database named in via ent lib configuration section.

Oct 1, 2012 at 2:49 AM

 

Is it possible to do the following (kinda same question, just phrased differently)

1) Have config file setting logging and exception information and set only the connection string via fluent api? (so far, i have found that if i want logging or exception to use my runtime connection string I have to set up the database, logging and exception handling options all via fluent api).  Is it possible to leave configuration for logging and exception management in the config file and ONLY configure the connection string via fluent api?

2) If I need to pass in a connection string, must i configure anything that uses that connection string via fluent api?

3) Is it possible to have settings in the config file use a connection string that is configured runtime?