using System;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Collections;
namespace AyADAL
{
public class BaseDAL
{
#region Atributos
private string strSentenciaSQL = "";
private string strSentenciaUPD = "";
private string[] strColNombres;
private int intContadorCondiciones, intParamCondicionContador, intParamContador, intValorRetornado = 1;
private CondicionDAL cdlTemp = new CondicionDAL();
private object objCampoDerechoValor;// = null;
private DataSet dsResultado = new DataSet();
private ArrayList arlParamValor = new ArrayList();
#endregion
#region Codigo para PA's
public string strProcedimiento(ref DbParameter[] p_dbpParametros, string p_strProcedimiento, string p_strStringConexion)
{
string strMensaje = string.Empty;
//DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database dbData = null;
DbCommand dbCommando = null;
try
{
if (!string.IsNullOrEmpty(p_strStringConexion))
dbData = factory.Create(p_strStringConexion);// DatabaseProviderFactory.CreateDatabase(p_strStringConexion);
//else
// dbData = factory.Create(); // DatabaseFactory.CreateDatabase();
dbCommando = dbData.GetStoredProcCommand(p_strProcedimiento);
if (p_dbpParametros != null)
{
for (int i = 0; i < p_dbpParametros.Length; i++)
{
if (p_dbpParametros[i] != null && p_dbpParametros[i].Direction == ParameterDirection.Input)
{
dbData.AddInParameter(dbCommando, p_dbpParametros[i].ParameterName, p_dbpParametros[i].DbType, p_dbpParametros[i].Value);
}
else if (p_dbpParametros[i].Direction == ParameterDirection.InputOutput)
dbData.AddOutParameter(dbCommando, p_dbpParametros[i].ParameterName, p_dbpParametros[i].DbType, p_dbpParametros[i].Size);
}
}
dbData.ExecuteNonQuery(dbCommando);
strMensaje = dbCommando.Parameters["@P_MENSAJE"].Value + " con el Status: " + dbCommando.Parameters["@P_STATUS"].Value;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbCommando.Connection.Close();
}
return strMensaje;
}
///
/// Se utiliza para las opciones de Insert, Update y Delete en la base de datos
///
///
///
///
///
public int intProcedimiento( DbParameter[] p_dbpParametros, string p_strProcedimiento, string p_strStringConexion)
{
int nrsultado = 0;
string strMensaje = string.Empty;
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database dbData = null;
DbCommand dbCommando = null;
DataSet dsResultado = null;
try
{
if (!string.IsNullOrEmpty(p_strStringConexion))
dbData = factory.Create(p_strStringConexion);
dbCommando = dbData.GetStoredProcCommand(p_strProcedimiento);
if (p_dbpParametros != null)
{
for (int i = 0; i < p_dbpParametros.Length; i++)
{
if (p_dbpParametros[i] != null && p_dbpParametros[i].Direction == ParameterDirection.Input)
{
dbData.AddInParameter(dbCommando, p_dbpParametros[i].ParameterName, p_dbpParametros[i].DbType, p_dbpParametros[i].Value);
}
else if (p_dbpParametros[i].Direction == ParameterDirection.InputOutput)
dbData.AddOutParameter(dbCommando, p_dbpParametros[i].ParameterName, p_dbpParametros[i].DbType, p_dbpParametros[i].Size);
}
}
dsResultado = dbData.ExecuteDataSet(dbCommando);
if (dsResultado.Tables.Count > 0)
{
if (dsResultado.Tables["Table"].Rows[0]["id"].ToString() != "")
nrsultado = Convert.ToInt32(dsResultado.Tables["Table"].Rows[0]["id"].ToString());
}
//strMensaje = dbCommando.Parameters["@P_MENSAJE"].Value + " con el Status: " + dbCommando.Parameters["@P_STATUS"].Value;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbCommando.Connection.Close();
}
return nrsultado;
}
///
/// Se utiliza para hacer consultas en la base de datos
///
///
///
///
///
public DataSet dsProcedimientoAlmacenado(string p_strProcedimiento, DbParameter[] p_dbpParametros, string p_strStringConexion)
{
DataSet dsValoresRetornados = new DataSet();
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database dbData = null;
DbCommand dbCommando = null;
try
{
if (!string.IsNullOrEmpty(p_strStringConexion))
dbData = factory.Create(p_strStringConexion);
dbCommando = dbData.GetStoredProcCommand(p_strProcedimiento);
if (p_dbpParametros != null)
{
for (int i = 0; i < p_dbpParametros.Length; i++)
{
if (p_dbpParametros[i] != null && p_dbpParametros[i].Direction == ParameterDirection.Input)
{
dbData.AddInParameter(dbCommando, p_dbpParametros[i].ParameterName, p_dbpParametros[i].DbType, p_dbpParametros[i].Value);
}
else if (p_dbpParametros[i].Direction == ParameterDirection.InputOutput)
dbData.AddOutParameter(dbCommando, p_dbpParametros[i].ParameterName, p_dbpParametros[i].DbType, p_dbpParametros[i].Size);
}
}
dsValoresRetornados = dbData.ExecuteDataSet(dbCommando);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dbCommando.Connection.Close();
}
return dsValoresRetornados;
}
#endregion
#region Codigo reutilizado
#region Metodos SQL
#region SQL Constructor de sentencia
///
/// Metodo que se utiliza para ejecuta la consulta
///
///
///
///
///
///
///
///
public DataSet EjecutarConsulta(string p_strNombreTabla, string p_strCampos, string p_strConnectionString, ArrayList p_arlCondiciones, string p_strTLFunciones, string p_strBLFunciones)
{
objCampoDerechoValor = null;
arlParamValor = new ArrayList();
dsResultado = ejecutarConsulta(construirConsulta(null, p_strNombreTabla, p_strCampos, p_arlCondiciones, p_strTLFunciones, p_strBLFunciones), arlParamValor,
p_strConnectionString);
return dsResultado;
}
///
/// Metodo que se utiliza para construir la clausula INSERT
///
///
///
///
///
///
///
public int Insertar(string p_strNombreTabla, string p_strCampos, object[] p_objValores, string p_strConnectionString)
{
Database db;
string strMes;
string strDia;
string strHora;
string strMin;
string strSeg;
DateTime dtFecha;
Boolean bValor;
int nValorBooleano = 0;
string strFecha;
int intParamContador = 1;
int intValorRetornado = 0;
strSentenciaSQL = clausulasDML.INSERT + " INTO " + p_strNombreTabla + " (" + p_strCampos + ") VALUES (";
arlParamValor = new ArrayList();
try
{
intParamContador = 1;
//for (int i = 0; i < p_objValores.Length; i++)
//{
// if (intParamContador != p_objValores.Length)
// strSentenciaSQL += "@Param" + intParamContador.ToString() + ", ";
// else
// strSentenciaSQL += "@Param" + @intParamContador.ToString();
// intParamContador++;
//}
#region Nuevo codigo
if (p_objValores != null && p_objValores.Length > 0)
{
for (int i = 0; i < p_objValores.Length; i++)
{
if (p_objValores[i] != null)
{
switch (p_objValores[i].GetType().ToString())
{
case "System.String":
strSentenciaSQL += "'" + p_objValores[i].ToString() + "'";
break;
case "System.Int":
strSentenciaSQL += p_objValores[i].ToString();
break;
case "System.Int16":
strSentenciaSQL += p_objValores[i].ToString();
break;
case "System.Int32":
strSentenciaSQL += p_objValores[i].ToString();
break;
case "System.Int64":
strSentenciaSQL += p_objValores[i].ToString();
break;
case "System.Decimal":
strSentenciaSQL += p_objValores[i].ToString();
break;
case "System.Boolean":
{
bValor = (Boolean)p_objValores[i];
if (bValor == true)
nValorBooleano = 1;
strSentenciaSQL += nValorBooleano.ToString();
}
break;
case "System.DateTime":
{
dtFecha = (DateTime)p_objValores[i];
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strHora = dtFecha.Hour.ToString();
strMin = dtFecha.Minute.ToString();
strSeg = dtFecha.Second.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + " " + strHora + ":" + strMin + ":" + strSeg + "'";
strSentenciaSQL += strFecha;
break;
}
case "System.Date":
{
dtFecha = (DateTime)p_objValores[i];
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + "'";
strSentenciaSQL += strFecha;
break;
}
}
}
else
strSentenciaSQL += "NULL";
intParamContador++;
if (p_objValores.Length - 1 != i)
strSentenciaSQL += ", ";
}
strSentenciaSQL += ") SELECT @@identity AS id";
DbParameter[] dbpSQLConsulta;
dbpSQLConsulta = new DbParameter[1];
DbProviderFactory dpfConector = DbProviderFactories.GetFactory("System.Data.SqlClient");
for (int i = 0; i < dbpSQLConsulta.Length; i++)
{
dbpSQLConsulta[i] = dpfConector.CreateParameter();
}
dbpSQLConsulta[0].ParameterName = "@TRANSACTSQL";
dbpSQLConsulta[0].Value = strSentenciaSQL;
dbpSQLConsulta[0].DbType = DbType.String;
string proc = "PA_EJECUTARTRANSACT";
intValorRetornado = intProcedimiento(dbpSQLConsulta, proc, p_strConnectionString);
dpfConector = null;
}
else
intValorRetornado = 0;
#endregion
}
catch (Exception ex)
{
throw ex;
}
return intValorRetornado;
}
///
/// Metodo que se utiliza para construir la clausula INSERT
///
///
///
///
///
///
///
public int Insertar(string p_strNombreTabla, string p_strCampos, object[] p_objValores, string p_strConnectionString, TransaccionDAL p_tdlTransaccion)
{
intValorRetornado = 0;
strSentenciaSQL = clausulasDML.INSERT + " INTO " + p_strNombreTabla + " (" + p_strCampos + ") VALUES (";
arlParamValor = new ArrayList();
try
{
intParamContador = 1;
for (int i = 0; i < p_objValores.Length; i++)
{
if (intParamContador != p_objValores.Length)
strSentenciaSQL += "@Param" + intParamContador.ToString() + ", ";
else
strSentenciaSQL += "@Param" + @intParamContador.ToString();
intParamContador++;
}
strSentenciaSQL += ")";
intParamContador = 1;
for (int i = 0; i < p_objValores.Length; i++)
{
arlParamValor.Add(p_objValores[i]);
}
if (p_tdlTransaccion == null)
intValorRetornado = ejecutarNonConsulta(strSentenciaSQL, arlParamValor, null, p_strConnectionString);
else
intValorRetornado = ejecutarTransaccion(strSentenciaSQL, arlParamValor, p_tdlTransaccion, p_strConnectionString);
}
catch (Exception ex)
{
throw ex;
}
return intValorRetornado;
}
///
/// Metodo que se utiliza para construir la clausula UPDATE
///
///
///
///
///
///
///
///
public int Actualizar(string p_strNombreTabla, string p_strCampos, object[] p_objValores, string p_strConnectionString, ArrayList p_arlCondiciones)
{
bool blnEsBorradoLogico = false;
string strMes;
string strDia;
string strHora;
string strMin;
string strSeg;
DateTime dtFecha;
Boolean bValor;
int nValorBooleano = 0;
string strFecha;
int intValorRetornado = 0;
int intParamContador = 1;
strColNombres = ObtenerNombreColumna(p_strCampos);
strSentenciaUPD = clausulasDML.UPDATE.ToString() + " " + p_strNombreTabla + " SET ";
try
{
arlParamValor = new ArrayList();
//blnEsBorradoLogico = updateUtility(strColNombres, p_objValores);
//int intParamCondicionContador = intParamContador;
if (p_objValores.Length == strColNombres.Length)
{
strSentenciaUPD = clausulasDML.UPDATE.ToString() + " " + p_strNombreTabla + " SET ";
arlParamValor = new ArrayList();
for (int i = 0; i < p_objValores.Length; i++)
{
switch (p_objValores[i].GetType().ToString())
{
case "System.String":
strSentenciaUPD += strColNombres[i].ToString() + " = '" + p_objValores[i].ToString() + "'";
break;
case "System.Int":
strSentenciaUPD += strColNombres[i].ToString() + " = " + p_objValores[i].ToString();
break;
case "System.Int16":
strSentenciaUPD += strColNombres[i].ToString() + " = " + p_objValores[i].ToString();
break;
case "System.Int32":
strSentenciaUPD += strColNombres[i].ToString() + " = " + p_objValores[i].ToString();
break;
case "System.Int64":
strSentenciaUPD += strColNombres[i].ToString() + " = " + p_objValores[i].ToString();
break;
case "System.Decimal":
strSentenciaUPD += strColNombres[i].ToString() + " = " + p_objValores[i].ToString();
break;
case "System.Boolean":
{
bValor = (Boolean)p_objValores[i];
if (bValor == true)
nValorBooleano = 1;
strSentenciaUPD += strColNombres[i].ToString() + " = " + nValorBooleano.ToString();
}
break;
case "System.DateTime":
{
dtFecha = (DateTime)p_objValores[i];
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strHora = dtFecha.Hour.ToString();
strMin = dtFecha.Minute.ToString();
strSeg = dtFecha.Second.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + " " + strHora + ":" + strMin + ":" + strSeg + "'";
strSentenciaUPD += strColNombres[i].ToString() + " = " + strFecha;
break;
}
case "System.Date":
{
dtFecha = (DateTime)p_objValores[i];
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + "'";
strSentenciaUPD += strColNombres[i].ToString() + " = " + strFecha;
break;
}
}
if (p_objValores.Length - 1 != i)
strSentenciaUPD += ", ";
}
//intParamCondicionContador = intParamContador;
strSentenciaUPD += construirCondicion(p_arlCondiciones, intParamCondicionContador);
DbParameter[] dbpSQLConsulta;
dbpSQLConsulta = new DbParameter[1];
DbProviderFactory dpfConector = DbProviderFactories.GetFactory("System.Data.SqlClient");
for (int j = 0; j < dbpSQLConsulta.Length; j++)
{
dbpSQLConsulta[j] = dpfConector.CreateParameter();
}
dbpSQLConsulta[0].ParameterName = "@TRANSACTSQL";
dbpSQLConsulta[0].Value = strSentenciaUPD;
dbpSQLConsulta[0].DbType = DbType.String;
string proc = "PA_EJECUTARTRANSACT";
intValorRetornado = intProcedimiento(dbpSQLConsulta, proc, p_strConnectionString);
dpfConector = null;
}
else
{
strSentenciaUPD += construirCondicion(p_arlCondiciones, intParamCondicionContador);
intValorRetornado = ejecutarNonConsulta(strSentenciaUPD, arlParamValor, null, p_strConnectionString);
}
}
catch (Exception ex)
{
throw ex;
}
return intValorRetornado;
}
///
/// Metodo que se utiliza en el metodo de Actualizar
///
///
///
///
private bool updateUtility(string[] p_strColNombres, object[] p_objValores)
{
intParamContador = 1;
int intPKeysCounter = 0;
int intStateFieldIndex = -1;
//bool blnEvaluateStateFieldForDelete = false, blnIsLogicalDelete = false;
bool blnEsBorradoLogico = false;
for (int i = 0; i < p_strColNombres.Length; i++)
{
//*****Se modifica ya que genera una inconsistencia al modificar PK's compuestas.*******
//if (!strColNames[i].ToUpper().Contains("PK"))
//{
if ((intParamContador + intPKeysCounter) != p_strColNombres.Length)
strSentenciaUPD += p_strColNombres[i].Trim() + "= @Param" + intParamContador.ToString() + ", ";
else
strSentenciaUPD += p_strColNombres[i].Trim() + "= @Param" + intParamContador.ToString();
if (p_strColNombres[i].ToUpper().Contains("ASTATUS") && p_strColNombres.Length == 3 || p_strColNombres[i].ToUpper().Contains("ASTATE") && p_strColNombres.Length == 3)
{
//blnEvaluateStateFieldForDelete = true;
intStateFieldIndex = intParamContador;
}
intParamContador++;
//}
//else
//intPKeysCounter++;
}
for (int i = 0; i < p_objValores.Length; i++)
{
arlParamValor.Add(p_objValores[i]);
if (i == intStateFieldIndex - 1 && p_objValores.Length == 3)
{
if (!(bool)p_objValores[i])
blnEsBorradoLogico = true;
}
}
return blnEsBorradoLogico;
}
///
/// Metodo que se utiliza para construir la clausula DELETE(Borrado Físico)
///
///
///
///
///
///
public int eliminarFisico(string p_strNombreTabla, string p_strConnectionString, ArrayList p_arlCondiciones )
{
intValorRetornado = 0;
strSentenciaSQL = clausulasDML.DELETE.ToString() + " " + p_strNombreTabla;
arlParamValor = new ArrayList();
try
{
strSentenciaSQL += construirCondicion(p_arlCondiciones, null);
intValorRetornado = ejecutarNonConsulta(strSentenciaSQL, arlParamValor, null, p_strConnectionString);
}
catch (Exception ex)
{
throw ex;
}
return intValorRetornado;
}
///
/// Metodo que se utiliza para construir la clausula SELECT
///
///
///
///
///
///
///
///
public string construirConsulta(DbCommand p_parentCommand, string p_strNombreTabla, string p_strCampos, ArrayList p_arlCondiciones, string p_strTLFunciones, string p_strBLFunciones)
{
strSentenciaSQL = clausulasDML.SELECT.ToString() + " ";
//Verificar si es un asterisco
if (p_strTLFunciones != "*")
strSentenciaSQL += p_strTLFunciones + " ";
strSentenciaSQL += p_strCampos + " " + clausulaGeneral.FROM.ToString() + " " + p_strNombreTabla;
strSentenciaSQL += construirCondicion(p_arlCondiciones, null) + " " + p_strBLFunciones;
return strSentenciaSQL;
}
private string escogerOperadorGen(string p_strConsulta)
{
switch (cdlTemp.operadorGeneral)
{
case operadorGeneral.EQUAL: //igual que
p_strConsulta += " = ";
break;
case operadorGeneral.UNEQUAL: //diferente de
p_strConsulta += " <> ";
break;
case operadorGeneral.BIGGERTHAN: //mayor que
p_strConsulta += " > ";
break;
case operadorGeneral.SMALLERTHAN: //menor que
p_strConsulta += " < ";
break;
case operadorGeneral.BIGGEREQUALTHAN: //mayor igual que
p_strConsulta += " >= ";
break;
case operadorGeneral.SMALLEREQUALTHAN: //menor igual que
p_strConsulta += " <= ";
break;
case operadorGeneral.IS: //es
p_strConsulta += " IS ";
objCampoDerechoValor = " NULL ";
break;
case operadorGeneral.ISNOT:
p_strConsulta += " IS NOT "; //no es
objCampoDerechoValor = " NULL ";
break;
case operadorGeneral.IN:
p_strConsulta += " IN "; //en
objCampoDerechoValor = "(" + cdlTemp.valorDerecho + ")";
break;
case operadorGeneral.NOTIN:
p_strConsulta += " NOT IN "; //no en
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.EXISTS:
p_strConsulta += " EXISTS "; //existe
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.NOTEXISTS:
p_strConsulta += " NOT EXISTS "; //no existe
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.BETWEEN:
// TODO
// strSentenciaSQL = " BETWEEN ";
// objCampoDerechoValor = "(" + cdlTemp.valorDerecho.Value + ")";
break;
case operadorGeneral.LIKE:
p_strConsulta += " LIKE ";
cdlTemp.valorDerecho = "%" + cdlTemp.valorDerecho + "%";
objCampoDerechoValor = String.Format("'{0}'", cdlTemp.valorDerecho);
break;
}
return p_strConsulta;
}
//********* Construcción Condiciones ************
///
/// Metodo que se utiliza para construir una condicion
///
///
///
///
public string construirCondicion(ArrayList p_arlCondiciones, int? p_intParamCondicionContador)
{
string strMes;
string strDia;
string strHora;
string strMin;
string strSeg;
DateTime dtFecha;
Boolean bValor;
int nValorBooleano = 0;
string strFecha;
string strSentenciaSQL = "";
int? intParamCondicionContador = 1;
if (p_intParamCondicionContador != null)
intParamCondicionContador = p_intParamCondicionContador;
if (p_arlCondiciones != null && p_arlCondiciones.Count > 0)
{
intContadorCondiciones = p_arlCondiciones.Count;
strSentenciaSQL += " " + clausulaGeneral.WHERE.ToString() + " ";
for (int i = 0; i < p_arlCondiciones.Count; i++)
{
cdlTemp = (CondicionDAL)p_arlCondiciones[i];
if (cdlTemp.parentesisInicio)
strSentenciaSQL += "(";
if (cdlTemp.nombreCampoIzquierdo == null || cdlTemp.nombreCampoIzquierdo.Equals(""))
strSentenciaSQL += (cdlTemp.valorIzquierdo);
else
strSentenciaSQL += (cdlTemp.nombreCampoIzquierdo);
strSentenciaSQL = generarCondicionOperadorGen(strSentenciaSQL);
if (cdlTemp.operadorGeneral == operadorGeneral.EQUAL ||
cdlTemp.operadorGeneral == operadorGeneral.UNEQUAL ||
cdlTemp.operadorGeneral == operadorGeneral.BIGGERTHAN ||
cdlTemp.operadorGeneral == operadorGeneral.SMALLERTHAN ||
cdlTemp.operadorGeneral == operadorGeneral.BIGGEREQUALTHAN ||
cdlTemp.operadorGeneral == operadorGeneral.SMALLEREQUALTHAN ||
cdlTemp.operadorGeneral == operadorGeneral.LIKE ||
cdlTemp.operadorGeneral == operadorGeneral.LIKEALL)
{
if (cdlTemp.valorDerechoEsCampo)
{
objCampoDerechoValor = cdlTemp.nombreCampoDerecho;
strSentenciaSQL += objCampoDerechoValor;
}
else
{
//Leer DBMS desde .config
//if (this._strDBMS == "Odbc")
//{
// objCampoDerechoValor = _strSentenceParam;
// p_parentCommand.Parameters.Add(this._adhDataAccessHelper.GetParameter(_strHelperParam + "P_" + intCountParameters, cdlTemp.valorDerecho.Value));
//}
//else
//{
//objCampoDerechoValor = TipoDato(cdlTemp.valorDerecho.GetType().ToString(), cdlTemp.valorDerecho);
switch (cdlTemp.valorDerecho.GetType().ToString())
{
case "System.String":
strSentenciaSQL += "'" + cdlTemp.valorDerecho + "'";
break;
case "System.Int":
strSentenciaSQL += cdlTemp.valorDerecho.ToString();
break;
case "System.Int16":
strSentenciaSQL += cdlTemp.valorDerecho.ToString();
break;
case "System.Int32":
strSentenciaSQL += cdlTemp.valorDerecho.ToString();
break;
case "System.Int64":
strSentenciaSQL += cdlTemp.valorDerecho.ToString();
break;
case "System.Decimal":
strSentenciaSQL += cdlTemp.valorDerecho.ToString();
break;
case "System.Boolean":
{
bValor = (Boolean)cdlTemp.valorDerecho;
if (bValor == true)
nValorBooleano = 1;
strSentenciaUPD += nValorBooleano.ToString();
}
break;
case "System.DateTime":
{
dtFecha = (DateTime)cdlTemp.valorDerecho;
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strHora = dtFecha.Hour.ToString();
strMin = dtFecha.Minute.ToString();
strSeg = dtFecha.Second.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + " " + strHora + ":" + strMin + ":" + strSeg + "'";
strSentenciaSQL += strFecha;
break;
}
case "System.Date":
{
dtFecha = (DateTime)cdlTemp.valorDerecho;
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + "'";
strSentenciaSQL += strFecha;
break;
}
}
//arlParamValor.Add(cdlTemp.valorDerecho);
//intParamCondicionContador++;
}
}
else if (cdlTemp.operadorGeneral == operadorGeneral.IS ||
cdlTemp.operadorGeneral == operadorGeneral.ISNOT ||
cdlTemp.operadorGeneral == operadorGeneral.NOTEXISTS ||
cdlTemp.operadorGeneral == operadorGeneral.EXISTS ||
cdlTemp.operadorGeneral == operadorGeneral.NOTIN ||
cdlTemp.operadorGeneral == operadorGeneral.IN)
{
strSentenciaSQL += objCampoDerechoValor;
//arlParamValue.Add(cdlTemp.valorDerecho);
}
if (cdlTemp.parentesisFinal)
strSentenciaSQL += ")";
intContadorCondiciones = intContadorCondiciones - 1;
if (intContadorCondiciones > 0)
{
if (cdlTemp.operadorLogico.ToString() != "None")
strSentenciaSQL += " " + cdlTemp.operadorLogico.ToString().ToUpper() + " ";
}
}
//procesarCondiciones(p_arlCondiciones, ref strSentenciaSQL, ref p_intParamCondicionContador);
}
return strSentenciaSQL;
}
///
/// Metodo que se utiliza para generar la condicion
///
///
///
private string generarCondicionOperadorGen(string p_strSentenciaSQL)
{
switch (cdlTemp.operadorGeneral)
{
case operadorGeneral.EQUAL: //igual
p_strSentenciaSQL += " = ";
break;
case operadorGeneral.UNEQUAL: //diferente de
p_strSentenciaSQL += " <> ";
break;
case operadorGeneral.BIGGERTHAN: //mayor que
p_strSentenciaSQL += " > ";
break;
case operadorGeneral.SMALLERTHAN: //menor que
p_strSentenciaSQL += " < ";
break;
case operadorGeneral.BIGGEREQUALTHAN: //mayor igual que
p_strSentenciaSQL += " >= ";
break;
case operadorGeneral.SMALLEREQUALTHAN: //menor igual que
p_strSentenciaSQL += " <= ";
break;
case operadorGeneral.IS: //es
p_strSentenciaSQL += " IS ";
objCampoDerechoValor = " NULL ";
break;
case operadorGeneral.ISNOT:
p_strSentenciaSQL += " IS NOT "; //no es
objCampoDerechoValor = " NULL ";
break;
case operadorGeneral.IN:
p_strSentenciaSQL += " IN "; //en
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.NOTIN:
p_strSentenciaSQL += " NOT IN "; //no en
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.EXISTS:
p_strSentenciaSQL += " EXISTS "; //existe
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.NOTEXISTS:
p_strSentenciaSQL += " NOT EXISTS "; //no existe
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.BETWEEN:
// TODO
//strSentenciaSQL += " BETWEEN ";
//objCampoDerechoValor = "(" + cdlTemp.ValorIzquierdo + " AND " + cdlTemp.valorDerecho + ")";
break;
case operadorGeneral.LIKE:
p_strSentenciaSQL += " LIKE "; //como
cdlTemp.valorDerecho = "%" + cdlTemp.valorDerecho + "%";
objCampoDerechoValor = String.Format("'{0}'", cdlTemp.valorDerecho);
break;
case operadorGeneral.LIKEALL:
p_strSentenciaSQL += " LIKE ";
cdlTemp.valorDerecho = "%" + cdlTemp.valorDerecho + "%";
objCampoDerechoValor = String.Format("'{0}'", cdlTemp.valorDerecho);
break;
}
return p_strSentenciaSQL;
}
///
/// Metodo que se utiliza para generar la condicion
///
///
///
private string generarCondicionEspecialOperadorGen(string p_strSentenciaSQL)
{
switch (cdlTemp.operadorGeneral)
{
case operadorGeneral.EQUAL:
strSentenciaSQL += " = ";
break;
case operadorGeneral.UNEQUAL:
strSentenciaSQL += " <> ";
break;
case operadorGeneral.BIGGERTHAN:
strSentenciaSQL += " > ";
break;
case operadorGeneral.SMALLERTHAN:
strSentenciaSQL += " < ";
break;
case operadorGeneral.BIGGEREQUALTHAN:
strSentenciaSQL += " >= ";
break;
case operadorGeneral.SMALLEREQUALTHAN:
strSentenciaSQL += " <= ";
break;
case operadorGeneral.IS:
strSentenciaSQL += " IS ";
objCampoDerechoValor = " NULL ";
break;
case operadorGeneral.ISNOT:
strSentenciaSQL += " IS NOT ";
objCampoDerechoValor = " NULL ";
break;
case operadorGeneral.IN:
strSentenciaSQL += " IN ";
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.NOTIN:
strSentenciaSQL += " NOT IN ";
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.EXISTS:
strSentenciaSQL += " EXISTS ";
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.NOTEXISTS:
strSentenciaSQL += " NOT EXISTS ";
objCampoDerechoValor = String.Format("({0})", cdlTemp.valorDerecho);
break;
case operadorGeneral.BETWEEN:
// TODO
// strSentenciaSQL = " BETWEEN ";
// objCampoDerechoValor = "(" + cdlTemp.valorDerecho.Value + ")";
break;
case operadorGeneral.LIKE:
strSentenciaSQL += " LIKE ";
cdlTemp.valorDerecho = cdlTemp.valorDerecho + "%";
objCampoDerechoValor = String.Format("'{0}'", cdlTemp.valorDerecho);
break;
case operadorGeneral.LIKEALL:
strSentenciaSQL += " LIKE ";
cdlTemp.valorDerecho = "%" + cdlTemp.valorDerecho + "%";
objCampoDerechoValor = String.Format("'{0}'", cdlTemp.valorDerecho);
break;
}
return strSentenciaSQL;
}
#endregion //SQL Constructor de sentencia
#region Ejecutar consultas
///
/// Metodo para obtener la ultima llave primaria de la tabla
///
///
///
///
public int SiguientePK(string strNombreTabla, string strConnectionString)
{
int intPKRetornada = 0;
string sqlQuery = "SELECT IDENT_CURRENT('" + strNombreTabla + "') as UltimaPK";
intPKRetornada = Int32.Parse(ejecutarQuery(sqlQuery, strConnectionString).Tables[0].Rows[0]["UltimaPK"].ToString());
return intPKRetornada;
}
private DataSet ejecutarQuery(string strQuery, string strConnectionString)
{
DataSet dsReturnValue = new DataSet();
Database dbData = null;
DatabaseProviderFactory dbFactory = new DatabaseProviderFactory();
DbCommand dbCommando = null;
try
{
if (!string.IsNullOrEmpty(strConnectionString))
dbData = dbFactory.Create(strConnectionString);
dbCommando = dbData.GetSqlStringCommand(strQuery);
dsReturnValue = dbData.ExecuteDataSet(dbCommando);
dbCommando.Parameters.Clear();
return dsReturnValue;
}
catch (Exception ex)
{
throw ex;
}
}
#region Execute Queries
private int ejecutarNonConsulta(string p_strSentenciaSQL, ArrayList p_arlParamValores, object[] p_objValores, string p_strConnectionString)
{
Database db;
string strMes;
string strDia;
string strHora;
string strMin;
string strSeg;
DateTime dtFecha;
Boolean bValor;
int nValorBooleano = 0;
string strFecha;
int intParamContador = 1;
int intValorRetornado = 0;
object objCondicionParam;
//DbCommand dbCommand = null;
string sqlQuery = p_strSentenciaSQL;
sqlQuery += " SELECT @@identity AS id";
try
{
if (p_arlParamValores != null && p_arlParamValores.Count > 0)
{
for (int i = 0; i < p_arlParamValores.Count; i++)
{
objCondicionParam = (object)p_arlParamValores[i];
switch (objCondicionParam.GetType().ToString())
{
case "System.String":
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), "'" + objCondicionParam.ToString() + "'");
break;
case "System.Int":
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), objCondicionParam.ToString());
break;
case "System.Int16":
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), objCondicionParam.ToString());
break;
case "System.Int32":
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), objCondicionParam.ToString());
break;
case "System.Int64":
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), objCondicionParam.ToString());
break;
case "System.Boolean":
{
bValor = (Boolean)objCondicionParam;
if (bValor == true)
nValorBooleano = 1;
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), nValorBooleano.ToString());
}
break;
case "System.DateTime":
{
dtFecha = (DateTime)objCondicionParam;
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strHora = dtFecha.Hour.ToString();
strMin = dtFecha.Minute.ToString();
strSeg = dtFecha.Second.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + " " + strHora + ":" + strMin + ":" + strSeg + "'";
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), strFecha);
break;
}
case "System.Date":
{
dtFecha = (DateTime)objCondicionParam;
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + "'";
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), strFecha);
break;
}
}
intParamContador++;
}
DbParameter[] dbpSQLConsulta;
dbpSQLConsulta = new DbParameter[1];
DbProviderFactory dpfConector = DbProviderFactories.GetFactory("System.Data.SqlClient");
for (int i = 0; i < dbpSQLConsulta.Length; i++)
{
dbpSQLConsulta[i] = dpfConector.CreateParameter();
}
dbpSQLConsulta[0].ParameterName = "@TRANSACTSQL";
dbpSQLConsulta[0].Value = sqlQuery;
dbpSQLConsulta[0].DbType = DbType.String;
string proc = "PA_EJECUTARTRANSACT";
intValorRetornado = intProcedimiento(dbpSQLConsulta, proc, p_strConnectionString);
dpfConector = null;
}
else
intValorRetornado = 0;
}
catch (Exception ex)
{
throw ex;
}
return intValorRetornado;
}
///
/// Método para obtener un dataset a partir de un stored procedure
///
///
///
///
/// Dataset
public DataSet ejecutarConsulta(string p_strConsulta, ArrayList p_arlParamValores, string p_strConnectionString)
{
object objCondicionParam;
int intParamContador = 1;
DataSet dsValorRetornado = new DataSet();
//Database db;
//DbCommand dbCommand = null;
string sqlQuery = p_strConsulta;
try
{
//if (!String.IsNullOrEmpty(p_strConnectionString))
// db = DatabaseFactory.CreateDatabase(p_strConnectionString);
//else
// db = DatabaseFactory.CreateDatabase();
//dbCommand = db.GetSqlStringCommand(p_strConsulta);
if (p_arlParamValores != null && p_arlParamValores.Count > 0)
{
for (int i = 0; i < p_arlParamValores.Count; i++)
{
objCondicionParam = (object)p_arlParamValores[i];
if (objCondicionParam != null)
{
//db.AddInParameter(dbCommand, "@Param" + intParamContador.ToString(), ObtenerDbTypeDeUnSystemType(objCondicionParam.GetType().ToString()), objCondicionParam);
if (objCondicionParam.GetType().ToString() == "System.String")
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), "'" + objCondicionParam.ToString() + "'");
else
sqlQuery = sqlQuery.Replace("@Param" + intParamContador.ToString(), objCondicionParam.ToString());
intParamContador++;
}
}
}
DbParameter[] dbpSQLConsulta;
dbpSQLConsulta = new DbParameter[1];
DbProviderFactory dpfConector = DbProviderFactories.GetFactory("System.Data.SqlClient");
for (int i = 0; i < dbpSQLConsulta.Length; i++)
{
dbpSQLConsulta[i] = dpfConector.CreateParameter();
}
dbpSQLConsulta[0].ParameterName = "@TRANSACTSQL";
dbpSQLConsulta[0].Value = sqlQuery;
dbpSQLConsulta[0].DbType = DbType.String;
string proc = "PA_EJECUTARTRANSACT";
dsValorRetornado = dsProcedimientoAlmacenado(proc, dbpSQLConsulta, p_strConnectionString);
//dsValorRetornado = db.ExecuteDataSet(dbCommand);
//dbCommand.Parameters.Clear();
dpfConector = null;
}
catch (Exception ex)
{
throw ex;
}
return dsValorRetornado;
}
///
/// Metodo que se utiliza para ejecutar una transacción
///
///
///
///
///
///
public int ejecutarTransaccion(string p_strSentenciaSQL, ArrayList p_arlParamValores, TransaccionDAL p_tdlTransaccion, string p_strConnectionString)
{
Database db;
int intParamContador = 1;
int intValorRetornado = 0;
object objCondicionParam;
DbCommand dbCommand = null;
try
{
db = p_tdlTransaccion.DB;
if (p_arlParamValores != null && p_arlParamValores.Count > 0)
{
dbCommand = db.GetSqlStringCommand(p_strSentenciaSQL);
for (int i = 0; i < p_arlParamValores.Count; i++)
{
objCondicionParam = (object)p_arlParamValores[i];
if (objCondicionParam != null)
db.AddInParameter(dbCommand, "@Param" + intParamContador.ToString(),
ObtenerDbTypeDeUnSystemType(objCondicionParam.GetType().ToString()), objCondicionParam);
else//se agregó este else para los casos que sean llaves foráneas q se requieren q sean valores nulos
db.AddInParameter(dbCommand, "@Param" + intParamContador.ToString(), DbType.Int32, null);
intParamContador++;
}
intValorRetornado = db.ExecuteNonQuery(dbCommand, p_tdlTransaccion.Transaction);
dbCommand.Parameters.Clear();
}
else
intValorRetornado = 0;
}
catch (Exception ex)
{
throw ex;
}
return intValorRetornado;
}
#endregion //Ejecutar consultas
#region Metodos Personalizados
///
/// Metodo que se utiliza para obtener el nombre de una columna
///
///
/// strColNombres
private string[] ObtenerNombreColumna(string p_strCampos)
{
string[] strColNombres;
char chrDelimiter = Char.Parse(",");
strColNombres = p_strCampos.Split(chrDelimiter);
return strColNombres;
}
///
/// Metodo que se utiliza para obtener la conversion de tipo de variables de sql a .net
///
///
/// DbType
///
private DbType ObtenerDbTypeDeUnSystemType(string strSystemType)
{
DbType dbtReturnedValue = DbType.Object;
switch (strSystemType)
{
case "System.Int32":
dbtReturnedValue = DbType.Int32;
break;
case "System.String":
dbtReturnedValue = DbType.String;
break;
case "System.Decimal":
dbtReturnedValue = DbType.Decimal;
break;
case "System.DateTime":
dbtReturnedValue = DbType.DateTime;
break;
case "System.Boolean":
dbtReturnedValue = DbType.Boolean;
break;
case "System.Double":
dbtReturnedValue = DbType.Double;
break;
case "System.Char":
dbtReturnedValue = DbType.String;
break;
case "System.Byte[]"://se agregó para este proyecto
dbtReturnedValue = DbType.Binary;
break;
}
return dbtReturnedValue;
}
private string TipoDato(string p_strValor)
{
string strMes;
string strDia;
string strHora;
string strMin;
string strSeg;
DateTime dtFecha;
Boolean bValor;
int nValorBooleano = 0;
string strFecha;
DbType objTipo = DbType.Object;
string strValorRetornado = string.Empty;
objTipo = ObtenerDbTypeDeUnSystemType(p_strValor);
switch (p_strValor)
{
case "System.String":
strValorRetornado = "'" + p_strValor + "'";
break;
case "System.Int":
strValorRetornado = p_strValor;
break;
case "System.Int16":
strValorRetornado = p_strValor;
break;
case "System.Int32":
strValorRetornado = p_strValor;
break;
case "System.Int64":
strValorRetornado = p_strValor;
break;
case "System.Decimal":
strValorRetornado = p_strValor;
break;
case "System.Boolean":
{
bValor = bool.Parse(objTipo.ToString());
if (bValor == true)
nValorBooleano = 1;
strValorRetornado += nValorBooleano.ToString();
}
break;
case "System.DateTime":
{
dtFecha = DateTime.Now;
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strHora = dtFecha.Hour.ToString();
strMin = dtFecha.Minute.ToString();
strSeg = dtFecha.Second.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + " " + strHora + ":" + strMin + ":" + strSeg + "'";
strValorRetornado = strFecha;
break;
}
case "System.Date":
{
dtFecha = DateTime.Now;
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Month < 10)
strMes = "0" + dtFecha.Month.ToString();
else
strMes = dtFecha.Month.ToString();
//Si el mes es menor a 10 da error, hay que agregarle el 0
if (dtFecha.Day < 10)
strDia = "0" + dtFecha.Day.ToString();
else
strDia = dtFecha.Day.ToString();
strFecha = "'" + dtFecha.Year.ToString() + strMes + strDia + "'";
strValorRetornado = strFecha;
break;
}
}
return strValorRetornado;
}
#endregion //Custom Methods
#endregion //SQL Methods
#endregion //Codigo reutilizado
#endregion
}
}