Logging with Custom DB Trace Listener

Topics: Logging Application Block
Sep 10, 2011 at 6:27 AM

Hi,

  I am Logging to Database using Custom Trace Listener. The logic works fine when i run the application from Local ASP.NET Development Server. But When I deploy the application to my web server, The log is happening only in event viewer. Database Log getting failed.

 

To check the exception log,  i am deleting a master record which has reference to the other table using a procedure. When i delete the record, exception will be handled.

For your reference, i have given my web.config and event log content below.

 

Web.Config

-----------

<loggingConfiguration name="" 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="Text Formatter"
          log="" machineName="." traceOutputOptions="None" />
      <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          DatabaseInstance="LoggingConnectionString" WriteLogSp="WriteLog" AddCategorySp="AddCategory"
          type="Unibetech.LoggingServices.BasicDatabaseTraceListener, Unibetech.LoggingServices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
          name="BasicDatabaseTraceListener" />
    </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: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
          name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Event Log Listener" />
        </listeners>
      </add>
      <add switchValue="All" name="Database">
        <listeners>
          <add name="BasicDatabaseTraceListener" />
        </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" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
 <exceptionHandling>
  <exceptionPolicies>
   <add name="Unibetech Exception Policy">
    <exceptionTypes>
     <add name="Exception" type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      postHandlingAction="NotifyRethrow">
      <exceptionHandlers>
       <add name="Logging Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        logCategory="Database" eventId="100" severity="Error" title="Unibeton Exception Handling"
        formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        priority="2" useDefaultLogger="false" />
      </exceptionHandlers>
     </add>
     <add name="UnauthorizedAccessException" type="System.UnauthorizedAccessException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      postHandlingAction="NotifyRethrow">
      <exceptionHandlers>
       <add name="Logging Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        logCategory="Database" eventId="100" severity="Error" title="Unibeton Exception Handling"
        formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        priority="1" useDefaultLogger="false" />
      </exceptionHandlers>
     </add>
     <add name="ExceptionHandlingException" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionHandlingException, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
      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="Database" eventId="100" severity="Error" title="Unibeton Exception Handling"
        formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
        priority="0" />
      </exceptionHandlers>
     </add>
    </exceptionTypes>
   </add>
  </exceptionPolicies>
 </exceptionHandling>

 

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

 

Event Viewer

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

Timestamp: 9/10/2011 6:10:21 AM

Message: Tracing to LogSource 'Database' failed. Processing for other sources will continue. See summary information below for more information. Should this problem persist, stop the service and check the configuration file(s) for possible error(s) in the configuration of the categories and sinks.


Summary for Enterprise Library Distributor Service:
======================================
-->
Message:
Timestamp: 9/10/2011 6:10:21 AM
Message: HandlingInstanceID: 296814ba-92a5-4af3-a3a6-bdb0b4b5c45e
An exception of type 'System.Data.SqlClient.SqlException' occurred and was caught.
----------------------------------------------------------------------------------
09/10/2011 10:10:21
Type : System.Data.SqlClient.SqlException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : The DELETE statement conflicted with the REFERENCE constraint "FK__tblProjec__AreaI__22B14FA5". The conflict occurred in database "MarsProd", table "dbo.tblProjectTerritory", column 'AreaID'.
The statement has been terminated.
Source : .Net SqlClient Data Provider
Help link :
Errors : System.Data.SqlClient.SqlErrorCollection
Class : 16
LineNumber : 10
Number : 547
Procedure : uspMasterAreaDelete
Server : svrmusstfs\ja
State : 0
ErrorCode : -2146232060
Data : System.Collections.ListDictionaryInternal
TargetSite : Void OnError(System.Data.SqlClient.SqlException, Boolean)
Stack Trace :    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Microsoft.Practices.EnterpriseLibrary.Data.Database.DoExecuteNonQuery(DbCommand command) in e:\Builds\EntLib\Latest\Source\Blocks\Data\Src\Data\Database.cs:line 443
   at Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteNonQuery(DbCommand command) in e:\Builds\EntLib\Latest\Source\Blocks\Data\Src\Data\Database.cs:line 714
   at UnibetechDataAccessLayer.DALArea.DeleteArea(Int32 AreaId) in D:\UB Systems\MARS II & EAM\EAM\UnibetechDataAccessLayer\Masters\DALArea.vb:line 92
   at UnibetechBusinessLayer.BALArea.DeleteArea(Int32 AreaID) in D:\UB Systems\MARS II & EAM\EAM\UnibetechBusinessLayer\Masters\BALArea.vb:line 20
   at FramePages_Masters_Area.gvArea_DeleteCommand(Object source, GridCommandEventArgs e)

