/[AnywhereTS-MSSQL]/trunk/AnywhereTS.DBSupport/DBConnector.cs
ViewVC logotype

Diff of /trunk/AnywhereTS.DBSupport/DBConnector.cs

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

--- trunk/AnywhereTS.DBSupport/DBConnector.cs	2012/07/13 22:37:40	87
+++ trunk/AnywhereTS.DBSupport/DBConnector.cs	2012/07/15 13:27:58	154
@@ -5,6 +5,8 @@
 using System.Data.Common;
 using System.Data;
 using System.Text.RegularExpressions;
+using System.IO;
+
 
 namespace AnywhereTS.DBSupport
 {
@@ -14,17 +16,21 @@
         where DBConnection : DbConnection, new()
         where DBDataAdapter : DbDataAdapter, new()
     {
+        bool ConnectionIsCreated { get; }
         bool ConnectionIsOpen { get; }
         void CreateConnection(out Exception ErrorInfo);
         void OpenConnection(out Exception ErrorInfo);
+
+        void GetConnectionClone(out DBConnection connection, out Exception ErrorInfo);
+
         void CloseConnection(out Exception ErrorInfo);
 
         DbDataReader ExecuteQuery(string command, List<DBParameter> Params, out Exception ErrorInfo);
         void ExecuteNonQuery(string command, List<DBParameter> Params, out Exception ErrorInfo);
         List<string> ExecuteColumnNamesReader(string command, List<DBParameter> Params, out Exception ErrorInfo);
 
-        DBCommand CreateCommandInstance(string command, List<DBParameter> Params, out Exception ErrorInfo);
-        public bool RunScript(string strFile, MsSqlConnector con, out Exception ErrorInfo);
+        //DBCommand CreateCommandInstance(string command, List<DBParameter> Params, out Exception ErrorInfo);
+        bool RunScript(string strFile, out Exception ErrorInfo);
     }
     public abstract class DBConnector<DBParameter, DBCommand, DBConnection, DBDataAdapter> :
         IDBConnector<DBParameter, DBCommand, DBConnection, DBDataAdapter>
@@ -34,62 +40,104 @@
         where DBDataAdapter : DbDataAdapter, new()
     {
 
-        public DBConnector(string DBServerAddress, string DBServerInstance, string DBDatabase)
+        public DBConnector(string Server, string Instance, string Database)
         {
-            this.DBServerAddress = DBServerAddress;
-            this.DBServerInstance = DBServerInstance;
-            this.DBDatabase = DBDatabase;
+            DBServerAddress = Server;
+            DBServerInstance = Instance;
+            DBDatabase = Database;
+            using (log4net.NDC.Push(string.Format("[Server={0}] [Instance={1}] [Database={2}]", Server, Instance, Database)))
+            {
+                Logging.DatabaseLog.Debug("Creating DBConnector instance");
+            }
         }
 
+        public static string GetConnectionString(string server, string instance, string database)
+        {
+            return string.Format(@"Data Source={0}\{1};Database={2};Integrated Security=SSPI", server, instance, database);
+        }
         protected DBConnection connection;
-        protected string DBServerAddress = "";
-        protected string DBServerInstance = "";
-        protected string DBDatabase = "";
+        #region DBServerAddress, DBServerInstance, DBDatabase
+        internal static string DBServerAddress = "";
+        internal static string DBServerInstance = "";
+        internal static string DBDatabase = "";
+        #endregion
+        #region  private string SafeSqlLiteral(string inputSQL)
         private string SafeSqlLiteral(string inputSQL) { return inputSQL.Replace("'", "''"); }
+        #endregion
         #region IDBConnector members
-        public DBCommand CreateCommandInstance(string command, List<DBParameter> Params, out Exception ErrorInfo)
+        #region  public virtual bool ConnectionIsCreated
+        public virtual bool ConnectionIsCreated { get; protected set; }
+        #endregion
+        #region  public virtual bool ConnectionIsOpen
+        public virtual bool ConnectionIsOpen { get; protected set; }
+        #endregion
+        #region public virtual DBCommand CreateCommandInstance(string command, List<DBParameter> Params, out Exception ErrorInfo)
+        //public virtual DBCommand CreateCommandInstance(string command, List<DBParameter> Params, out Exception ErrorInfo)
+        //{
+        //    ErrorInfo = null;
+        //    try
+        //    {
+        //        command = this.SafeSqlLiteral(command);
+        //        DBCommand sqlComm = new DBCommand();
+        //        sqlComm.CommandText = command;
+        //        sqlComm.Connection = connection;
+        //        foreach (DBParameter p in Params) { sqlComm.Parameters.Add(p); }
+        //        return sqlComm;
+        //    }
+        //    catch (SqlException ex)
+        //    {
+        //        SqlException e = (ex.GetBaseException() as SqlException);
+        //        using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", e.Number.ToString(), e.Message, System.Environment.NewLine, e.ToString())))
+        //        {
+        //            Logging.DatabaseLog.Error(string.Format("Failed to create command instance using command: {0}", command));
+        //        }
+        //        ErrorInfo = ex; throw ErrorInfo;
+        //    }
+        //    catch (Exception ex)
+        //    {
+        //        Exception e = ex.GetBaseException();
+        //        using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", e.GetType().Name, e.Message, System.Environment.NewLine, e.ToString())))
+        //        {
+        //            Logging.DatabaseLog.Error(string.Format("Failed to create command instance using command: {0}", command));
+        //        }
+        //        ErrorInfo = ex; throw ErrorInfo;
+        //    }
+        //}
+        #endregion
+        #region public virtual void GetConnectionClone(ref DBConnection connection)
+        public virtual void GetConnectionClone(out DBConnection connection, out Exception ErrorInfo)
         {
             ErrorInfo = null;
-            try
-            {
-                command = this.SafeSqlLiteral(command);
-                DBCommand sqlComm = new DBCommand();
-                sqlComm.CommandText = command;
-                sqlComm.Connection = connection;
-                foreach (DBParameter p in Params) { sqlComm.Parameters.Add(p); }
-                return sqlComm;
-            }
-            catch (SqlException ex)
-            {
-                using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", ex.Number.ToString(), ex.Message, System.Environment.NewLine, ex.ToString())))
-                {
-                    Logging.DatabaseLog.Error(string.Format("Failed to create command instance using command: {0}", command));
-                }
-                ErrorInfo = ex; throw ErrorInfo;
-            }
-            catch (Exception ex)
-            {
-                using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
-                {
-                    Logging.DatabaseLog.Error(string.Format("Failed to create command instance using command: {0}", command));
-                }
-                ErrorInfo = ex; throw ErrorInfo;
-            } 
+            connection = this.connection;
         }
-        private bool _ConnectionIsOpen;
-        public virtual bool ConnectionIsOpen { get { return _ConnectionIsOpen; } protected set { _ConnectionIsOpen = value; } }
+        #endregion
+        #region  public virtual DBConnection CreateConnection(out Exception ErrorInfo)
         public virtual void CreateConnection(out Exception ErrorInfo)
         {
             ErrorInfo = null;
+            string connetionString = string.Empty;
             try
             {
-                string connetionString = null;
-                connetionString = string.Format(@"Data Source={0}\{1};Initial Catalog={2};Integrated Security=SSPI", DBServerAddress, DBServerInstance, DBDatabase);
-                connection = new DBConnection();
-                connection.ConnectionString = connetionString;
+                if (!this.ConnectionIsCreated)
+                {
+                    connetionString = GetConnectionString(DBServerAddress, DBServerInstance, DBDatabase);
+                    using (log4net.NDC.Push(string.Format("connetionString={0}", connetionString)))
+                    {
+                        Logging.DatabaseLog.Debug("Creating Connection");
+                        connection = new DBConnection();
+                        connection.ConnectionString = connetionString;
+                        Logging.DatabaseLog.Debug("Created Connection");
+                        this.ConnectionIsCreated = true;
+                    }
+                }
+                else
+                {
+                    throw new Exception("Connection has already been created.");
+                }
             }
             catch (SqlException ex)
             {
+                this.ConnectionIsCreated = false;
                 using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", ex.Number.ToString(), ex.Message, System.Environment.NewLine, ex.ToString())))
                 {
                     Logging.DatabaseLog.Error(string.Format("Failed to create connection to {0} Database", DBDatabase));
@@ -98,25 +146,43 @@
             }
             catch (Exception ex)
             {
+                this.ConnectionIsCreated = false;
                 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
                 {
                     Logging.DatabaseLog.Error(string.Format("Failed to create connection to {0} Database", DBDatabase));
                 }
                 ErrorInfo = ex; throw ErrorInfo;
-            } 
+            }
         }
+        #endregion
+        #region public virtual void OpenConnection(out Exception ErrorInfo)
         public virtual void OpenConnection(out Exception ErrorInfo)
         {
             ErrorInfo = null;
+            string connetionString = string.Empty;
             try
             {
-                //this.CloseConnection(out ErrorInfo);
-                connection.Open();
-                this.ConnectionIsOpen = true;
+                if (this.ConnectionIsCreated && this.ConnectionIsOpen)
+                    this.CloseConnection(out ErrorInfo);
+                if (!this.ConnectionIsCreated)
+                    this.CreateConnection(out ErrorInfo);
+                connetionString = GetConnectionString(DBServerAddress, DBServerInstance, DBDatabase);
+                using (log4net.NDC.Push(string.Format("connectionString={0}", connetionString)))
+                {
+                    Logging.DatabaseLog.Debug("Opening Connection");
+                    connection.Open();  
+                    this.ConnectionIsOpen = true; 
+                    Logging.DatabaseLog.Debug("Opened Connection");
+                }
             }
             //catch (SqlException ex) { Console.WriteLine(ex.ToString()); ErrorInfo = ex;  throw ErrorInfo;}
             catch (SqlException ex)
             {
+                this.ConnectionIsOpen = false;
+                if (ex.Message.ToLower().Contains(string.Format("Cannot open database").ToLower()))
+                {
+                    ErrorInfo = null;
+                }
                 using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", ex.Number.ToString(), ex.Message, System.Environment.NewLine, ex.ToString())))
                 {
                     Logging.DatabaseLog.Error(string.Format("Failed to open connection to {0} Database", DBDatabase));
@@ -125,20 +191,32 @@
             }
             catch (Exception ex)
             {
+                this.ConnectionIsOpen = false;
+                if (ex.Message.ToLower().Contains(string.Format("Cannot open database").ToLower()))
+                {
+                    ErrorInfo = null;
+                }
                 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
                 {
                     Logging.DatabaseLog.Error(string.Format("Failed to open connection to {0} Database", DBDatabase));
                 }
                 ErrorInfo = ex; throw ErrorInfo;
-            } 
+            }
         }
+        #endregion
+        #region public virtual void CloseConnection(out Exception ErrorInfo)
         public virtual void CloseConnection(out Exception ErrorInfo)
         {
             ErrorInfo = null;
             try
             {
                 if (this.ConnectionIsOpen)
+                {
                     connection.Close();
+                    this.ConnectionIsOpen = false;
+                    this.ConnectionIsCreated = false;
+                    this.connection = null;
+                }
             }
             catch (SqlException ex)
             {
@@ -155,9 +233,10 @@
                     Logging.DatabaseLog.Error(string.Format("Failed to close connection to {0} Database", DBDatabase));
                 }
                 ErrorInfo = ex; throw ErrorInfo;
-            } 
+            }
         }
