Exception Handling within DataAccess Layer

Topics: Exception Handling Application Block
Nov 20, 2007 at 12:54 PM
I am Unable to Log my Exception Occure in DataAccess Layer UserDA Class. When ever Exception Occur in DataAccess Layer in FindUser(string username) method, i want to log that exception in trace.log file.


plz help me, i tryied alot but i am not getting ...........see below code


DataAccess Layer ------------------------------>UserDA Class

using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging;


public DataTable FindUser(string username)
{
DbCommand dbCommand = null;
DataTable dt = null;
IDataReader dataReader = null;

try
{
Database db = DatabaseFactory.CreateDatabase();

StringBuilder sqlCommand = new StringBuilder();

sqlCommand.Append("SELECT ARCHITECTUSER,PASSWD");
sqlCommand.Append(" FROM ARCHITECTUSER WHERE USERNAME=@USERNAME");

dbCommand = db.GetSqlStringCommand(sqlCommand.ToString());

db.AddInParameter(dbCommand, "@USERNAME", DbType.String, username);

//DataSet ds = new DataSet();

//ds = db.ExecuteDataSet(dbCommand);


using (dataReader = db.ExecuteReader(dbCommand))
{
dt = LoadDataTable(dataReader);
}

if (dt.Rows.Count == 0)
return null;

return dt;

}
catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "DataAccess Layer Policy");
if (rethrow)
{
}
return null;
}
finally
{
// Close the Reader.
if (dataReader != null || !dataReader.IsClosed)
dataReader.Close();

// Explicitly close the connection.
if (dbCommand != null)
{
if (dbCommand.Connection.State == System.Data.ConnectionState.Open)
{
dbCommand.Connection.Close();
}
}
}
}


Web.Config

Loggin Application Block
**********************************
<loggingConfiguration name="Logging Application Block" tracingEnabled="false"
defaultCategory="myCategory" logWarningsWhenNoCategoriesMatch="false">
<listeners>
<add fileName="trace.log" header="----------------------------------------"
footer="----------------------------------------" formatter=""
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="FlatFile TraceListener" />
</listeners>
<categorySources>
<add switchValue="All" name="myCategory">
<listeners>
<add name="FlatFile TraceListener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings" />
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>

<add name="DataAccess Layer Policy">
<exceptionTypes>
<add type="System.Data.OleDb.OleDbException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="None" name="OleDbException">
<exceptionHandlers>
<add logCategory="myCategory" eventId="100" severity="Error"
title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
priority="0" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Logging Handler" />
</exceptionHandlers>
</add >
<add type="System.Data.Common.DbException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="None" name="DbException">
<exceptionHandlers>
<add logCategory="myCategory" eventId="100" severity="Error"
title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
priority="0" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Logging Handler" />
</exceptionHandlers>
</add>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="None" name="Exception">
<exceptionHandlers>
<add logCategory="myCategory" eventId="100" severity="Error"
title="Enterprise Library Exception Handling" formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
priority="0" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>

</exceptionHandling>
Nov 21, 2007 at 1:04 PM
I haven't run the code, but my guess in that the exception being thrown is of type SqlException and you are not handling it in the DataAccess Policy.

I would first verify which exception is being thrown and make sure it is being accounted for correctly in the exception policy.

I would also look over your code, because I can't think of any reason to write:

if (rethrow)
{
}

in the catch statement. Maybe you want:

if (rethrow)
   throw;

Regards,

Dave

_______________________

David Hayden
Microsoft MVP C#
Nov 29, 2007 at 10:14 AM
Edited Nov 29, 2007 at 10:18 AM
Hi Dave,

Thanks for yours reply,

what you told currect,

if (rethrow)
throw;

but when i use postHandlingAction="None" in that case also i want to use throw keyword or not? pz tell me.

the above problem solved by this way:

Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

I changed PublicKeyToken=b03f5f7f11d50a3a ----> PublicKeyToken=null. now its working fine. Tell me what is problem when i use PublicKeyToken=b03f5f7f11d50a3a .
Nov 29, 2007 at 10:33 AM
Edited Nov 29, 2007 at 10:43 AM
Hi Dave,

I am working on Architecture fo my project. I am using .Net 2.0 with EntLib 3.1. in that i am using DAB,EHAB and LAB.

here i am facing one more problem. I want to strore my Exception in each layer into my Sql server 2005 database or SQLExpress database.

I followed these steps below:

1. I run the scripts available in this path
C:\EntLib3Src\App Blocks\Src\Logging\TraceListeners\Database\Scripts

2. Now Logging Database Created in SQL server 2005 and also in SQLExpress databse. below syntax for SQL Express database. i try for both database but i am getting same error.


The table are Log,Category and CategoryLog .

3. web.config

Connection String and also i used DAB.


<add name="MyLoggingDB" connectionString="data source=SPICITY106\SQLEXPRESS;initial catalog=Logging;user id=sa;password=spicity106sqlexpress;packet size=4096;"
providerName="System.Data.SqlClient" />

<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add databaseInstanceName="MyLoggingDB" writeLogStoredProcName="WriteLog"
addCategoryStoredProcName="AddCategory" formatter="Text Formatter"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
name="Database Trace Listener" />
<add source="Enterprise Library Logging" formatter="Text Formatter"
log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
name="Formatted EventLog TraceListener" />
</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=3.1.0.0, Culture=neutral, PublicKeyToken=null"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="dbCategory">
<listeners>
<add name="Database Trace Listener" />
</listeners>
</add>
<add switchValue="All" name="General">
<listeners>
<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 & Warnings">
<listeners>
<add name="Formatted EventLog TraceListener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>

Code:

LogEntry logEntry = new LogEntry();
logEntry.Message = "Hello World once more again";
Logger.Write(logEntry);

but i am getting this error
"Invalid TraceListenerData type in configuration 'listenerDataType=\"Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null\"'. (C:\\My RND\\Exception Handling Block 3.0\\ArchitectDemoWeb\\web.config line 13)"


Please tell me how to implement database logging.

i searched in Google, very once asking proper article on Database Logging using Enterprise Libarary 3.1.

i am waiting for yours reply....