Additional Info:

MachineName : SVREDCDWS01
TimeStamp : 9/10/2011 6:10:21 AM
FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
AppDomainName : /LM/W3SVC/1/Root/UBSystems-3-129601085407707819
ThreadIdentity : UNIBETONRM\sureshs
WindowsIdentity : UNIBETONRM\sureshs

Category: Database
Priority: 2
EventId: 100
Severity: Error
Title:Unibeton Exception Handling
Machine: SVREDCDWS01
App Domain: /LM/W3SVC/1/Root/UBSystems-3-129601085407707819
ProcessId: 3392
Process Name: c:\windows\system32\inetsrv\w3wp.exe
Thread Name:
Win32 ThreadId:3468
Extended Properties: HelpLink.ProdName - Microsoft SQL Server
HelpLink.ProdVer - 09.00.4053
HelpLink.EvtSrc - MSSQLServer
HelpLink.EvtID - 547
HelpLink.BaseHelpUrl - http://go.microsoft.com/fwlink
HelpLink.LinkId - 20476

--> MachineName: SVREDCDWS01
--> TimeStamp: 9/10/2011 6:10:21 AM
--> FullName: Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
--> AppDomainName: /LM/W3SVC/1/Root/UBSystems-3-129601085407707819
--> WindowsIdentity: NT AUTHORITY\NETWORK SERVICE

Exception Information Details:
======================================
Exception Type: System.FormatException
Message: Invalid length for a Base-64 char array.
Data: System.Collections.ListDictionaryInternal
TargetSite: Byte[] FromBase64String(System.String)
HelpLink: NULL
Source: mscorlib

StackTrace Information Details:
======================================
   at System.Convert.FromBase64String(String s)
   at Unibetech.CryptographyServices.SymmetricEncryption.DecryptDataTripleDES(String data) in D:\UB Systems\MARS II & EAM\EAM\Unibtech.CryptographyServices\SymmetricEncrption.cs:line 225
   at Unibetech.LoggingServices.LogDatabaseGateway.DecryptConnectionString(String KeyName) in D:\UB Systems\MARS II & EAM\EAM\Unibetech.LoggingServices\LogDatabaseGateway.cs:line 21
   at Unibetech.LoggingServices.LogDatabaseGateway.CreateDatabase(String KeyName) in D:\UB Systems\MARS II & EAM\EAM\Unibetech.LoggingServices\LogDatabaseGateway.cs:line 32
   at Unibetech.LoggingServices.BasicDatabaseTraceListener.ExecuteStoredProcedure(LogEntry logEntry) in D:\UB Systems\MARS II & EAM\EAM\Unibetech.LoggingServices\BasicDatabaseTraceListener.cs:line 108
   at Unibetech.LoggingServices.BasicDatabaseTraceListener.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data) in D:\UB Systems\MARS II & EAM\EAM\Unibetech.LoggingServices\BasicDatabaseTraceListener.cs:line 76
   at Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.TraceListenerWrapper.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data) in e:\Builds\EntLib\Latest\Source\Blocks\Logging\Src\Logging\TraceListeners\TraceListenerWrapper.cs:line 92
   at Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.TraceListenerWrapper.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data) in e:\Builds\EntLib\Latest\Source\Blocks\Logging\Src\Logging\TraceListeners\TraceListenerWrapper.cs:line 92
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogSource.TraceData(TraceEventType eventType, Int32 id, LogEntry logEntry, TraceListenerFilter traceListenerFilter, TraceEventCache traceEventCache) in e:\Builds\EntLib\Latest\Source\Blocks\Logging\Src\Logging\LogSource.cs:line 178
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriterImpl.ProcessLog(LogEntry log, TraceEventCache traceEventCache) in e:\Builds\EntLib\Latest\Source\Blocks\Logging\Src\Logging\LogWriterImpl.cs:line 553

Category:

Priority: -1

EventId: 6352

Severity: Error

Title:

Machine: SVREDCDWS01

App Domain: /LM/W3SVC/1/Root/UBSystems-3-129601085407707819

ProcessId: 3392

Process Name: c:\windows\system32\inetsrv\w3wp.exe

Thread Name:

Win32 ThreadId:3468

Extended Properties:

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

 

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

 

 

 

Kindly help me, i struck with this issue from past 1 week.

 

 

Sep 10, 2011 at 8:04 AM

Curious....can you post as well your custom trace listener implementation ?

