The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl, DataAccessPolicy]) failed: Object reference not set to an instance of an object. (Strategy type

Topics: Exception Handling Application Block
Jul 29, 2011 at 12:38 PM

hi,

pls help me to resolve this issue.

when im executing my project im getting above error.



Aug 1, 2011 at 6:51 AM

Hi,

Can you post the exact stack trace and possibly the code where this exception thrown? Have you checked if you have properly instantiated your objects especially your ExceptionManager class?

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us

Aug 1, 2011 at 7:25 AM

hi,

thanks for the reply.

this is the stack trace:

   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.GetExceptionPolicy(Exception exception, String policyName, ExceptionPolicyFactory factory)
   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName, ExceptionPolicyFactory policyFactory)
   at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
   at ToolGenAppDAL.ExceptionHandlers.DataAccessExceptionHandler.HandleException(Exception& ex) in C:\CODE_GEN_26JULY_UPDATED\GeneratedSolution\ToolGenAppDAL\ExceptionHandlers\DataAccessExceptionHandler.cs:line 36
   at ToolGenAppDAL.BaseDAL.ExecuteNoneQuery(SqlCommand SqlComm) in C:\CODE_GEN_26JULY_UPDATED\GeneratedSolution\ToolGenAppDAL\BaseDAL.cs:line 105
   at ToolGenAppDAL.EmployeeDAL.Insert(EmployeeEntity objEmployeeEntity) in C:\CODE_GEN_26JULY_UPDATED\GeneratedSolution\ToolGenAppDAL\EmployeeDAL.cs:line 57
   at ToolGenAppWCFServices.EmployeeService.InsertEmployee(EmployeeEntity objEmployeeEntity) in C:\CODE_GEN_26JULY_UPDATED\GeneratedSolution\ToolGenAppWCFServices\EmployeeService.svc.cs:line 28
   at SyncInvokeInsertEmployee(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)

 

 

this is the class where i have used exception policy.

 

public static class

DataAccessExceptionHandler

{public static bool HandleException(ref System.Exception

 

ex)

{

 

bool rethrow = false

;

 

if ((ex is SqlException

))

{

 

SqlException dbExp = (SqlException

)ex;

 

if

(dbExp.Number >= 50000)

{

rethrow =

ExceptionPolicy.HandleException(ex, "DataAccessCustomPolicy"

);

ex =

new DataAccessCustomException

(ex.Message);

}

 

else

{

rethrow =

ExceptionPolicy.HandleException(ex, "DataAccessPolicy"

);

 

if

(rethrow)

{

 

throw

ex;

}

}

}

 

else if (ex is System.Exception

)

{

rethrow =

ExceptionPolicy.HandleException(ex, "DataAccessPolicy"

);

 

if

(rethrow)

{

 

throw

ex;

}

}

 

return

rethrow;

}

}

 

 

 its throwing the exception in

 

 

 

else

{

rethrow =

 

ExceptionPolicy.HandleException(ex, "DataAccessPolicy"

);

 

 

if

(rethrow)

{

 

 

throw

ex;

}

}

 

 

 please help me to solve this...

Aug 1, 2011 at 8:20 AM

I suspect the value of ex is null. Have you checked in your code if that is the case? How did  you exactly call your DataAccessExceptionHandler class?

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us

Aug 1, 2011 at 9:10 AM

no value of ex is not null.

this is the function where im calling  DataAccessExceptionHandler class in catch block:

public

 

 int ExecuteNoneQuery(SqlCommand

SqlComm)

{

 

try

{

OpenSqlConnection();

SqlComm.Connection = SqlConn;

 

int

i = SqlComm.ExecuteNonQuery();

 

return

i;

}

 

catch (Exception

ex)

{

 

bool rethrow = DataAccessExceptionHandler.HandleException(ref

ex);

 

if

(rethrow)

{

 

throw

ex;

}

 

return

0;

}

 

 

finally

{

CloseSqlConnection();

}

}

 

 

Aug 2, 2011 at 6:55 AM

Hi,

I tried your code, and it works fine with me. Can you also post your config here? Also, is this a WCF application?

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us

Aug 2, 2011 at 8:26 AM

hi,

This is my Web.config and this is not WCF application but im using WCF services in this.

How it is working at your end?

