Object synchronization method was called from an unsynchronized block of code

Topics: Logging Application Block
Jun 17, 2010 at 2:47 PM

Hi,

I'm using the following lines to test some logging:

   Dim writer As LogWriter = EnterpriseLibraryContainer.Current.GetInstance(Of LogWriter)()
   writer.Write("I'm a log entry created by the Logging block!")

Everytime I call this code I get the next error:

A first chance exception of type
'System.Threading.SynchronizationLockException' occurred in
Microsoft.Practices.Unity.dll

Additional information: Object synchronization method was called from
an unsynchronized block of code

What's wrong??

 

 

Jun 18, 2010 at 3:00 AM

You're most likely encountering this issue.

 

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

Jun 18, 2010 at 7:27 AM

Sarah,

It indeed look's like it's the issue you mentioned.
When I publish my application, the logging lines work correctly.

But how to get around the error in debug mode?
At the debug exceptions window in Visual Studio I turned off the "System.Threading.SynchronizeationLockException" to thrown, but now I get the following error:

A first chance exception of type 'System.ArgumentException' occurred in Microsoft.Practices.EnterpriseLibrary.Common.dll

Additional information: The type 'Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler,
 Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging' cannot be resolved.
 Please verify the spelling is correct or that the full type name is provided.

How to debug my application without getting an error when logging?

Onno Sloof

The Netherlands

 

Jun 18, 2010 at 7:46 AM

Go to Tools -> Options.  Click on Debugging on the left side panel and uncheck Enable Just My Code.   The effect is that, your application won't break on exceptions throwned by the user, only those which are unhandled. 

 

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

Jun 18, 2010 at 9:24 AM

thanks for the reply, but uncheck "Enable Just My Code" is realy no option.
When I uncheck this setting, my app breaks on a lot of other things.
For example, I'v de following lines:

If My.Computer.Network.IsAvailable = True And ApplicationDeployment.IsNetworkDeployed = True Then
   MyApp = ApplicationDeployment.CurrentDeployment
End If

 In this and a lot of other lines (when I press continue) I get the following error:

A first chance exception of type 'System.Deployment.Application.InvalidDeploymentException'
occurred in System.Deployment.dll

Additional information: Application identity is not set.

I can say, it is a big, complex application, and I realy want to log thru Enterprise library, but it seems to be to complicated to get is to work.
But when I test an exersise of the logging part of the hands-on it works great.

Onno Sloof

Jun 18, 2010 at 5:51 PM

When it breaks there, you just need to hit F5 and things will continue running.

This is really a debugger issue, unfortunately - the exception is expected and correctly handled.

Jul 15, 2010 at 6:31 PM

Hi,

I am using Enterprise Library 5 - I am getting this error when I run my application in debug mode. 

A first chance exception of type 'System.Threading.SynchronizationLockException' occurred in Microsoft.Practices.Unity.DLL

A first chance exception of type 'System.Threading.SynchronizationLockException' occurred in Microsoft.Practices.Unity.DLL

A first chance exception of type 'System.Security.SecurityException' occurred in mscorlib.dll

A first chance exception of type 'System.Security.SecurityException' occurred in System.dll

A first chance exception of type 'System.Security.SecurityException' occurred in mscorlib.dll

A first chance exception of type 'System.Security.SecurityException' occurred in System.dll

 I am using VS 2010 and trying to call Logger.Write(myLog).  The exception occurs when the break point hits Logger.write.   Here’s my code:

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'Testing

        If Not Page.IsPostBack Then

            If Request.IsAuthenticated Then

                If Roles.IsUserInRole("IT") Then

                    lblInfo.Text = "User is in IT Role - Success"

                    LogInfo()

                Else

                    lblInfo.Text = "User is in NOT in IT Role - Failure"

                End If

            End If

         End If

    End Sub

     Private Sub LogInfo()

         Try

            Dim myLog As New LogEntry

            With myLog

                .EventId = 6000

                .Title = "Test_Checkout"

                .Severity = TraceEventType.Information

                .Message = "LoggedIn - " & User.Identity.Name

            End With

            Logger.Write(myLog)

        Catch ex As Exception

            Dim exp As String = ex.Message

            ExceptionPolicy.HandleException(ex, "Log Only")

        End Try

      End Sub

 Plese help me resolve this issue.  Any help is appreciated.