-
+        #endregion
+        #region public virtual DbDataReader ExecuteQuery(string command, List<DBParameter> Params, out Exception ErrorInfo)
         public virtual DbDataReader ExecuteQuery(string command, List<DBParameter> Params, out Exception ErrorInfo)
         {
             ErrorInfo = null;
@@ -187,8 +266,10 @@
                     Logging.DatabaseLog.Error(string.Format("Failed to execute querey: {0}", command));
                 }
                 ErrorInfo = ex; throw ErrorInfo;
-            } 
+            }
         }
+        #endregion
+        #region public virtual void ExecuteNonQuery(string command, List<DBParameter> Params, out Exception ErrorInfo)
         public virtual void ExecuteNonQuery(string command, List<DBParameter> Params, out Exception ErrorInfo)
         {
             ErrorInfo = null;
@@ -217,8 +298,10 @@
                     Logging.DatabaseLog.Error(string.Format("Failed to execute non querey: {0}", command));
                 }
                 ErrorInfo = ex; throw ErrorInfo;
-            }    
+            }
         }
+        #endregion
+        #region public virtual List<string> ExecuteColumnNamesReader(string command, List<DBParameter> Params, out Exception ErrorInfo)
         public virtual List<string> ExecuteColumnNamesReader(string command, List<DBParameter> Params, out Exception ErrorInfo)
         {
             ErrorInfo = null;
@@ -258,59 +341,56 @@
                     Logging.DatabaseLog.Error(string.Format("Failed to get colum names from reader: {0}", command));
                 }
                 ErrorInfo = ex; throw ErrorInfo;