Im using enterprise library 4.0 and visual studio 2010.

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null" />
    <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </configSections>
  <connectionStrings>
      <add name="ApplicationServices"
           connectionString="Data Source=syntwdd0412;Initial Catalog=ASPNETDB;Persist Security Info=True;User ID=pmdbsow;Password=syntel123$"
           providerName="System.Data.SqlClient" />
  </connectionStrings>

  <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add fileName="rolling.log" footer="----------------------------------------"
        formatter="Text Formatter" header="----------------------------------------"
        rollFileExistsBehavior="Overwrite" rollInterval="None" rollSizeKB="500"
        timeStampPattern="yyyy-MM-dd" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
        traceOutputOptions="DateTime, ProcessId, Callstack" filter="All"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
        name="Rolling Flat File Trace Listener" />
    </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=4.0.0.0, Culture=neutral, PublicKeyToken=null"
        name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Rolling Flat File Trace Listener" />
        </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="Rolling Flat File Trace Listener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
  <exceptionHandling>
    <exceptionPolicies>
      <add name="BusinessLogicCustomPolicy">
        <exceptionTypes>
          <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="NotifyRethrow" name="Exception">
            <exceptionHandlers>
              <add exceptionMessage="" exceptionMessageResourceType="" replaceExceptionType="ToolGenAppDAL.ExceptionHandlers.BusinessLogicCustomException,ToolGenAppDAL,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="Replace Handler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
      <add name="BusinessLogicPolicy">
        <exceptionTypes>
          <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="ThrowNewException" name="Exception">
            <exceptionHandlers>
              <add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
                formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="BusinessLogicLoggingHandler" />
              <add exceptionMessage="&quot;An unknown error has occurred in Business Logic Layer while processing your request. Please contract Help Desk Support at X-XXX-XXX-XXXX with Error Token ID {handlingInstanceID}.&quot;"
                exceptionMessageResourceType="" replaceExceptionType="ToolGenAppDAL.ExceptionHandlers.BusinessLogicException,ToolGenAppDAL,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="BusinessLogicReplaceHandler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
      <add name="DataAccessCustomPolicy">
        <exceptionTypes>
          <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="NotifyRethrow" name="Exception">
            <exceptionHandlers>
              <add exceptionMessage="" exceptionMessageResourceType="" replaceExceptionType="ToolGenAppDAL.ExceptionHandlers.DataAccessCustomException,ToolGenAppDAL,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="Replace Handler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
      <add name="DataAccessPolicy">
        <exceptionTypes>
          <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="ThrowNewException" name="Exception">
            <exceptionHandlers>
              <add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
                formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="DataAccessLoggingHandler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
      <add name="PassThroughPolicy">
        <exceptionTypes>
          <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="NotifyRethrow" name="Exception">
            <exceptionHandlers>
              <add exceptionMessage="" exceptionMessageResourceType="" replaceExceptionType="ToolGenAppDAL.ExceptionHandlers.PassThroughException,ToolGenAppDAL,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="PassThroughReplaceHandler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
      <add name="UserInterfacePolicy">
        <exceptionTypes>
          <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="ThrowNewException" name="Exception">
            <exceptionHandlers>
              <add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
                formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="UserInterfaceReplaceHandler" />
              <add exceptionMessage="&quot;An error occord at front end. please check.&quot;"
                exceptionMessageResourceType="" replaceExceptionType="ToolGenAppDAL.ExceptionHandlers.UserInterfaceException,ToolGenAppDAL,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="Replace Handler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>

    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IEmployeeService" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:10529/EmployeeService.svc"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IEmployeeService"
        contract="EmployeeServiceReference.IEmployeeService" name="BasicHttpBinding_IEmployeeService" />
    </client>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
</configuration>

Aug 2, 2011 at 9:50 AM

I tested it using Enterprise Library 5.0. Can you try a simple test if it still throw the same exception on simple method like:

try
{
throw new InvalidCastException();
}
catch(Exception ex)
{
          bool rethrow = ExceptionPolicy.HandleException(ex, "DataAccessPolicy");
}

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us

 

Aug 3, 2011 at 10:49 AM

hi,

i have tried with simple method also ..but still its throwing same exception...

then i have tried using enterprise library 5.0...now that error is not coming...but its throwing new exception...

Erro: Activation error occured while trying to get instance of type ExceptionPolicyImpl, key "DataAccessPolicy"

help me to solve this error.

Aug 3, 2011 at 11:41 AM

Can you tell us where did you defined your configuration file? and the code that calls the HandleException? I'm just thinking that they are on the separate application (WCF service and the client). If this is not the case, then can you send us your sample repro project?

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
Contact Us