C#•Create a Custom Publisher

Listing 2. EMAB lets you create a custom publisher in a straightforward manner, as shown by this publisher that logs exceptions to SQL Server. Note, however, that the server, database, and table names are hard-coded.

using System;
using System.Collections.Specialized;
using Microsoft.ApplicationBlocks.
   ExceptionManagement;
using System.Text;
using System.Data.SqlClient;
namespace csEMABCustomPub
{
   public class ExceptionPublisher 
      : IExceptionPublisher
   {
      string serverName = "(local)";
      string databaseName = "ExceptionLog";
      string tableName = "AppException";
      public ExceptionPublisher()
      {
      }
      void IExceptionPublisher.Publish(
         Exception exception, 
         NameValueCollection addInfo, 
         NameValueCollection cfgSettings)
      {
         SqlConnection cn = new SqlConnection();
         SqlCommand cmd = new SqlCommand();
         StringBuilder sbConn = new 
            StringBuilder();
         StringBuilder sbSQL = new 
            StringBuilder();
         StringBuilder sbAddInfo = new 
            StringBuilder();
   sbConn.AppendFormat("server={0};database={1};
uid=sa;pwd=;",serverName,databaseName);
         cn.ConnectionString=sbConn.ToString();
         if(addInfo != null)
         {
            foreach (string i in addInfo)
            {
               sbAddInfo.AppendFormat("{0}: 
                  {1}; ", 
                  i, addInfo.Get(i));
            }
         }
         cn.Open();
         cmd.Connection=cn;
         sbSQL.AppendFormat("insert into {0} 
         (ExcMessage, ExcSource, ExcStackTrace, 
         ExcTargetSite, ExcAddInfo) values ", 
            tableName);
         sbSQL.AppendFormat("('{0}','{1}',
         '{2}','{3}','{4}')", exception.Message,
         exception.Source,exception.StackTrace,
exception.TargetSite,sbAddInfo.ToString());
         cmd.CommandText=sbSQL.ToString();
         cmd.ExecuteNonQuery();
         cn.Close();
      }
   }
}