Sep 10, 2011 at 8:29 AM

I am raising the exception by using below command

 ExceptionPolicy.HandleException(ExObject, "Unibetech Exception Policy")

 

and my implementation is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;


namespace Unibetech.LoggingServices
{
    /// <summary>
    /// Custom trace listener using basic integration with the configuration tool
    /// </summary>
    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class BasicDatabaseTraceListener : CustomTraceListener
    {
        public BasicDatabaseTraceListener()
        {
        }

        #region Fields
        private string connectionStringName = null;
        private string writeSp = null;
        private string addCategorySp = null;
        #endregion

        #region Properties
        private string DatabaseInstanceName
        {
            get
            {
                if (string.IsNullOrEmpty(connectionStringName))
                {
                    connectionStringName = this.Attributes["DatabaseInstance"];
                }
                return connectionStringName;
            }
        }

        private string WriteLogStoredProcedure
        {
            get
            {
                if (string.IsNullOrEmpty(writeSp))
                {
                    writeSp = this.Attributes["WriteLogSp"];
                }
                return writeSp;
            }
        }

        private string AddCategoryStoredProcedure
        {
            get
            {
                if (string.IsNullOrEmpty(addCategorySp))
                {
                    addCategorySp = this.Attributes["AddCategorySp"];
                }
                return addCategorySp;
            }
        }
        #endregion

        #region Public Methods

        public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data)
        {
            if (data is LogEntry)
            {
                ExecuteStoredProcedure(data as LogEntry);
            }
            else if (data is string)
            {
                Write(data as string);
            }
            else
            {
                base.TraceData(eventCache, source, eventType, id, data);
            }
        }

        public override void Write(string message)
        {
            //your implementation here
        }

        public override void WriteLine(string message)
        {
            //your implementation here
        }
        #endregion

        #region Private Methods
        /// <summary>
        /// Writes log entries and their categories
        /// </summary>
        /// <param name="logEntry"></param>
        private void ExecuteStoredProcedure(LogEntry logEntry)
        {
            LogDatabaseGateway dbGateWay = new LogDatabaseGateway();
           
            Database db = dbGateWay.CreateDatabase(DatabaseInstanceName);

            using (DbConnection connection = db.CreateConnection())
            {
                connection.Open();
                try
                {
                    using (DbTransaction transaction = connection.BeginTransaction())
                    {
                        try
                        {
                            ContextLogEntry contextLog = logEntry as ContextLogEntry;
                            int logId = 0;

                            DbCommand dbCommand = db.GetStoredProcCommand(WriteLogStoredProcedure);

                            if (contextLog != null)
                            {
                                db.AddInParameter(dbCommand, "ContextID", System.Data.DbType.Int32, contextLog.ContextId);

                            }
                            else
                            {
                                db.AddInParameter(dbCommand, "@EventID", DbType.Int32, logEntry.EventId);
                                db.AddInParameter(dbCommand, "@Priority", DbType.Int32, logEntry.Priority);
                                db.AddInParameter(dbCommand, "@Severity", DbType.String, logEntry.Severity);
                                db.AddInParameter(dbCommand, "@Title", DbType.String, logEntry.Title);
                                db.AddInParameter(dbCommand, "@Timestamp", DbType.DateTime, DateTime.Now);
                                db.AddInParameter(dbCommand, "@MachineName", DbType.String, logEntry.MachineName);
                                db.AddInParameter(dbCommand, "@AppDomainName", DbType.String, logEntry.AppDomainName);
                                db.AddInParameter(dbCommand, "@ProcessID", DbType.String, logEntry.ProcessId);
                                db.AddInParameter(dbCommand, "@ProcessName", DbType.String, logEntry.ProcessName);
                                db.AddInParameter(dbCommand, "@ThreadName", DbType.String, logEntry.ManagedThreadName);
                                db.AddInParameter(dbCommand, "@Win32ThreadId", DbType.String, logEntry.Win32ThreadId);                              
                            }
                           
                            logId = Convert.ToInt32(ExecuteWriteLogStoredProcedure(logEntry, db, transaction, dbCommand));
                          
                            ExecuteAddCategoryStoredProcedure(logEntry, logId, db, transaction);
                           
                            transaction.Commit();
                        }
                        catch
                        {
                            transaction.Rollback();
                            throw;
                        }

                    }
                }
                finally
                {
                    connection.Close();
                }
            }
        }

