using System; using System.Data; using System.Linq; using System.Reflection; using Ease.Core.Utility; using Microsoft.Data.SqlClient; using System.Linq.Expressions; using System.Collections.Generic; using System.IO; using System.Diagnostics; namespace Ease.Core.DataAccess { #region DataAccess: Transaction Context public class TransactionContext : IDisposable { #region Declaration & Constructors private int _tryCount = 0; private SQLSyntax _syntax; private Provider _provider; private int _commandTimeout; private ConnectionContext _contex; private IDbConnection _connection; private static bool _createSession; private IDbTransaction _transaction; private TransactionContext() { _tryCount = 0; _contex = null; _commandTimeout = 0; _createSession = false; _syntax = SQLSyntax.SQL; } #endregion #region Properties /// /// Current connection /// public IDbConnection Connection { get { return _connection; } } /// /// Current transation /// public IDbTransaction Transaction { get { return _transaction; } } /// /// Get or set command timeout if value is 0, uses default command timeout /// public int CommandTimeOut { get { return _commandTimeout; } set { _commandTimeout = value; } } #endregion #region Transaction related functions /// /// Start the session without lock the table of database /// use only for select query. /// /// Return an instance of TransactionContext object. public static TransactionContext Begin() { TransactionContext tc = new TransactionContext(); _createSession = false; try { tc.prepareConnection(); } catch (Exception ex) { throw new Exception(ex.Message); } return tc; } /// /// Start the session with lock the table(s) of database /// may be used both action and select query. /// /// True to create a new session to lock the databse. /// Return an instance of TransactionContext object. public static TransactionContext Begin(bool createSession) { TransactionContext tc = new TransactionContext(); _createSession = createSession; try { tc.prepareConnection(); } catch { } return tc; } /// /// Start the session without lock the table of database /// use only for select query using connectioncontext. /// /// Only used when it has to connect other than default database (more than one databse). /// Return an instance of TransactionContext object. public static TransactionContext Begin(ConnectionContext ctx) { TransactionContext tc = new TransactionContext(); tc._contex = ctx; _createSession = false; try { tc.prepareConnection(); } catch { } return tc; } /// /// Start the session wit lock the table of database /// may be used both action and select query. /// /// True to create a new session to lock the databse. /// Only used when it has to connect other than default database (more than one databse). /// Return an instance of TransactionContext object. public static TransactionContext Begin(bool createSession, ConnectionContext ctx) { TransactionContext tc = new TransactionContext(); tc._contex = ctx; _createSession = createSession; try { tc.prepareConnection(); } catch { } return tc; } /// /// Start the session without lock the table of database /// use only for select query using connectioncontext. /// /// A valid conntection string. /// Return an instance of TransactionContext object. public static TransactionContext Begin(Provider provider, SQLSyntax syntax, string coneectionString) { TransactionContext tc = new TransactionContext(); tc._syntax = syntax; _createSession = false; tc._provider = provider; try { tc.prepareConnection(coneectionString); } catch { } return tc; } /// /// Start the session wit lock the table of database may be used both action and select query. /// /// True to create a new session to lock the databse. /// A valid conntection string. /// Return an instance of TransactionContext object. public static TransactionContext Begin(bool createSession, Provider provider, SQLSyntax syntax, string coneectionString) { TransactionContext tc = new TransactionContext(); tc._syntax = syntax; tc._provider = provider; _createSession = createSession; try { tc.prepareConnection(coneectionString); } catch { } return tc; } /// /// Start the session with lock the table(s) of database /// may be used both action and select query. /// /// True to create a new session to lock the databse. /// Configurion of each object, could found in ServiceTemplate /// calling in following base.ServiceConfuguration. /// Return an instance of TransactionContext object. public static TransactionContext Begin(string svcConfig, bool createSession = false) { TransactionContext tc = new TransactionContext(); _createSession = createSession; tc._contex = new ConnectionContext(svcConfig); try { tc.prepareConnection(); } catch { } return tc; } /// /// End the session which means that release all resources /// public void End() { if (_transaction != null) _transaction.Commit(); releaseResources(); } /// /// Release all resources /// void releaseResources() { try { if (_connection != null && _connection.State == ConnectionState.Open) _connection.Close(); if (_transaction != null) _transaction.Dispose(); if (_connection != null) _connection.Dispose(); _contex = null; _connection = null; _commandTimeout = 0; _transaction = null; _createSession = false; GC.Collect(); } catch { } } #endregion #region Command preparation and private function void prepareConnection() { int connectionIdx = 0; //#### //if (Settings.Default != null) // connectionIdx = Settings.Default.Index; this.prepareConnection(connectionIdx: connectionIdx); } void prepareConnection(int connectionIdx) { if (_connection == null) { ConnectionFactory cf; if (_contex != null) { cf = ConnectionFactory.ContextConnection(_contex); _syntax = cf.Syntax; _connection = cf.CreateConnection(_contex); } else { ConnectionFactory.SetConnectionIndex(connectionIdx: connectionIdx); cf = ConnectionFactory.Default; _syntax = cf.Syntax; _connection = cf.CreateConnection(); } cf = null; try { _connection.Open(); } catch (Microsoft.Data.SqlClient.SqlException e) { switch (e.Number) { case 2: case 53: case 258: case 976: case 2702: case 4060: case 10054: case 10060: case 10061: case 11001: case 37002: { int ccIdx = 0; _connection = null; int dsCount = ConnectionFactory.ConnectionCount; if (dsCount > 1) { _tryCount++; if (_tryCount > dsCount) { throw new Exception( string.Format("Eorror code: {0} -> {1}", e.ErrorCode, e.Message), e); } else { if (dsCount <= (connectionIdx + 1)) { ccIdx = 0; } else { ccIdx = connectionIdx + 1; } //Save Connection Index //#### //if (Settings.Default != null) //{ // Settings.Default.Index = ccIdx; // Settings.Default.Save(); //} //Prepare new connection this.prepareConnection(connectionIdx: ccIdx); } } else { throw new Exception(string.Format("Eorror code: {0} -> {1}", e.ErrorCode, e.Message), e); } break; } default: throw new Exception(string.Format("Server: {0} -> {1}", e.Server, e.Message), e); } } if (_createSession) _transaction = _connection.BeginTransaction(IsolationLevel.ReadCommitted); } } public DataSet ExecuteDataSet(string v, int allowDeducID, object p1, object p2, int payrollTypeID) { throw new NotImplementedException(); } void prepareConnection(string connectionString) { if (_connection == null) { _connection = ConnectionFactory.CreateConnection(_provider, _syntax, connectionString) .CreateConnection(); try { _connection.Open(); } catch (Microsoft.Data.SqlClient.SqlException e) { throw new Exception(string.Format("Server: {0} -> {1}", e.Server, e.Message), e); } if (_createSession) _transaction = _connection.BeginTransaction(IsolationLevel.ReadCommitted); } } /// /// Create command using current connection and/or transanction. /// /// Valid command object. public void PrepareCommand(IDbCommand command) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(PrepareCommand)."); if (_connection != null) command.Connection = _connection; if (_transaction != null) command.Transaction = _transaction; } #endregion #region Execute NonQuery /// /// Execute a SqlCommand (that returns no resultset) against the database specified /// in the configuration file. /// /// /// e.g.: /// ExecuteNonQuery("INSERT INTO TableName(fld1, fld2, fld3) VALUES(%s, %n, %d)", valu1, value2, valu3); /// /// Comm delimitted value. /// T-SQL command. public void ExecuteNonQuery(string commandText, params object[] args) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteNonQuery)."); commandText = SQLParser.MakeSQL(_syntax, commandText, args); if (_transaction != null) { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).ExecuteNonQuery(_commandTimeout, _transaction, CommandType.Text, commandText); else TransactionFactory.Default.ExecuteNonQuery(_commandTimeout, _transaction, CommandType.Text, commandText); } else { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).ExecuteNonQuery(_commandTimeout, _connection, CommandType.Text, commandText); else TransactionFactory.Default.ExecuteNonQuery(_commandTimeout, _connection, CommandType.Text, commandText); } } /// /// Execute a SqlCommand (that returns no resultset) against the database specified in /// the app configuration file. /// /// /// e.g.: /// ExecuteNonQuery(CommandType.StoredProcedure, "SpName", new SqlParameter("@UserID", 24));. /// ExecuteNonQuery(CommandType.Text, "INSERT INTO TableName(Fld1) VALUES(?)", new SqlParameter("@Date", '1 Jan 2007')); /// /// The CommandType (stored procedure, text, etc.) /// The stored procedure name or T-SQL command /// An array of SqlParamters used to execute the command public void ExecuteNonQuery(CommandType commandType, string commandText, IDataParameter[] commandParametes) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteNonQuery)."); if (_transaction != null) { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).ExecuteNonQuery(_commandTimeout, _transaction, commandType, commandText, commandParametes); else TransactionFactory.Default.ExecuteNonQuery(_commandTimeout, _transaction, commandType, commandText, commandParametes); } else { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).ExecuteNonQuery(_commandTimeout, _connection, commandType, commandText, commandParametes); else TransactionFactory.Default.ExecuteNonQuery(_commandTimeout, _connection, commandType, commandText, commandParametes); } } /// /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// /// /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// The CommandType (stored procedure, text, etc.). /// The name of the stored prcedure. /// An array of objects to be assigned as the input values of the stored procedure. public void ExecuteNonQuery(CommandType commandType, string spName, params object[] parameterValues) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteNonQuery)."); if (_transaction != null) { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex) .ExecuteNonQuery(_commandTimeout, _transaction, spName, parameterValues); else TransactionFactory.Default.ExecuteNonQuery(_commandTimeout, _transaction, spName, parameterValues); } else { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex) .ExecuteNonQuery(_commandTimeout, _connection, spName, parameterValues); else TransactionFactory.Default.ExecuteNonQuery(_commandTimeout, _connection, spName, parameterValues); } } #endregion #region Generate ID /// /// This function return integer value according to the parameter. /// /// /// e.g.: /// IDataReader iReader = GenerateID("Users", "UswerID");. /// /// A valid table name which is exit in the database /// A valid field name of the table /// Retun 4 bytes integer value public int GenerateID(string tableName, string fieldName) { return this.GenerateID(tableName, fieldName, string.Empty); } /// /// This function return integer value according to the parameter. /// /// /// e.g.: /// IDataReader iReader = GenerateID("Users", "UswerID", "WHERE UswerID>100 AND CreatedDate='1 Jan 2009'");. /// /// A valid table name which is exist in the database. /// A valid field name of the table. /// Any valid where clause. /// Retun 4 bytes integer value. public int GenerateID(string tableName, string fieldName, string whereClause) { object maxID = this.ExecuteScalar("SELECT MAX(%q) FROM %q %q", fieldName, tableName, whereClause); if (maxID == null || maxID == DBNull.Value) { maxID = 1; } else { maxID = Convert.ToInt32(maxID) + 1; if ((int)maxID <= 0) maxID = 1; } return Convert.ToInt32(maxID); } /// /// /// /// /// /// /// /// /// private int GetNewID(string objectID, string itemID, short? forYear, int? forMonth, DateTime? forDate) { SqlParameter[] p = new SqlParameter[6]; p[0] = new SqlParameter("@ObjectID", SqlDbType.VarChar, 255); p[0].Direction = ParameterDirection.Input; p[0].Value = objectID; p[1] = new SqlParameter("@ItemID", SqlDbType.VarChar, 255); p[1].Direction = ParameterDirection.Input; p[1].Value = itemID; p[2] = new SqlParameter("@IDForYear", SqlDbType.Int); p[2].Direction = ParameterDirection.Input; p[2].Value = forYear; p[3] = new SqlParameter("@IDForMonth", SqlDbType.Int); p[3].Direction = ParameterDirection.Input; p[3].Value = forMonth; p[4] = new SqlParameter("@IDForDate", SqlDbType.DateTime); p[4].Direction = ParameterDirection.Input; p[4].Value = forDate; p[5] = new SqlParameter("@NewID", SqlDbType.Int); p[5].Direction = ParameterDirection.Output; p[5].Value = 0; this.ExecuteNonQuery(CommandType.StoredProcedure, "[dbo].[GetID]", p); int newID = 0; if (p[5].Value != null && p[5].Value != DBNull.Value) newID = Convert.ToInt32(p[5].Value); return newID; } /// /// Generate Sequence no /// /// Any valid string /// Any valid string /// Yearly initialize the serial /// Return new ID public int GetNewID(string objectID, string itemID, short forYear) { return this.GetNewID(objectID, itemID, forYear, null, null); } /// /// Generate Sequence no /// /// Any valid string /// Any valid string /// Monthly initialize the serial /// Return new ID public int GetNewID(string objectID, string itemID, int forMonth) { return this.GetNewID(objectID, itemID, null, forMonth, null); } /// /// Generate Sequence no /// /// Any valid string /// Any valid string /// Daily initialize the serial /// Return new ID public int GetNewID(string objectID, string itemID, DateTime forDate) { return this.GetNewID(objectID, itemID, null, null, forDate); } /// /// Return newID of integer type, without maintain yearly serial /// /// Any valid string /// Any valid string /// Return the newID public int GetNewID(string objectID, string itemID) { return this.GetNewID(objectID, itemID, null, null, null); } #endregion #region Execute Reader /// /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in /// the app configuration. /// /// /// e.g.: /// IDataReader iReader = ExecuteReader("SELECT * FROM TableName WHERE ID=%n AND Date=%d", id, date);. /// /// T-SQL command. /// Comma delimited values. /// A IDataReader containing the resultset generated by the command. public IDataReader ExecuteReader(string commandText, params object[] args) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteReader)."); commandText = SQLParser.MakeSQL(_syntax, commandText, args); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteReader(_commandTimeout, _transaction, CommandType.Text, commandText); else return TransactionFactory.Default.ExecuteReader(_commandTimeout, _transaction, CommandType.Text, commandText); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteReader(_commandTimeout, _connection, CommandType.Text, commandText); else return TransactionFactory.Default.ExecuteReader(_commandTimeout, _connection, CommandType.Text, commandText); } } /// /// Execute a SqlCommand (that returns a resultset) against the database specified in the app configuration /// using the provided parameters. /// /// /// e.g.: /// IDataReader iReader = ExecuteReader(CommandType.StoredProcedure, "GetUsers", new IDataParameter("@OwnerID", -9));. /// IDataReader iReader = ExecuteReader(CommandType.Text, "SELECT * FROM TableName WHERE Date=?", new SqlParameter("@Date", '1 Jan 2007')); /// /// The CommandType (stored procedure, text, etc.). /// The stored procedure name or T-SQL command. /// An array of IDataParameter used to execute the command. /// A IDataReader containing the resultset generated by the command. public IDataReader ExecuteReader(CommandType commandType, string commandText, params IDataParameter[] commandParameters) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteReader)."); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex).ExecuteReader(_commandTimeout, _transaction, commandType, commandText, commandParameters); else return TransactionFactory.Default.ExecuteReader(_commandTimeout, _transaction, commandType, commandText, commandParameters); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex).ExecuteReader(_commandTimeout, _connection, commandType, commandText, commandParameters); else return TransactionFactory.Default.ExecuteReader(_commandTimeout, _connection, commandType, commandText, commandParameters); } } /// /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in /// the app configuration using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// /// /// This method provides no access to output parameters or the stored procedure's return value parameter. /// e.g.: /// IDataReader iReader = ExecuteReader("GetUsers", -9, 20); /// /// The name of the stored procedure. /// An array of objects to be assigned as the input values of the stored procedure. /// A IDataReader containing the resultset generated by the command public IDataReader ExecuteReader(CommandType commandType, string spName, params object[] parameterValues) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteReader)."); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteReader(_commandTimeout, _transaction, spName, parameterValues); else return TransactionFactory.Default.ExecuteReader(_commandTimeout, _transaction, spName, parameterValues); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteReader(_commandTimeout, _connection, spName, parameterValues); else return TransactionFactory.Default.ExecuteReader(_commandTimeout, _connection, spName, parameterValues); } } #endregion #region Execute Scalar /// /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in /// the app configuration. /// /// /// e.g.: /// int ttCount = (int)ExecuteScalar("SELECT COUNT(*) FROM TableName");. /// /// T-SQL command. /// Comma delimited values. /// An object containing the value in the 1x1 resultset generated by the command. public object ExecuteScalar(string commandText, params object[] args) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteScalar)."); commandText = SQLParser.MakeSQL(_syntax, commandText, args); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteScalar(_commandTimeout, _transaction, CommandType.Text, commandText); else return TransactionFactory.Default.ExecuteScalar(_commandTimeout, _transaction, CommandType.Text, commandText); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteScalar(_commandTimeout, _connection, CommandType.Text, commandText); else return TransactionFactory.Default.ExecuteScalar(_commandTimeout, _connection, CommandType.Text, commandText); } } /// /// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the app configuration /// using the provided parameters. /// /// /// e.g.: /// int ttCount = (int)ExecuteScalar(CommandType.StoredProcedure, "GetNoOfTT", new SqlParameter("@Date", '1 Jan 2007')); /// int ttCount = (int)ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM TableName WHERE Date=?", new SqlParameter("@Date", '1 Jan 2007')); /// /// The CommandType (stored procedure, text, etc.) /// The stored procedure name or T-SQL command /// An array of IDataParameter used to execute the command /// An object containing the value in the 1x1 resultset generated by the command public object ExecuteScalar(CommandType commandType, string commandText, params IDataParameter[] commandParameters) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteScalar)."); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex).ExecuteScalar(_commandTimeout, _transaction, commandType, commandText, commandParameters); else return TransactionFactory.Default.ExecuteScalar(_commandTimeout, _transaction, commandType, commandText, commandParameters); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex).ExecuteScalar(_commandTimeout, _connection, commandType, commandText, commandParameters); else return TransactionFactory.Default.ExecuteScalar(_commandTimeout, _connection, commandType, commandText, commandParameters); } } /// /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in /// the app configuration using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// /// /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// int ttCount = (int)ExecuteScalar("GetNoOfTT", 24, 36); /// /// The name of the stored procedure /// An array of objects to be assigned as the input values of the stored procedure /// An object containing the value in the 1x1 resultset generated by the command public object ExecuteScalar(CommandType commandType, string spName, params object[] parameterValues) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(ExecuteScalar)."); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteScalar(_commandTimeout, _transaction, spName, parameterValues); else return TransactionFactory.Default.ExecuteScalar(_commandTimeout, _transaction, spName, parameterValues); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteScalar(_commandTimeout, _connection, spName, parameterValues); else return TransactionFactory.Default.ExecuteScalar(_commandTimeout, _connection, spName, parameterValues); } } #endregion #region Execute DataTable /// /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in /// the app configuration. /// /// /// e.g.: /// DataSet ds = ExecuteDataset("SELECT * FROM TableName WHERE ID=%n AND Date=%d",1, '1 Jan 2007'); /// /// T-SQL command /// A dataset containing the resultset generated by the command public DataTable ExecuteDataTable(string commandText, params object[] args) { if (_connection == null && _transaction == null) throw new Exception("Connection is already closed"); commandText = SQLParser.MakeSQL(_syntax, commandText, args); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteDataTable(_commandTimeout, _transaction, CommandType.Text, commandText); else return TransactionFactory.Default.ExecuteDataTable(_commandTimeout, _transaction, CommandType.Text, commandText); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteDataTable(_commandTimeout, _connection, CommandType.Text, commandText); else return TransactionFactory.Default.ExecuteDataTable(_commandTimeout, _connection, CommandType.Text, commandText); } } /// /// Execute a SqlCommand (that returns a resultset) against the database specified in the app configuration /// using the provided parameters. /// /// /// e.g.: /// DataSet ds = ExecuteDataset(CommandType.StoredProcedure, "GetUsers", new SqlParameter("@OwnerID", -9)); /// DataSet ds = ExecuteDataset(CommandType.Text, "SELECT * FROM Users WHERE OwnerID = ?", new SqlParameter("@OwnerID", -9)); /// /// The CommandType (stored procedure, text, etc.) /// The stored procedure name or T-SQL command /// An array of SqlParamters used to execute the command /// A dataset containing the resultset generated by the command public DataTable ExecuteDataTable(CommandType commandType, string commandText, params IDataParameter[] commandParameters) { if (_connection == null && _transaction == null) throw new Exception("Connection is already closed"); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex).ExecuteDataTable(_commandTimeout, _transaction, commandType, commandText, commandParameters); else return TransactionFactory.Default.ExecuteDataTable(_commandTimeout, _transaction, commandType, commandText, commandParameters); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex).ExecuteDataTable(_commandTimeout, _connection, commandType, commandText, commandParameters); else return TransactionFactory.Default.ExecuteDataTable(_commandTimeout, _connection, commandType, commandText, commandParameters); } } /// /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in /// the app configuration using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// /// /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// DataSet ds = ExecuteDataset("GetUsers", -9); /// /// The name of the stored procedure /// An array of objects to be assigned as the input values of the stored procedure /// A dataset containing the resultset generated by the command public DataTable ExecuteDataTable(CommandType commandType, string spName, params object[] parameterValues) { if (_connection == null && _transaction == null) throw new Exception("Connection is already closed"); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteDataTable(_commandTimeout, _transaction, spName, parameterValues); else return TransactionFactory.Default.ExecuteDataTable(_commandTimeout, _transaction, spName, parameterValues); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteDataTable(_commandTimeout, _connection, spName, parameterValues); else return TransactionFactory.Default.ExecuteDataTable(_commandTimeout, _connection, spName, parameterValues); } } #endregion #region Execute Dataset /// /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in /// the app configuration. /// /// /// e.g.: /// DataSet ds = ExecuteDataset("SELECT * FROM TableName WHERE ID=%n AND Date=%d",1, '1 Jan 2007'); /// /// T-SQL command /// A dataset containing the resultset generated by the command public DataSet ExecuteDataSet(string commandText, params object[] args) { if (_connection == null && _transaction == null) throw new Exception("Connection is already closed"); commandText = SQLParser.MakeSQL(_syntax, commandText, args); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteDataset(_commandTimeout, _transaction, CommandType.Text, commandText); else return TransactionFactory.Default.ExecuteDataset(_commandTimeout, _transaction, CommandType.Text, commandText); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteDataset(_commandTimeout, _connection, CommandType.Text, commandText); else return TransactionFactory.Default.ExecuteDataset(_commandTimeout, _connection, CommandType.Text, commandText); } } /// /// Execute a SqlCommand (that returns a resultset) against the database specified in the app configuration /// using the provided parameters. /// /// /// e.g.: /// DataSet ds = ExecuteDataset(CommandType.StoredProcedure, "GetUsers", new SqlParameter("@OwnerID", -9)); /// DataSet ds = ExecuteDataset(CommandType.Text, "SELECT * FROM Users WHERE OwnerID = ?", new SqlParameter("@OwnerID", -9)); /// /// The CommandType (stored procedure, text, etc.) /// The stored procedure name or T-SQL command /// An array of SqlParamters used to execute the command /// A dataset containing the resultset generated by the command public DataSet ExecuteDataSet(CommandType commandType, string commandText, params IDataParameter[] commandParameters) { if (_connection == null && _transaction == null) throw new Exception("Connection is already closed"); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex).ExecuteDataset(_commandTimeout, _transaction, commandType, commandText, commandParameters); else return TransactionFactory.Default.ExecuteDataset(_commandTimeout, _transaction, commandType, commandText, commandParameters); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex).ExecuteDataset(_commandTimeout, _connection, commandType, commandText, commandParameters); else return TransactionFactory.Default.ExecuteDataset(_commandTimeout, _connection, commandType, commandText, commandParameters); } } /// /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in /// the app configuration using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// /// /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// DataSet ds = ExecuteDataset("GetUsers", -9); /// /// The name of the stored procedure /// An array of objects to be assigned as the input values of the stored procedure /// A dataset containing the resultset generated by the command public DataSet ExecuteDataSet(CommandType commandType, string spName, params object[] parameterValues) { if (_connection == null && _transaction == null) throw new Exception("Connection is already closed"); if (_transaction != null) { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteDataset(_commandTimeout, _transaction, spName, parameterValues); else return TransactionFactory.Default.ExecuteDataset(_commandTimeout, _transaction, spName, parameterValues); } else { if (_contex != null) return TransactionFactory.ContextTransactionHelper(_contex) .ExecuteDataset(_commandTimeout, _connection, spName, parameterValues); else return TransactionFactory.Default.ExecuteDataset(_commandTimeout, _connection, spName, parameterValues); } } #endregion #region Fill Dataset /// /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in /// the connection string. /// /// /// e.g.: /// FillDataset(ds, new string[] {"orders"}, "SELECT * FROM Users WHERE OwnerID=%n AND CreateDate=%d", -9, '1 Jan 2007'); /// /// A dataset wich will contain the resultset generated by the command /// This array will be used to create table mappings allowing the DataTables to be referenced /// by a user defined name (probably the actual table name) /// T-SQL command /// Comma delimited values public void FillDataset(DataSet dataSet, string[] tableNames, string commandText, params object[] args) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(FillDataset)."); commandText = SQLParser.MakeSQL(_syntax, commandText, args); if (_transaction != null) { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).FillDataset(_commandTimeout, _transaction, CommandType.Text, commandText, dataSet, tableNames); else TransactionFactory.Default.FillDataset(_commandTimeout, _transaction, CommandType.Text, commandText, dataSet, tableNames); } else { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).FillDataset(_commandTimeout, _connection, CommandType.Text, commandText, dataSet, tableNames); else TransactionFactory.Default.FillDataset(_commandTimeout, _connection, CommandType.Text, commandText, dataSet, tableNames); } } /// /// Execute a SqlCommand (that returns a resultset) against the database specified in the app configuration /// using the provided parameters. /// /// /// e.g.: /// FillDataset(CommandType.StoredProcedure, "GetUsers", ds, new string[] {"Users"}, new SqlParameter("@OwnerID", -9)); /// FillDataset(CommandType.Tex, "SELECT * FROM Users WHERE OwnerID = ?", ds, new string[] {"Users"}, new SqlParameter("@OwnerID", -9)); /// /// The CommandType (stored procedure, text, etc.) /// The stored procedure name or T-SQL command /// A dataset wich will contain the resultset generated by the command /// This array will be used to create table mappings allowing the DataTables to be referenced /// by a user defined name (probably the actual table name) /// /// An array of SqlParamters used to execute the command public void FillDataset(CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params IDataParameter[] commandParameters) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(FillDataset)."); if (_transaction != null) { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).FillDataset(_commandTimeout, _transaction, commandType, commandText, dataSet, tableNames, commandParameters); else TransactionFactory.Default.FillDataset(_commandTimeout, _transaction, commandType, commandText, dataSet, tableNames, commandParameters); } else { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).FillDataset(_commandTimeout, _connection, commandType, commandText, dataSet, tableNames, commandParameters); else TransactionFactory.Default.FillDataset(_commandTimeout, _connection, commandType, commandText, dataSet, tableNames, commandParameters); } } /// /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in /// the app configuration using the provided parameter values. This method will query the database to discover the parameters for the /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order. /// /// /// This method provides no access to output parameters or the stored procedure's return value parameter. /// /// e.g.: /// FillDataset(CommandType.StoredProcedure, "GetUsers", ds, new string[] {"Users"}, 24); /// /// The CommandType stored procedure /// The name of the stored procedure /// A dataset wich will contain the resultset generated by the command /// This array will be used to create table mappings allowing the DataTables to be referenced /// by a user defined name (probably the actual table name) /// /// An array of objects to be assigned as the input values of the stored procedure public void FillDataset(string spName, DataSet dataSet, string[] tableNames, params object[] parameterValues) { if (_connection == null && _transaction == null) throw new Exception("There is no connection to prepare command(FillDataset)."); if (_transaction != null) { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).FillDataset(_commandTimeout, _transaction, spName, dataSet, tableNames, parameterValues); else TransactionFactory.Default.FillDataset(_commandTimeout, _transaction, spName, dataSet, tableNames, parameterValues); } else { if (_contex != null) TransactionFactory.ContextTransactionHelper(_contex).FillDataset(_commandTimeout, _connection, spName, dataSet, tableNames, parameterValues); else TransactionFactory.Default.FillDataset(_commandTimeout, _connection, spName, dataSet, tableNames, parameterValues); } } #endregion #region Error Handler /// /// This function handles all type of error related to SQL command /// public void HandleError() { if (_transaction != null) { try { _transaction.Rollback(); } catch { } } releaseResources(); } #endregion #region Dispose /// /// Release all resources /// public void Dispose() { releaseResources(); } #endregion } #endregion }