log the exception in DB

Topics: Exception Handling Application Block, Logging Application Block
Dec 5, 2010 at 9:10 AM

I wanna log the exception into DB but can't config the app.config

when I add <exceptionhandling>block and <loggingConfiguration> to app.config with the error occur.
what is the config for use Enterprise Liberary to config for log the exception in DB(Logging database)?

this is my code :

<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>

<dataConfiguration defaultDatabase="ExampleDatabase" />
<connectionStrings>
<!--<add name="EmployeeDatabase" connectionString="Database=Employees;Server=CorpHQ;User ID=admin;Password=2g$tXD76qr"
providerName="System.Data.SqlClient" />-->

<add name="ExampleDatabase" connectionString="Data Source=FARATEAMSERVER;Initial Catalog=MyLogging;User ID=sa;Password=123x456;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add name="Database Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database"
databaseInstanceName="ExampleDatabase" writeLogStoredProcName="WriteLog"
addCategoryStoredProcName="AddCategory" formatter="Text Formatter"
traceOutputOptions="None" filter="All" />
<add name="FlatFile TraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
fileName="C:\Temp\SalaryCalculator.log" header="----------------------------------------"
footer="----------------------------------------" formatter="Text Formatter"
traceOutputOptions="None" filter="All" />
<add name="Formatted EventLog TraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
source="Enterprise Library Logging" formatter="Text Formatter"
log="Application" machineName="" traceOutputOptions="None" filter="All" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
template="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})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="FlatFile TraceListener" />
<add name="Formatted EventLog TraceListener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors &amp; Warnings">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
<add name="AssistingAdministrators">
<exceptionTypes>
<add name="Exception" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="Logging Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging"
logCategory="General" eventId="9001" severity="Error" title="Salary Calculations Service"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
priority="5" />
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
exceptionMessage="Application error. Please advise your administrator and provide them with this error code: {handlingInstanceID}"
exceptionMessageResourceName="" exceptionMessageResourceType=""
replaceExceptionType="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
<add name="ExceptionShielding">
<exceptionTypes>
<add name="Exception" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="Wrap Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
exceptionMessage="Application Error. Please contact your administrator."
exceptionMessageResourceType="" exceptionMessageResourceName=""
wrapExceptionType="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
<add name="LoggingAndReplacingException">
<exceptionTypes>
<add name="Exception" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="Logging Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging"
logCategory="General" eventId="9000" severity="Error" title="Salary Calculations Service"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
priority="5" />
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
exceptionMessage="An application error occurred and has been logged. Please contact your administrator."
exceptionMessageResourceName="" exceptionMessageResourceType=""
replaceExceptionType="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
<add name="NotifyingRethrow">
<exceptionTypes>
<add name="DivideByZeroException" type="System.DivideByZeroException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="None">
<exceptionHandlers>
<add name="Logging Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging"
logCategory="General" eventId="9002" severity="Error" title="Salary Calculations Service"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
priority="5" />
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
exceptionMessage="Application error will be ignored and processing will continue."
exceptionMessageResourceName="" exceptionMessageResourceType=""
replaceExceptionType="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
<add name="Exception" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="Wrap Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
exceptionMessage="An application error has occurred." exceptionMessageResourceType=""
exceptionMessageResourceName="" wrapExceptionType="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
<add name="ReplacingException">
<exceptionTypes>
<add name="Exception" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
exceptionMessage="Application Error. Please contact your administrator."
exceptionMessageResourceName="" exceptionMessageResourceType=""
replaceExceptionType="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
<add name="SalaryServicePolicy">
<exceptionTypes>
<add name="Exception" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.FaultContractExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF"
exceptionMessage="Service error. Please contact your administrator."
faultContractType="ExceptionHandlingExample.SalaryService.SalaryCalculationFault, ExceptionHandlingExample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
name="Fault Contract Exception Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ISalaryService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="">
<extendedProtectionPolicy policyEnforcement="Never" />
</transport>
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:11150/SalaryService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISalaryService"
contract="SalaryService.ISalaryService" name="WSHttpBinding_ISalaryService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>