Thank you,

Vinny

 

Jul 16, 2010 at 1:00 AM

If you run it in release mode, does your program still halt on the exception? 

 

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

Jul 16, 2010 at 4:14 PM
Edited Jul 16, 2010 at 4:44 PM
Hi Sarah,

In release mode the program does not halt on the exception. But nothing gets written to the log table.  I added the category source to log which was missing earlier. Below is the code:
 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

          If Not Page.IsPostBack Then

           If Request.IsAuthenticated Then

               If Roles.IsUserInRole("IT") Then

                   lblInfo.Text = "User is in IT Role - Success"

                   LogInfo()

               Else

                   lblInfo.Text = "User is in NOT in IT Role - Failure"

               End If

           End If

       End If

   End Sub

 

Private Sub LogInfo()

        Try

           Dim myLog As New LogEntry

           With myLog

               .Categories.Add("General")

               .EventId = 6000

               .Title = "Test_Enrollment"

               .Severity = TraceEventType.Information

               .Message = "LoggedIn - " & User.Identity.Name

           End With

           Logger.Write(myLog)

       Catch ex As Exception

           Dim exp As String = ex.Message

           ExceptionPolicy.HandleException(ex, "Log Only")

       End Try

     End Sub

 I am using Custom Role provider.  The Security Exception that I am getting, could it be related to this?  Why is the logging not working? Am I missing any settings? Here's my web.config:

<?xml version="1.0"?>

 <configuration>

<configSections>

   <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>

 <loggingConfiguration name="LoggingApplicationBlock" tracingEnabled="true"

   defaultCategory="General">

   <listeners>

     <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       source="Enterprise Library Logging" formatter="DefaultTextFormatter"

        log="TAR_Enrollment" machineName="." traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, Callstack" />

     <add name="DatabaseTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

        databaseInstanceName="DatabaseLogging" writeLogStoredProcName="WriteLog"

       addCategoryStoredProcName="AddCategory" formatter="DefaultTextFormatter" />

     <add name="EmailTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       toAddress="chris@gmail.com;

       fromAddress="sysadmin@#####.com" subjectLineStarter="Message from TAR_Enrollment"

       smtpServer="mailrelay.####.com" formatter="DefaultTextFormatter"

       filter="Information" />

     <add name="ErrorRollingFlatFileTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       fileName="C:\TAR_EnrollmentLogging\rolling.logrolling.log" footer="********** End **********"

       formatter="DefaultTextFormatter" header="********* Begin **********"

       rollFileExistsBehavior="Increment" rollInterval="Week" maxArchivedFiles="1000" />

     <add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       fileName="C:\Test\Mytrace.log" formatter="DefaultTextFormatter" traceOutputOptions="LogicalOperationStack" />

   </listeners>

   <formatters>

     <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

       template="{timestamp(local:[ddd dd MMM yyyy HH:mm:ss.fff])} [{threadName}]{tab}[{message}]{tab}{dictionary([{key} - {value}] )}&#xA;"

       name="DefaultTextFormatter" />

   </formatters>

   <categorySources>

     <add switchValue="All" name="General">

       <listeners>

         <add name="Event Log Listener" />

         <add name="DatabaseTraceListener" />

         <add name="ErrorRollingFlatFileTraceListener" />

         <add name="Flat File Trace Listener" />

       </listeners>

     </add>

     <add switchValue="Information" name="Critical">

       <listeners>

         <add name="ErrorRollingFlatFileTraceListener" />

         <add name="DatabaseTraceListener" />

       </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="Event Log Listener" />

         <add name="ErrorRollingFlatFileTraceListener" />

       </listeners>

     </errors>

   </specialSources>

</loggingConfiguration>

<exceptionHandling>

   <exceptionPolicies>

     <add name="Log Only Policy">

       <exceptionTypes>

         <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

           postHandlingAction="NotifyRethrow">

           <exceptionHandlers>

             <add name="Logging Exception Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

               logCategory="Critical" eventId="6000" severity="Error" title="Enterprise Library Exception Handling"

               formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"

               priority="0" />

           </exceptionHandlers>

         </add>

       </exceptionTypes>

     </add>

     <add name="Notify Policy">

       <exceptionTypes>

         <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

           postHandlingAction="NotifyRethrow">

           <exceptionHandlers>

             <add name="Logging Exception Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

                logCategory="Critical" eventId="6000" severity="Error" title="Enterprise Library Exception Handling"

               formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"

               priority="0" />

           </exceptionHandlers>

         </add>

       </exceptionTypes>

     </add>

   </exceptionPolicies>

