Enterprise Library 6.0 WCF Exception Handling Shielding Exception is not working

Topics: Exception Handling Application Block
Jul 24, 2013 at 6:37 PM
Please see below issue detail-

I downloaded Entlib 6.0 from codeplex.com and created custom configuration source as Entlib.config and referred as a source in WCF Web.config. And called the C# code to write Exception but not working.

  1. Web.config
    <?xml version="1.0"?>
    <configuration>
    <configSections>
    <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <enterpriseLibrary.ConfigurationSource selectedSource="fileSource"
    parentSource="fileSource">
    <sources>
    <add name="fileSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    filePath="C:\Projects_2012\SmartClientLogging\WindowsFormsApplication1\TaskListWCF\Entlib.config" />
    </sources>
    <redirectSections>
    <add sourceName="fileSource" name="loggingConfiguration" />
    </redirectSections>
    </enterpriseLibrary.ConfigurationSource>
    <appSettings>
    </appSettings>
    <system.web>
    <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
    <behaviors>
    <serviceBehaviors>
    <behavior name="ITaskService.ServiceBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />          
    </behavior>
    </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
    <service name="Logging.TaskListServiceImplementation.TaskService" behaviorConfiguration="ITaskService.ServiceBehavior">
    <endpoint address="" binding="wsHttpBinding" contract="Logging.TaskListServiceContract.ITaskService" bindingConfiguration="WSHttpBinding_ITaskService" />        
    </service>
    </services>
    <bindings>
    <wsHttpBinding>
    <binding name="WSHttpBinding_ITaskService" closeTimeout="03:00:00"
        openTimeout="03:00:00" receiveTimeout="03:10:00" sendTimeout="03:00:00"
        bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
        maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
        messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
        allowCookies="false">
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
          maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <reliableSession ordered="true" inactivityTimeout="03:10:00"
          enabled="false" />
      <security mode="Message">
        <transport clientCredentialType="Windows" proxyCredentialType="None"
            realm="" />
        <message clientCredentialType="Windows" negotiateServiceCredential="true"
            algorithmSuite="Default" />
      </security>
    </binding>
    </wsHttpBinding>
    </bindings>
    </system.serviceModel>
    </configuration>

  1. Entlib.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
 defaultCategory="Important" logWarningsWhenNoCategoriesMatch="true">
<listeners>
  <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
    fileName="C:\Projects_2012\SmartClientLogging\WindowsFormsApplication1\TaskListWCF\App_Data\RollingFlatFile.log" footer="----------------------------------------"
    formatter="Text Formatter" header="----------------------------------------"
    rollFileExistsBehavior="Increment" rollInterval="None" rollSizeKB="20"
    timeStampPattern="yyyy-MM-dd" maxArchivedFiles="3" traceOutputOptions="None"
    filter="All" />
</listeners>
<formatters>
  <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
    template="Timestamp: {timestamp(local)}{tab}Message: {message}{tab}Category: {category}{tab}Priority: {priority}{tab}EventId: {eventid}{tab}ActivityId: {property(ActivityId)}{tab}Severity: {severity}{tab}Title:{title}{tab}"
    name="Brief Format Text" />
  <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
    template="Timestamp: {timestamp}{tab}Message: {message}{tab}Category: {category}{tab}Priority: {priority}{tab}EventId: {eventid}{tab}Severity: {severity}{tab}Title: {title}{tab}Activity ID: {property(ActivityId)}{tab}Machine: {localMachine}{tab}App Domain: {localAppDomain}{tab}ProcessId: {localProcessId}{tab}Process Name: {localProcessName}{tab}Thread Name: {threadName}{tab}Win32 ThreadId:{win32ThreadId}{tab}Extended Properties: {dictionary({key} - {value}{tab})}"
    name="Text Formatter" />
</formatters>
<logFilters>
  <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
    minimumPriority="2" maximumPriority="99" name="Priority Filter" />
  <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
    enabled="true" name="LogEnabled Filter" />
  <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
    categoryFilterMode="AllowAllExceptDenied" name="Category Filter">
    <categoryFilters>
      <add name="BlockedByFilter" />
    </categoryFilters>
  </add>
</logFilters>
<categorySources>
  <add switchValue="All" name="Important">
    <listeners>
      <!--<add name="Formatted EventLog TraceListener" />-->
      <add name="Rolling Flat File Trace Listener" />
    </listeners>
  </add>
</categorySources>
<specialSources>
  <allEvents switchValue="All" name="All Events" />
  <notProcessed switchValue="All" name="Unprocessed Category">
    <listeners>
      <!--<add name="UnprocessedFlatFile" />-->
    </listeners>
  </notProcessed>
  <errors switchValue="All" name="Logging Errors &amp; Warnings">
    <listeners>
      <!--<add name="Formatted EventLog TraceListener" />-->
    </listeners>
  </errors>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
  <add name="WCF Exception Shielding">
    <exceptionTypes>
      <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        postHandlingAction="ThrowNewException">
        <exceptionHandlers>
          <add type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF.FaultContractExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            exceptionMessage="An unexpected error has occurred in this service.  Please contact the service adminstrator." faultContractType="Logging.TaskListServiceContract.TestFaultContract, Logging.TaskListServiceContract, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
            name="Fault Contract Exception Handler" />
        </exceptionHandlers>
      </add>
    </exceptionTypes>
  </add>
</exceptionPolicies>
</exceptionHandling>
</configuration>

C# Code
[ExceptionShielding("WCF Exception Shielding")]
public class TaskService : ITaskService
{       
    public string Test()
    {                     
        throw new Exception("Testing Exception Handling");
        return string.Format("You entered:", "Test");
    }                 }
Work arounds are
  1. adding the following code in the Test() method
        IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
        LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
        Logger.SetLogWriter(logWriterFactory.Create());&
  2. In global.asax adding in Application_Start
    ExceptionPolicy.SetExceptionManager(new ExceptionPolicyFactory().CreateManager());
I am using the exception sheilding on WCF and using channel factory to connect from client to WCF service. Could you please provide help to resolve the issue other than above 2 work arounds and thanks in advance.
Jul 26, 2013 at 6:51 AM
You don't want to run the configuration for logging in the Test() method: that should be done at startup.
        protected void Application_Start(object sender, EventArgs e)
        {
            IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
            LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
            Logger.SetLogWriter(logWriterFactory.Create());

            ExceptionPolicyFactory exceptionPolicyFactory = new ExceptionPolicyFactory(configurationSource);
            ExceptionPolicy.SetExceptionManager(exceptionPolicyFactory.CreateManager());
        }

Note the changes to the exception configuration to use the config source.

Also, in the Entlib.config file you need to declare the exception configuration configSection:
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>

With those changes it should work properly.

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Jul 26, 2013 at 8:12 PM
Edited Jul 26, 2013 at 8:14 PM
Thanks Randy

It is working once adding Global.asax file and your code and Entlib changes on the WCF service . But is there any work around avoid adding Global.asax in the WCF service. Please advise
Jul 27, 2013 at 9:30 PM
Edited Jul 27, 2013 at 9:47 PM
Basically, what needs to happen is to run some bootstrap code at startup. Within IIS, Global.asax is a standard way of doing this but there are many other ways:
~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to