C#•Put Together the Final Custom Publisher

Listing 6. Your custom publisher now publishes to SQL Server and examines the App.config file, enabling you to modify the server, database, and table names on the fly.

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();
         if (cfgSettings != null)
         {
            if (cfgSettings["serverName"] != 
               null &&  
            cfgSettings["serverName"].Length > 
               0)
            {  
               serverName = 
                  cfgSettings["serverName"];
            }
            if (cfgSettings["databaseName"] 
               !=null && 
            cfgSettings["databaseName"].Length 
               > 0)
            {
               databaseName = 
                  cfgSettings["databaseName"];
            }
            if (cfgSettings["tableName"] 
               !=null && 
            cfgSettings["tableName"].Length > 0)
            {
               tableName = 
                  cfgSettings["tableName"];
            }
         }
         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();
      }
   }
}