        private int ExecuteWriteLogStoredProcedure(LogEntry logEntry, Database db, DbTransaction transaction, DbCommand dbCommand)
        {
            db.AddInParameter(dbCommand, "Message", System.Data.DbType.String, logEntry.Message);

            //currently, there's always no associated formatter.
            if (Formatter != null)
                db.AddInParameter(dbCommand, "FormattedMessage", DbType.String, Formatter.Format(logEntry));
            else
                 db.AddInParameter(dbCommand, "FormattedMessage", DbType.String, logEntry.ToString());

            db.AddOutParameter(dbCommand, "LogID", DbType.Int32, 4);

            db.ExecuteNonQuery(dbCommand, transaction);

            object result = db.GetParameterValue(dbCommand, "LogID");
            int logId = int.Parse(result.ToString());
            return logId;
        }

        /// <summary>
        /// Writes the logEntry's category
        /// </summary>
        /// <param name="logEntry"></param>
        /// <param name="logID"></param>
        /// <param name="db"></param>
        /// <param name="transaction"></param>
        private void ExecuteAddCategoryStoredProcedure(LogEntry logEntry, int logID, Database db, DbTransaction transaction)
        {
            foreach (string category in logEntry.Categories)
            {
                DbCommand cmd = db.GetStoredProcCommand(AddCategoryStoredProcedure);
                db.AddInParameter(cmd, "categoryName", DbType.String, category);
                db.AddInParameter(cmd, "logID", DbType.Int32, logID);
                db.ExecuteNonQuery(cmd, transaction);
            }
        }
        #endregion
    }
}

 

 

 

 

Sep 10, 2011 at 9:30 AM
public override void Write(string message)
        {
            //your implementation here
        }

        public override void WriteLine(string message)
        {
            //your implementation here
        }

 

Where's the implementation for this? Remember that Write() and WriteLine() are the ones that are being called to log your data. Take a look at this sample: http://msdn.microsoft.com/en-us/library/cc511727.aspx

Sep 10, 2011 at 11:24 AM

I have implemented TraceData, which works fine in my local asp.net development webserver.

 

can you please let me know how to pass parameters to writelog procedure from message parameter of write method.

 

Sep 10, 2011 at 12:22 PM

I have implemented Write and WriteLine method, as you said. But still give the same error.

 

 


        public override void Write(string message)
        {
            //your implementation here           

            LogDatabaseGateway dbGateWay = new LogDatabaseGateway();

            Database db = dbGateWay.CreateDatabase(DatabaseInstanceName);

            using (DbConnection connection = db.CreateConnection())
            {
                connection.Open();
                try
                {
                    using (DbTransaction transaction = connection.BeginTransaction())
                    {
                        try
                        {
                       
                            DbCommand dbCommand = db.GetStoredProcCommand(WriteLogStoredProcedure);

                            db.AddInParameter(dbCommand, "@EventID", DbType.Int32, 0 );
                            db.AddInParameter(dbCommand, "@Priority", DbType.Int32, 20);
                            db.AddInParameter(dbCommand, "@Severity", DbType.String, "Error");
                            db.AddInParameter(dbCommand, "@Title", DbType.String, "Unibeton Exception Handling");
                            db.AddInParameter(dbCommand, "@Timestamp", DbType.DateTime, DateTime.Now);
                            db.AddInParameter(dbCommand, "@MachineName", DbType.String, "machinename");
                            db.AddInParameter(dbCommand, "@AppDomainName", DbType.String, "AppDomainName");
                            db.AddInParameter(dbCommand, "@ProcessID", DbType.String, "ProcessId");
                            db.AddInParameter(dbCommand, "@ProcessName", DbType.String, "ProcessName");
                            db.AddInParameter(dbCommand, "@ThreadName", DbType.String, "ManagedThreadName");
                            db.AddInParameter(dbCommand, "@Win32ThreadId", DbType.String, "Win32ThreadId");

                            db.AddInParameter(dbCommand, "Message", System.Data.DbType.String, message.ToString());

                            db.AddInParameter(dbCommand, "FormattedMessage", DbType.String, message.ToString());

                            db.AddOutParameter(dbCommand, "LogID", DbType.Int32, 4);

                            db.ExecuteNonQuery(dbCommand, transaction);
                          
                            transaction.Commit();
                        }
                        catch
                        {
                            transaction.Rollback();
                            throw;
                        }

                    }
                }
                finally
                {
                    connection.Close();
                }
            }
        }

        public override void WriteLine(string message)
        {
            //your implementation here

            LogDatabaseGateway dbGateWay = new LogDatabaseGateway();

            Database db = dbGateWay.CreateDatabase(DatabaseInstanceName);

            using (DbConnection connection = db.CreateConnection())
            {
                connection.Open();
                try
                {
                    using (DbTransaction transaction = connection.BeginTransaction())
                    {
                        try
                        {

                            DbCommand dbCommand = db.GetStoredProcCommand(WriteLogStoredProcedure);

                            db.AddInParameter(dbCommand, "@EventID", DbType.Int32, 0);
                            db.AddInParameter(dbCommand, "@Priority", DbType.Int32, 20);
                            db.AddInParameter(dbCommand, "@Severity", DbType.String, "Error");
                            db.AddInParameter(dbCommand, "@Title", DbType.String, "Unibeton Exception Handling");
                            db.AddInParameter(dbCommand, "@Timestamp", DbType.DateTime, DateTime.Now);
                            db.AddInParameter(dbCommand, "@MachineName", DbType.String, "machinename");
                            db.AddInParameter(dbCommand, "@AppDomainName", DbType.String, "AppDomainName");
                            db.AddInParameter(dbCommand, "@ProcessID", DbType.String, "ProcessId");
                            db.AddInParameter(dbCommand, "@ProcessName", DbType.String, "ProcessName");
                            db.AddInParameter(dbCommand, "@ThreadName", DbType.String, "ManagedThreadName");
                            db.AddInParameter(dbCommand, "@Win32ThreadId", DbType.String, "Win32ThreadId");

                            db.AddInParameter(dbCommand, "Message", System.Data.DbType.String, message.ToString());

                            db.AddInParameter(dbCommand, "FormattedMessage", DbType.String, message.ToString());

                            db.AddOutParameter(dbCommand, "LogID", DbType.Int32, 4);

                            db.ExecuteNonQuery(dbCommand, transaction);

                            transaction.Commit();
                        }
                        catch
                        {
                            transaction.Rollback();
                            throw;
                        }

                    }
                }
                finally
                {
                    connection.Close();
                }
            }
        }