-            }            
-        }
-        public string[] ParseScriptToCommands(string strScript)
-        {
-            string[] commands;
-            commands = Regex.Split(strScript, "GO\r\n", RegexOptions.IgnoreCase);
-            return commands;
+            }
         }
-        public virtual bool RunScript(string strFile, out Exception ErrorInfo)
+        #endregion
+        #region public string[] ParseScriptToCommands(string strScript)
+     
+        protected abstract bool ClientRunScript(string strFile, out Exception ErrorInfo);
+        #endregion
+        #region public virtual bool RunScript(string strFile, out Exception ErrorInfo)
+        public bool RunScript(string strFile, out Exception ErrorInfo)
         {
             ErrorInfo = null;
             try
             {
-                string[] strCommands;
-                strCommands = ParseScriptToCommands(strFile);
                 if (this.ConnectionIsOpen)
                 {
-                    foreach (string strCmd in strCommands)
+                    if (!ClientRunScript(strFile, out ErrorInfo))
                     {
-                        if (strCmd.Length > 0)
-                        {
-                            // Substitute database directory with the decided one.
-                            DBCommand command = this.CreateCommandInstance(strCmd, new List<DBParameter>(), out ErrorInfo);
-                            command.ExecuteNonQuery();
-                        }
+                        if(ErrorInfo != null)
+                            throw ErrorInfo;
+                        return false;
                     }
-                    return true;
                 }
                 else
                 {
-                    Logging.ATSAdminLog.Fatal(string.Format("Failed to run script: [database connection is not open] {0}{1}", System.Environment.NewLine, strFile));
+                    Logging.DatabaseLog.Fatal(string.Format("Failed to run script: [database connection is not open] {0}{1}", System.Environment.NewLine, strFile));
                     return false;
                 }
             }
             catch (SqlException ex)
             {
-                using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", ex.Number.ToString(), ex.Message, System.Environment.NewLine, ex.ToString())))
+                SqlException e = (ex.GetBaseException() as SqlException);
+                using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", e.Number.ToString(), e.Message, System.Environment.NewLine, e.ToString())))
                 {
                     Logging.DatabaseLog.Error(string.Format("Failed to run script: {0}{1}", System.Environment.NewLine, strFile));
                 }
-                ErrorInfo = ex;
+                ErrorInfo = ex; throw ErrorInfo;
             }
             catch (Exception ex)
             {
-                using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
+                Exception e = ex.GetBaseException();
+                using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", e.GetType().Name, e.Message, System.Environment.NewLine, e.ToString())))
                 {
                     Logging.DatabaseLog.Error(string.Format("Failed to run script: {0}{1}", System.Environment.NewLine, strFile));
                 }
-                ErrorInfo = ex;
+                ErrorInfo = ex; throw ErrorInfo;
             }
             return false;
         }
         #endregion
+        #endregion
 
         #region IDisposable Members
         public virtual void Dispose()
@@ -318,7 +398,8 @@
             try
             {
                 Exception ErrorInfo;
-                CloseConnection(out ErrorInfo);
+                if (this.ConnectionIsOpen)
+                    CloseConnection(out ErrorInfo);
             }
             catch
             {

 

  ViewVC Help
Powered by ViewVC 1.1.22