-----------------------------------------------------------------------------------------------



>//===============================================================================
// Microsoft patterns & practices Enterprise Library
// Exception Handling Application Block Examples
//===============================================================================
// Copyright © Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================

using System;

// references to configuration namespaces (required in all examples)
using DevGuideExample.MenuSystem;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

// references to application block namespace(s) for these examples
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using ExceptionHandlingExample.SalaryService;
using System.ServiceModel;
using System.ComponentModel;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Collections.Generic;
using System.Diagnostics;

namespace ExceptionHandlingExample
{
class Program
{
static ExceptionManager exManager;
static LogWriter defaultWriter;

static void Main(string[] args)
{
#region Resolve the required object

// Resolve the default LogWriter object from the container.
// The actual concrete type is determined by the configuration settings.
defaultWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();

// Resolve the default ExceptionManager object from the container.
exManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();

#endregion

#region Main menu routines

var app = new MenuDrivenApplication("Exception Handling Block Developer's Guide Examples",
DefaultNoExceptionShielding,
WithWrapExceptionShielding,
WithReplaceExceptionShielding,
LoggingTheException,
ShieldingExceptionsInWCF,
ExecutingCodeAroundException,
ProvidingAdminAssistance);

app.Run();

#endregion
}

// You can run the examples in one of two ways inside Visual Studio:
// -----------------------------------------------------------------
// 1: By starting them with F5 (debugging mode) and then pressing F5 again
// when the debugger halts at the exception in the SalaryCalculator class,
// or:
// 2: By starting them Ctrl-F5 (non-debugging mode).
[Description("Typical Default Behavior without Exception Shielding")]
static void DefaultNoExceptionShielding()
{
Console.WriteLine("Getting salary for 'jsmith'...");
Console.WriteLine();
SalaryCalculator calc = new SalaryCalculator();
Console.WriteLine("Result is: {0}", calc.GetWeeklySalary("jsmith", 0));
}

[Description("Behavior After Applying Exception Shielding with a Wrap Handler")]
static void WithWrapExceptionShielding()
{
Console.WriteLine("Getting salary for 'jsmith'...");
Console.WriteLine();
// NOTE: Any exception raised when creating the SalaryCalculator
// class instance will not be handled using this approach.
SalaryCalculator calc = new SalaryCalculator();
var result = exManager.Process(() => calc.GetWeeklySalary("jsmith", 0), "ExceptionShielding");
Console.WriteLine("Result is: {0}", result);
// NOTE: If you do not need to return the value from the function, you can
// simply consume it within the lambda expression. This is a simple example:
// ------------------------------
//exManager.Process(() =>
// {
// SalaryCalculator calc = new SalaryCalculator();
// Console.WriteLine("Result is: {0}", calc.GetWeeklySalary("jsmith", 0));
// },
// "ExceptionShielding");
// ------------------------------
// This approach also allows you to handle any exception raised by creating the
// instance of the SalaryCalculator class.
}

[Description("Behavior After Applying Exception Shielding with a Replace Handler")]
static void WithReplaceExceptionShielding()
{
Console.WriteLine("Getting salary for 'jsmith'...");
Console.WriteLine();
// NOTE: Any exception raised when creating the SalaryCalculator
// class instance will not be handled using this approach.
SalaryCalculator calc = new SalaryCalculator();
decimal result = exManager.Process(() => calc.GetWeeklySalary("jsmith", 0), "ReplacingException");
Console.WriteLine("Result is: {0}", result);
}

[Description("Logging an Exception to Preserve the Information it Contains")]
static void LoggingTheException()
{
try
{
Console.WriteLine("Getting salary for 'jsmith'...");
Console.WriteLine();
// NOTE: Any exception raised when creating the SalaryCalculator
// class instance will not be handled using this approach.
var calc = new SalaryCalculator();
decimal result = exManager.Process(() => calc.GetWeeklySalary("jsmith", 0), "LoggingAndReplacingException");
Console.WriteLine("Result is: {0}", result);
}
catch (Exception ex)
{
// Create a Dictionary of extended properties
Dictionary<string, object> exProperties = new Dictionary<string, object>();
exProperties.Add("Extra Information", "Some Special Value");

// Create a LogEntry using the constructor parameters.
LogEntry entry = new LogEntry(ex.Message, "Database",8, 9009, TraceEventType.Error, "Logging Block Examples", exProperties);
defaultWriter.Write(entry);

MenuOption.ShowExceptionDetails(ex);
Console.WriteLine("Open the Windows Application Event Log to see the logged exception details.");
}
}

[Description("Applying Exception Shielding at WCF Application Boundaries")]
static void ShieldingExceptionsInWCF()
{
// You can run this example in one of three ways:
// - Inside VS by starting it with F5 (debugging mode) and then pressing F5 again
// when the debugger halts at the exception in the SalaryCalculator class.
// - Inside VS by right-clicking SalaryService.svc in Solution Explorer and selecting
// View in Browser to start the service, then pressing Ctrl-F5 (non-debugging mode)
// to run the application.
// - By starting the SalaryService in VS (as in previous option) and then running the
// executable file ExceptionHandlingExample.exe in the bin\debug folder directly.

try
{
Console.WriteLine("Getting salary for 'jsmith' from WCF Salary Service...");
// Create an instance of the client for the WCF Salary Service.
ISalaryService svc = new SalaryServiceClient();
// Call the method of the service to get the result.
Console.WriteLine("Result is: {0}", svc.GetWeeklySalary("jsmith", 0));
}
catch (Exception ex)
{
// Show details of the exception returned to the calling code.
MenuOption. ShowExceptionDetails(ex);
// Show details of the fault contract returned from the WCF service.
ShowFaultContract(ex);
}
}

[Description("Executing Custom Code Before and After Handling an Exception")]
static void ExecutingCodeAroundException()
{
//------------------------------------------------------
// Note that this is a somewhat contrived exeample designed to
// show how you can use the HandleException method, detect different
// exception types, and ignore specific types of exceptions.
try
{
// Execute code that raises a DivideByZeroException.
Console.WriteLine("Getting salary for 'jsmith' ... this will raise a DivideByZero exception.");
SalaryCalculator calc = new SalaryCalculator();
Console.WriteLine("Result is: {0}", calc.RaiseDivideByZeroException("jsmith", 0));
}
catch (Exception ex)
{
Exception newException;
bool rethrow = exManager.HandleException(ex, "NotifyingRethrow", out newException);
if (rethrow)
{
// Exception policy setting is "ThrowNewException".
// Code here to perform any clean up tasks required.
// Then throw the exception returned by the exception handling policy.
throw newException;
}
else
{
// Exception policy setting is "None" so exception is not thrown.
// Code here to perform any other processing required.
// In this example, just ignore the exception and do nothing.
Console.WriteLine("Detected and ignored Divide By Zero Error - no value returned.");
}
}
try
{
// Now execute code that raises an ArgumentOutOfRangeException.
// Use the same exception handling policy and catch section code.
Console.WriteLine();
Console.WriteLine("Getting salary for 'jsmith' ... this will raise an ArgumentOutOfRange exception.");
SalaryCalculator calc = new SalaryCalculator();
Console.WriteLine("Result is: {0}", calc.RaiseArgumentOutOfRangeException("jsmith", 0));
}
catch (Exception ex)
{
Exception newException;
bool rethrow = exManager.HandleException(ex, "NotifyingRethrow", out newException);
if (rethrow)
{
// Exception policy setting is "ThrowNewException".
// Code here to perform any clean up tasks required.
// Then throw the exception returned by the exception handling policy.
throw newException;
}
else
{
// Exception policy setting is "None".
// Code here to perform any other processing required.
// In this example, just ignore the exception and do nothing.
Console.WriteLine("Detected and ignored Divide By Zero Error - no value returned.");
}
}
}

[Description("Providing Assistance to Administrators for Locating Exception Details")]
static void ProvidingAdminAssistance()
{
Console.WriteLine("Getting salary for 'jsmith'...");
Console.WriteLine();
// NOTE: Any exception raised when creating the SalaryCalculator
// class instance will not be handled using this approach.
SalaryCalculator calc = new SalaryCalculator();
decimal result = exManager.Process(() => calc.GetWeeklySalary("jsmith", 0), "AssistingAdministrators");
Console.WriteLine("Result is: {0}", result);
}

#region Auxiliary routines

private static void ShowFaultContract(Exception ex)
{
var faultContract = ex as FaultException<SalaryCalculationFault>;
if (faultContract != null)
{
SalaryCalculationFault salaryCalculationFault = faultContract.Detail;
Console.WriteLine("Fault contract detail: ");
Console.WriteLine("Fault ID: {0}", salaryCalculationFault.FaultID);
Console.WriteLine("Message: {0}", salaryCalculationFault.FaultMessage);
}
}

#endregion
}
}