Sep 10, 2011 at 1:17 PM

I'm just taking a guess here, but I don't think your problem is EntLib at all; I saw this in the stack trace at the top:

at System.Convert.FromBase64String(String s)
at Unibetech.CryptographyServices.SymmetricEncryption.DecryptDataTripleDES(String data) in D:\UB Systems\MARS II & EAM\EAM\Unibtech.CryptographyServices\SymmetricEncrption.cs:line 225

Then, in the Exception Information Details:

Exception Type: System.FormatException
Message: Invalid length for a Base-64 char array.

It seems like you're passing in some sort of invalid data or something...I advise you to look into the data being passed into SymmetricEncrption.cs file and thouroughly test it.

 

There's another thing I noticed as well; take a look at this data you placed:

Category: Database
Priority: 2
EventId: 100
Severity: Error
Title:Unibeton Exception Handling
Machine: SVREDCDWS01
App Domain: /LM/W3SVC/1/Root/UBSystems-3-129601085407707819
ProcessId: 3392
Process Name: c:\windows\system32\inetsrv\w3wp.exe
Thread Name:
Win32 ThreadId:3468
Extended Properties: HelpLink.ProdName - Microsoft SQL Server
HelpLink.ProdVer - 09.00.4053
HelpLink.EvtSrc - MSSQLServer
HelpLink.EvtID - 547
HelpLink.BaseHelpUrl - http://go.microsoft.com/fwlink
HelpLink.LinkId - 20476

If the event ID is correct, then this is related to security; make sure security is not a problem with the server. As you said, it works fine in your ASP.NET Web Development Server but not on the server itself. Go check it out.

Hope this helps. :)

Sep 10, 2011 at 2:02 PM

As you said in the First Point, the issue is with the SymmetricEncrption. Actually, I am decrypting the connection from the web.config. I had tried to hard the connection string directly from the code without the encryption method. It works fine.

 

Thanks for your help.

 

Now I will try to find the solution for the encryption logic issue.

Sep 10, 2011 at 3:02 PM

If it helps, you can also encrypt/decrypt from your web.config using Ent Lib automatically; in the configuration tool, in your Logging Application Block Settings, click the chevron (the 3 arrows pointing up/down) and you'll see the Security field; you can choose between DPA or RSA.

Sep 11, 2011 at 5:32 AM

Hi,

  I have solved the problem by referring to the below url.

 

http://forums.asp.net/t/1222829.aspx/1?Invalid+length+for+a+Base+64+char+array+how+do+I+check+the+length+

 

 

Thanks