</exceptionHandling>

<connectionStrings>

   <add name="EnrollmentDataProvider" connectionString="Server=tardev11;database=TAR_Enrollment;Trusted_Connection=true;"

     providerName="System.Data.SqlClient" />

   <add name="DatabaseLogging" connectionString="Data Source=tardev11;Initial Catalog=Logging;Integrated Security=True"

     providerName="System.Data.SqlClient" />

   <add name="DB2DataProviderDDTek" connectionString="Host=10.168.8.6;Port=446;Database=S10055AD;User ID=####;Password=####;Collection=IJDTOBJ71;Pooling=true;Connection Reset=true;Max Pool Size=15;Load Balance Timeout=0;Enlist=false;Min Pool Size=0;CursorsWithHold=false;Connection Retry Count=1"

     providerName="DDTek.DB2" />

</connectionStrings>

<appSettings>

   <add key="DefaultApplicationTitle" value="TAR_Enrollment" />

   <add key="CurrentApplicationEventID" value="6000" />

</appSettings>

<system.web>

   <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />

 

   <authentication mode="Windows">

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

   </authentication>

      <roleManager enabled="true" defaultProvider="EnrollmentRoleProvider"

     cacheRolesInCookie="true"

     cookieName=".TARROLES"

     cookieTimeout="30"

     cookiePath="/"

     cookieRequireSSL="false"

     cookieSlidingExpiration="true"

     cookieProtection="All" >

     <providers>

       <clear/>

       <!--<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />

       <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />-->

       <add name="EnrollmentRoleProvider" type="PrincetonReview.Enrollment.RoleProvider.EnrollmentRoleProvider" connectionStringName="EnrollmentDataProvider" applicationName="TAREnrollment" />

     </providers>

   </roleManager>

  

</system.web>

 

<location path="BatchProcess">

   <system.web>

     <authorization>

       <allow roles="Marketing, IT" />

       <deny users="*" />

     </authorization>

   </system.web>

</location>

<system.webServer>

     <modules runAllManagedModulesForAllRequests="true"/>

</system.webServer>

</configuration>

 

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

Read the full discussion online.

To add a post to this discussion, reply to this email (entlib@discussions.codeplex.com)

To start a new discussion for this project, email entlib@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe on CodePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at CodePlex.com

 

Jul 17, 2010 at 4:36 AM

There are other trace listeners configured under the General category, do they generate the expected logs and only the database trace listener doesn't perform as expected?  What is the exact Security exception message?

 

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

Jul 17, 2010 at 2:28 PM

Hi Sarah,

None of the trace listeners are logging, even the Event Logger.  Following is the Security exception that I see in my Immediate Window in VS 2010 when I run the app on my local machine and this occurs as soon as I hit the Logger.Write method.  Is the connection string setting ok in my config file?

A first chance exception of type 'System.Security.SecurityException' occurred in mscorlib.dll

A first chance exception of type 'System.Security.SecurityException' occurred in System.dll

 

Thanks,

Vinny

Jul 19, 2010 at 10:30 AM

Hi Vinny,

I've just copied and pasted your configuration above and I think I was able to reproduce your problem from my end. If we indeed encounter the same issue then my finding is this.

In your Event Log Listener tracelistener you are registering an event source with Source Name "Enterprise Library Logging" to a Log Name of "TAR_Enrollment" given that in my machine I already have a registered Source Name same with "Enterprise Library Logging" to a different Log Name (which is one of my assumption too in your end) nothing happens every time the Logger.Write get executed. Note that an event source can only be registered to only one Log Name.

So the resolution can be to used different Source Name. Please try this and see if this will resolve your problem. 

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

 

 

Jul 19, 2010 at 2:04 PM

Hi Geno,

Thank you for your response.  The logger did work when I changed my Event log Listener log name.  I also tried removing the listener from the 'General' log source and it did write to all the other listeners without any problem.  Yes, it was the settings in the Event Log that was causing this grief. 

Thank you for pointing out the problem.  I appreciate it.

Regards,

Vinny