--------------------------------------------------------------------------------------------
I don't why LoggingTheException()
can't log the exception in database,please help me.
and error occur in red line !!!
Dec 6, 2010 at 6:35 AM

First thing you need to do is to make sure that your Database trace listener is added in a Logging Category sources which your Logging Exception Handler uses.

    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="FlatFile TraceListener" />
          <add name="Formatted EventLog TraceListener" />
          <add name="Database Trace Listener" />
        </listeners>
      </add>
    </categorySources>

As for the logging exception in line "defaultWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();" please post the exact exception encountered. Just one hint though, if you are already using VS2010 or .NET 4.0 make sure that your project target the full .NET Framework instead of the Client Profile (Right click on project, select Properties) (this is a known issue in entlib 5). If this is not the case please post the details of the exception.

 

Gino Terrado
Global Technologies and Solutions
Avanade, Inc.
 entlib.support@avanade.com

Dec 6, 2010 at 7:50 AM

I add <add name="Database Trace Listener" /> to <categorySources> block but twice faced with this exception in "defaultWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();":

Microsoft.Practices.ServiceLocation.ActivationException was unhandled
  Message=Activation error occured while trying to get instance of type LogWriter, key ""
  Source=Microsoft.Practices.ServiceLocation
  StackTrace:
       at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
       at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService]()
       at ExceptionHandlingExample.Program.Main(String[] args) in C:\Documents and Settings\j.fathi.FARABORD\My Documents\Downloads\EntLib Dev Guide RC - Code Samples\ExceptionHandling\ExceptionHandling\Program.cs:line 40
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: Microsoft.Practices.Unity.ResolutionFailedException
       Message=Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Database cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:

  Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl,LogWriter.__default__ (mapped from Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, (none))
  Resolving parameter "structureHolder" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl(Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder structureHolder, Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation.ILoggingInstrumentationProvider instrumentationProvider, Microsoft.Practices.EnterpriseLibrary.Logging.ILoggingUpdateCoordinator updateCoordinator)
    Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder,LogWriterStructureHolder.__default__ (mapped from Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder, (none))
    Resolving parameter "traceSources" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder(System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.Logging.Filters.ILogFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] filters, System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] traceSourceNames, System.Collections.Generic.IEnumerable`1[[Microsoft.Practices.EnterpriseLibrary.Logging.LogSource, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] traceSources, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource allEventsTraceSource, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource notProcessedTraceSource, Microsoft.Practices.EnterpriseLibrary.Logging.LogSource errorsTraceSource, System.String defaultCategory, System.Boolean tracingEnabled, System.Boolean logWarningsWhenNoCategoriesMatch, System.Boolean revertImpersonation)
      Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogSource,CauseLoggingError
      Resolving parameter "traceListeners" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.LogSource(System.String name, System.Collections.Generic.IEnumerable`1[[System.Diagnostics.TraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] traceListeners, System.Diagnostics.SourceLevels level, System.Boolean autoFlush, Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation.ILoggingInstrumentationProvider instrumentationProvider)
        Resolving Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.ReconfigurableTraceListenerWrapper,CauseLoggingError (mapped from System.Diagnostics.TraceListener, CauseLoggingError)
        Resolving parameter "wrappedTraceListener" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.ReconfigurableTraceListenerWrapper(System.Diagnostics.TraceListener wrappedTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.ILoggingUpdateCoordinator coordinator)
          Resolving Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener,CauseLoggingError‌implementation (mapped from System.Diagnostics.TraceListener, CauseLoggingError‌implementation)
          Resolving parameter "database" of constructor Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener(Microsoft.Practices.EnterpriseLibrary.Data.Database database, System.String writeLogStoredProcName, System.String addCategoryStoredProcName, Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.ILogFormatter formatter)
            Resolving Microsoft.Practices.EnterpriseLibrary.Data.Database,DoesNotExist

       Source=Microsoft.Practices.Unity
       TypeRequested=LogWriter
       StackTrace:
            at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
            at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
            at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
            at Microsoft.Practices.Unity.UnityServiceLocator.DoGetInstance(Type serviceType, String key)
            at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
       InnerException: System.InvalidOperationException
            Message=The type Database cannot be constructed. You must configure the container to supply this value.
            Source=Microsoft.Practices.Unity
            StackTrace:
                 at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context, SelectedConstructor selectedConstructor)
                 at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey)
                 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
                 at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
                 at BuildUp_Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener(IBuilderContext )
                 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
                 at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
                 at BuildUp_Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.ReconfigurableTraceListenerWrapper(IBuilderContext )
                 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
                 at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
                 at Microsoft.Practices.Unity.ResolvedArrayWithElementsResolverPolicy.DoResolve[T](IBuilderContext context, IDependencyResolverPolicy[] elementPolicies)
                 at Microsoft.Practices.Unity.ResolvedArrayWithElementsResolverPolicy.Resolve(IBuilderContext context)
                 at BuildUp_Microsoft.Practices.EnterpriseLibrary.Logging.LogSource(IBuilderContext )
                 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
                 at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
                 at Microsoft.Practices.Unity.ResolvedArrayWithElementsResolverPolicy.DoResolve[T](IBuilderContext context, IDependencyResolverPolicy[] elementPolicies)
                 at Microsoft.Practices.Unity.ResolvedArrayWithElementsResolverPolicy.Resolve(IBuilderContext context)
                 at BuildUp_Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterStructureHolder(IBuilderContext )
                 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
                 at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
                 at BuildUp_Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl(IBuilderContext )
                 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
                 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
                 at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
            InnerException:

