EchoTex_Payroll/Ease.Core/DataAccess/TransactionContext.cs
2024-10-14 10:01:49 +06:00

1321 lines
56 KiB
C#

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
/// <summary>
/// Current connection
/// </summary>
public IDbConnection Connection
{
get { return _connection; }
}
/// <summary>
/// Current transation
/// </summary>
public IDbTransaction Transaction
{
get { return _transaction; }
}
/// <summary>
/// Get or set command timeout if value is 0, uses default command timeout
/// </summary>
public int CommandTimeOut
{
get { return _commandTimeout; }
set { _commandTimeout = value; }
}
#endregion
#region Transaction related functions
/// <summary>
/// Start the session without lock the table of database
/// use only for select query.
/// </summary>
/// <returns>Return an instance of TransactionContext object.</returns>
public static TransactionContext Begin()
{
TransactionContext tc = new TransactionContext();
_createSession = false;
try
{
tc.prepareConnection();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return tc;
}
/// <summary>
/// Start the session with lock the table(s) of database
/// may be used both action and select query.
/// </summary>
/// <param name="createSession">True to create a new session to lock the databse.</param>
/// <returns>Return an instance of TransactionContext object.</returns>
public static TransactionContext Begin(bool createSession)
{
TransactionContext tc = new TransactionContext();
_createSession = createSession;
try
{
tc.prepareConnection();
}
catch
{
}
return tc;
}
/// <summary>
/// Start the session without lock the table of database
/// use only for select query using connectioncontext.
/// </summary>
/// <param name="ctx">Only used when it has to connect other than default database (more than one databse).</param>
/// <returns>Return an instance of TransactionContext object.</returns>
public static TransactionContext Begin(ConnectionContext ctx)
{
TransactionContext tc = new TransactionContext();
tc._contex = ctx;
_createSession = false;
try
{
tc.prepareConnection();
}
catch
{
}
return tc;
}
/// <summary>
/// Start the session wit lock the table of database
/// may be used both action and select query.
/// </summary>
/// <param name="createSession">True to create a new session to lock the databse.</param>
/// <param name="ctx">Only used when it has to connect other than default database (more than one databse).</param>
/// <returns>Return an instance of TransactionContext object.</returns>
public static TransactionContext Begin(bool createSession, ConnectionContext ctx)
{
TransactionContext tc = new TransactionContext();
tc._contex = ctx;
_createSession = createSession;
try
{
tc.prepareConnection();
}
catch
{
}
return tc;
}
/// <summary>
/// Start the session without lock the table of database
/// use only for select query using connectioncontext.
/// </summary>
/// <param name="coneectionString">A valid conntection string.</param>
/// <returns>Return an instance of TransactionContext object.</returns>
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;
}
/// <summary>
/// Start the session wit lock the table of database may be used both action and select query.
/// </summary>
/// <param name="createSession">True to create a new session to lock the databse.</param>
/// <param name="coneectionString">A valid conntection string.</param>
/// <returns>Return an instance of TransactionContext object.</returns>
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;
}
/// <summary>
/// Start the session with lock the table(s) of database
/// may be used both action and select query.
/// </summary>
/// <param name="createSession">True to create a new session to lock the databse.</param>
/// <param name="svcConfig">Configurion of each object, could found in ServiceTemplate
/// calling in following base.ServiceConfuguration.</param>
/// <returns>Return an instance of TransactionContext object.</returns>
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;
}
/// <summary>
/// End the session which means that release all resources
/// </summary>
public void End()
{
if (_transaction != null)
_transaction.Commit();
releaseResources();
}
/// <summary>
/// Release all resources
/// </summary>
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);
}
}
/// <summary>
/// Create command using current connection and/or transanction.
/// </summary>
/// <param name="command">Valid command object.</param>
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
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the database specified
/// in the configuration file.
/// </summary>
/// <remarks>
/// e.g.:
/// ExecuteNonQuery("INSERT INTO TableName(fld1, fld2, fld3) VALUES(%s, %n, %d)", valu1, value2, valu3);
/// </remarks>
/// <param name="args">Comm delimitted value.</param>
/// <param name="commandText">T-SQL command.</param>
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);
}
}
/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the database specified in
/// the app configuration file.
/// </summary>
/// <remarks>
/// e.g.:
/// ExecuteNonQuery(CommandType.StoredProcedure, "SpName", new SqlParameter("@UserID", 24));.
/// ExecuteNonQuery(CommandType.Text, "INSERT INTO TableName(Fld1) VALUES(?)", new SqlParameter("@Date", '1 Jan 2007'));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.).</param>
/// <param name="spName">The name of the stored prcedure.</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure.</param>
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
/// <summary>
/// This function return integer value according to the parameter.
/// </summary>
/// <remarks>
/// e.g.:
/// IDataReader iReader = GenerateID("Users", "UswerID");.
/// </remarks>
/// <param name="tableName">A valid table name which is exit in the database</param>
/// <param name="fieldName">A valid field name of the table</param>
/// <returns>Retun 4 bytes integer value</returns>
public int GenerateID(string tableName, string fieldName)
{
return this.GenerateID(tableName, fieldName, string.Empty);
}
/// <summary>
/// This function return integer value according to the parameter.
/// </summary>
/// <remarks>
/// e.g.:
/// IDataReader iReader = GenerateID("Users", "UswerID", "WHERE UswerID>100 AND CreatedDate='1 Jan 2009'");.
/// </remarks>
/// <param name="tableName">A valid table name which is exist in the database.</param>
/// <param name="fieldName">A valid field name of the table.</param>
/// <param name="sqlClause">Any valid where clause.</param>
/// <returns>Retun 4 bytes integer value.</returns>
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);
}
/// <summary>
///
/// </summary>
/// <param name="objectID"></param>
/// <param name="itemID"></param>
/// <param name="forYear"></param>
/// <param name="forMonth"></param>
/// <param name="forDate"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Generate Sequence no
/// </summary>
/// <param name="objectID">Any valid string</param>
/// <param name="itemID">Any valid string</param>
/// <param name="forYear">Yearly initialize the serial</param>
/// <returns>Return new ID</returns>
public int GetNewID(string objectID, string itemID, short forYear)
{
return this.GetNewID(objectID, itemID, forYear, null, null);
}
/// <summary>
/// Generate Sequence no
/// </summary>
/// <param name="objectID">Any valid string</param>
/// <param name="itemID">Any valid string</param>
/// <param name="forMonth">Monthly initialize the serial</param>
/// <returns>Return new ID</returns>
public int GetNewID(string objectID, string itemID, int forMonth)
{
return this.GetNewID(objectID, itemID, null, forMonth, null);
}
/// <summary>
/// Generate Sequence no
/// </summary>
/// <param name="objectID">Any valid string</param>
/// <param name="itemID">Any valid string</param>
/// <param name="forDate">Daily initialize the serial</param>
/// <returns>Return new ID</returns>
public int GetNewID(string objectID, string itemID, DateTime forDate)
{
return this.GetNewID(objectID, itemID, null, null, forDate);
}
/// <summary>
/// Return newID of integer type, without maintain yearly serial
/// </summary>
/// <param name="objectID">Any valid string</param>
/// <param name="itemID">Any valid string</param>
/// <returns>Return the newID</returns>
public int GetNewID(string objectID, string itemID)
{
return this.GetNewID(objectID, itemID, null, null, null);
}
#endregion
#region Execute Reader
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the app configuration.
/// </summary>
/// <remarks>
/// e.g.:
/// IDataReader iReader = ExecuteReader("SELECT * FROM TableName WHERE ID=%n AND Date=%d", id, date);.
/// </remarks>
/// <param name="commandText">T-SQL command.</param>
/// <param name="args">Comma delimited values.</param>
/// <returns>A IDataReader containing the resultset generated by the command.</returns>
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);
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the app configuration
/// using the provided parameters.
/// </summary>
/// <remarks>
/// 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'));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.).</param>
/// <param name="commandText">The stored procedure name or T-SQL command.</param>
/// <param name="commandParameters">An array of IDataParameter used to execute the command.</param>
/// <returns>A IDataReader containing the resultset generated by the command.</returns>
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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
/// e.g.:
/// IDataReader iReader = ExecuteReader("GetUsers", -9, 20);
/// </remarks>
/// <param name="spName">The name of the stored procedure.</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure.</param>
/// <returns>A IDataReader containing the resultset generated by the command</returns>
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
/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in
/// the app configuration.
/// </summary>
/// <remarks>
/// e.g.:
/// int ttCount = (int)ExecuteScalar("SELECT COUNT(*) FROM TableName");.
/// </remarks>
/// <param name="commandText">T-SQL command.</param>
/// <param name="args">Comma delimited values.</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command.</returns>
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);
}
}
/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the app configuration
/// using the provided parameters.
/// </summary>
/// <remarks>
/// 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'));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of IDataParameter used to execute the command</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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);
/// </remarks>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
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
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the app configuration.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset("SELECT * FROM TableName WHERE ID=%n AND Date=%d",1, '1 Jan 2007');
/// </remarks>
/// <param name="commandText">T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
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);
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the app configuration
/// using the provided parameters.
/// </summary>
/// <remarks>
/// 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));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// DataSet ds = ExecuteDataset("GetUsers", -9);
/// </remarks>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
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
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the app configuration.
/// </summary>
/// <remarks>
/// e.g.:
/// DataSet ds = ExecuteDataset("SELECT * FROM TableName WHERE ID=%n AND Date=%d",1, '1 Jan 2007');
/// </remarks>
/// <param name="commandText">T-SQL command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
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);
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the app configuration
/// using the provided parameters.
/// </summary>
/// <remarks>
/// 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));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
/// DataSet ds = ExecuteDataset("GetUsers", -9);
/// </remarks>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>A dataset containing the resultset generated by the command</returns>
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
/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
/// FillDataset(ds, new string[] {"orders"}, "SELECT * FROM Users WHERE OwnerID=%n AND CreateDate=%d", -9, '1 Jan 2007');
/// </remarks>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">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)</param>
/// <param name="commandText">T-SQL command</param>
/// <param name="args">Comma delimited values</param>
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);
}
}
/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the app configuration
/// using the provided parameters.
/// </summary>
/// <remarks>
/// 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));
/// </remarks>
/// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">The stored procedure name or T-SQL command</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">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)
/// </param>
/// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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);
/// </remarks>
/// <param name="commandType">The CommandType stored procedure</param>
/// <param name="spName">The name of the stored procedure</param>
/// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
/// <param name="tableNames">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)
/// </param>
/// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
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
/// <summary>
/// This function handles all type of error related to SQL command
/// </summary>
public void HandleError()
{
if (_transaction != null)
{
try
{
_transaction.Rollback();
}
catch
{
}
}
releaseResources();
}
#endregion
#region Dispose
/// <summary>
/// Release all resources
/// </summary>
public void Dispose()
{
releaseResources();
}
#endregion
}
#endregion
}