E
engahmedbarbary
Guest
I work on c# App I face Issue I can't modify function to accepting SQL connection or Not from developer .
so some developer using function pass SQL connection and some others not pass SQL connection
so that I need to handle both cases to not make exception .
Calling function as below :
int result =ExecuteNonQuery("sp_getAllData"); here not write connection
some other developer
SqlConnection con = new SqlConnection("database,server,id,password")
int result =ExecuteNonQuery("sp_getAllData",con); here I write connection
public int ExecuteNonQuery(string sql, SqlConnection sqlconnection, DbParameter[] @params = null, CommandType cmdType = CommandType.StoredProcedure)
{
int RecordsCount = 0;
if (sql == "") return 0;
// this is fixed sql connection but if I passed connection what I do
using (sqlconnection = new SqlConnection(GlobalVariables.con))
{
sqlconnection.Open();
var insertTransaction = sqlconnection.BeginTransaction();
using (var cmd = new SqlCommand(sql, sqlconnection) { Transaction = insertTransaction, CommandType = cmdType })
{
cmd.Parameters.Clear();
if (@params != null && @params.Length > 0)
{
cmd.Parameters.AddRange(@params);
}
try
{
RecordsCount = cmd.ExecuteNonQuery();
insertTransaction.Commit();
}
catch (SqlException)
{
insertTransaction.Rollback();
throw;
}
catch (Exception)
{
throw;
}
}
}
return RecordsCount;
}
Continue reading...
so some developer using function pass SQL connection and some others not pass SQL connection
so that I need to handle both cases to not make exception .
Calling function as below :
int result =ExecuteNonQuery("sp_getAllData"); here not write connection
some other developer
SqlConnection con = new SqlConnection("database,server,id,password")
int result =ExecuteNonQuery("sp_getAllData",con); here I write connection
public int ExecuteNonQuery(string sql, SqlConnection sqlconnection, DbParameter[] @params = null, CommandType cmdType = CommandType.StoredProcedure)
{
int RecordsCount = 0;
if (sql == "") return 0;
// this is fixed sql connection but if I passed connection what I do
using (sqlconnection = new SqlConnection(GlobalVariables.con))
{
sqlconnection.Open();
var insertTransaction = sqlconnection.BeginTransaction();
using (var cmd = new SqlCommand(sql, sqlconnection) { Transaction = insertTransaction, CommandType = cmdType })
{
cmd.Parameters.Clear();
if (@params != null && @params.Length > 0)
{
cmd.Parameters.AddRange(@params);
}
try
{
RecordsCount = cmd.ExecuteNonQuery();
insertTransaction.Commit();
}
catch (SqlException)
{
insertTransaction.Rollback();
throw;
}
catch (Exception)
{
throw;
}
}
}
return RecordsCount;
}
Continue reading...