what gonna do?!?


Dec 6, 2010 at 11:43 AM

Weird :( ... I already tried explicitly copy and pasting your config and it works fine upon instantiating an instance of the logwriter from my end. 

Are you sure you already check the target framework of your project? Also, could you at least try in your application code to just have the LogWriter instantiation using your config and see if it will work. If the issue still persist could you send your sample app to us for further investigation (entlib.support@avanade.com).

Gino Terrado
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com
 

 

 

Dec 6, 2010 at 11:28 PM

Your entlib configuration should also be defined in the app.config of an executable/host project.  In  your case, your app.config is probably in a class library.

 

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Dec 8, 2010 at 6:22 AM

I do every config again as soon as I can and give a feed back to you.

so many thanks for hrlp

Dec 11, 2010 at 2:11 PM
I send my project to "entlib.support@avanade.com" with subject:"logging exception in Database" from "ozzy_fat2000@yahoo.com" please help me.
Dec 13, 2010 at 11:56 AM

We haven't have your email yet. Kindly resend it. Thanks.

 Gino Terrado
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com
 


Dec 14, 2010 at 2:47 AM

You could also post only the relevant code which doesn't log.  It's a bit hard to read through all the code, please only post which method is it.  I also noticed you have calls to the Write method against a LogWriter object (defaultWriter.Write).  Was it the code which doesn't successfully log?  If yes, then that is expected because you specified the category "Database" but your config doesn't have such category. 

And do you really need that logging code when you already have a Logging Handler included in some of your exception policies?  That should do the logging without the need for you to manually put logging codes in your WCF service.

 

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com