using System;
using System.Data;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using LLNet.Utils;

namespace LLNet.BLL
{
	/// <summary>
	/// Clase Encargada de la administración de las requisiciones del GUI,
	/// las validaciones de las reglas de negocio y la comunicación con DAL
	/// </summary>
	public class BLLServer : Model.IBLL
	{

		#region Declaraciones Privadas

		private string defaultConnName;

		/// <summary>
		/// key: Recibe una estructura ModuleRef (moduleName, connName)
		/// value: 
		/// </summary>
		protected Hashtable loadModules = new Hashtable();
		protected Hashtable loadDataSets = new Hashtable();

		#endregion

		#region Clases

		public class ModuleDef
		{
			public string connName;
			public object module;

			public ModuleDef(string pconnName, object pmodule)
			{
				connName = pconnName;
				module = pmodule;
			}
		}

		#endregion

		#region Constructor

		public BLLServer() 
		{

        }

		#endregion

		#region Métodos privados de la clase

		/// <summary>
		/// Devuelve el tipo del modulo basado en la conexión y el modulo requerido
		/// </summary>
		/// <param name="connName">conexión</param>
		/// <param name="module">modulo requerido: Ej: Recibos</param>
		/// <returns></returns>
		protected string getModuleName(string connName,string module)
		{
			int position = connName.IndexOf(".");
			string dbType = connName.Substring(0,position);
			string typeName = "LLNet.DAL." + dbType + "." + module + "." + module;
			return typeName;
		}

        /// <summary>
		/// Busca en el assembly actual la clase que define las reglas de negocio de un DataSet tipado
		/// </summary>
		/// <param name="dataSetType">Tipo de DataSet</param>
		/// <returns>DataSet con Reglas de Negocio</returns>
		private DataSet FindRuleDataSetByDsType(System.Type dataSetType)
		{
			foreach (System.Type type in Assembly.GetExecutingAssembly().GetTypes())
			{
				if (type.IsSubclassOf(dataSetType))
				{
					return (DataSet)Activator.CreateInstance(type,new object[] { this });
				}
			}
			return null;
		}

        /// <summary>
		/// 
		/// </summary>
		/// <param name="dsType"></param>
		/// <returns></returns>
		private DataSet getDataSetByType(Type dsType)
		{
			DataSet ds = (DataSet)loadDataSets[dsType];
			if (ds == null)
			{
				try
				{
					ds = (DataSet)Activator.CreateInstance(dsType);
					loadDataSets.Add(dsType,ds);
				} 
				catch (Exception ex)
				{
                    throw new Exception(ex.Message);
				}
			}
			else
				ds.Clear();

            return ds;
		}

		private string tryToInsertRecursiveTag(string sql)
		{
			string aux = sql.ToUpper();
			int firstOcurrence = aux.IndexOf("WHERE");
			int lastOcurrence = aux.IndexOf("WHERE");

			//solo existe una vez
			if (firstOcurrence == lastOcurrence && lastOcurrence != -1)
				return ( sql + " " + Utils.QueryParams.PredefinedTags.AllToolbarsTag );
			else
				return null;
		}

        private string getTypedCmd(DAL.IDAL module, string queryName, string dataSetName, string tableName, Utils.QueryParams pList)
		{
			//-- Declaracion de variables
			object objSql;
			string strQueryName = Utils.Helpers.Nvl(queryName, "").ToString();
			string strCmdText = "";
			
			//-- Validamos consulta
			if (strQueryName == String.Empty)
				strQueryName = dataSetName + "." + tableName;

			objSql = module.QueryMap[strQueryName];

			if (objSql == null)
			{
				strCmdText = module.FindSelectCmdText(tableName);

				if (strCmdText == null)
					strCmdText = module.FindQueryInDB(strQueryName);

				if (pList != null && pList.Count > 0)
				{
					strCmdText = tryToInsertRecursiveTag(strCmdText);
					if (strCmdText == null)
                        throw new Exception("Debe definir el query " + dataSetName + "." + tableName + " para el dataset tipado " + dataSetName + " con el Tag: &&ToolbarFilter&& ya que el select query es complejo.");
				}
			}
			else
				strCmdText = objSql.ToString();
			//-- Regresamos el resultado
			return strCmdText;
		}

		private string getCmd(DAL.IDAL module, string queryName)
		{
			//-- Declaracion de variables
			object objSql;
			string strQueryName = Utils.Helpers.Nvl(queryName, "").ToString();
			string strCmdText = "";
			
			objSql = module.QueryMap[strQueryName];

			if (objSql == null)
				strCmdText = module.FindQueryInDB(strQueryName);
			else
				strCmdText = objSql.ToString();

            //-- Regresamos el resultado
			return strCmdText;
		}

        private string getRankCmd(DAL.IDAL module, string query, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Model.IntRange records, Utils.QueryParams pList)
		{
		//-- Declaracion de variables
			Model.IntRange localRange = new LLNet.Model.IntRange(range);
			string strLocalFilter = Utils.Helpers.Nvl(rankFilter, "").ToString(); 
			string strLocalSort = Utils.Helpers.Nvl(rankSort, "").ToString(); 
			string strRankField = "";
			string strCmd = query;
			string strQry = "";
		//-- Establecemos los filtros
			if (pList != null)
			{
				strCmd = pList.ReplaceParams(strCmd);
				if (strCmd == null) return null;
			}
		//-- Establecemos las propiedades
			if ((rankType == Model.FilterTypes.TopNPercent) || (rankType == Model.FilterTypes.BottomNPercent))
			{
			//-- Obtenemos el total de registros
				string strTmp = String.Format(module.QueryMap["TotCount"].ToString(), strCmd);
				object result = null;
				try	
				{
					result = module.ExecuteScalar(strTmp);
				} 
				catch (Exception ex) 
				{
                    throw new Exception(ex.Message);
				}
				long totRec =Helpers.ObjToInt64(result);
			//-- Establecemos las posiciones
				localRange.a = Convert.ToInt32(Math.Ceiling(Convert.ToDouble((totRec * localRange.a * 1.0)/100 )));
				localRange.b = Convert.ToInt32(Math.Ceiling(Convert.ToDouble((totRec * localRange.b * 1.0)/100 )));
			}
		//-- Establecemos el campo para el orden
			if (rankField != String.Empty)
			{
				if ((rankType == Model.FilterTypes.TopNRecords) || (rankType == Model.FilterTypes.TopNPercent))
					strRankField = String.Format("ORDER BY {0} DESC NULLS LAST", rankField);
				else
					strRankField = String.Format("ORDER BY {0} NULLS LAST", rankField);
			}
		//-- Preparar comando para ranking
			strCmd = String.Format(module.QueryMap["RankCmd"].ToString(), strCmd, strRankField);
		//-- Ranking
			strQry = module.QueryMap["PageCmd"].ToString();
			if (records != null)
				strQry = strQry.Replace("tupla", "tpl");
			strCmd = String.Format(strQry, strCmd, localRange.b, localRange.a);
		//-- Filtramos el ranking
			if((strLocalFilter != String.Empty) || (strLocalSort != String.Empty))
			{
				if (strLocalSort != String.Empty)
				{
					if (!strLocalSort.TrimStart().ToUpper().StartsWith("ORDER BY ")) 
						strLocalSort = "ORDER BY " + strLocalSort;
				}
				strCmd = String.Format(module.QueryMap["SelectRankCmd"].ToString(), strCmd, strLocalFilter, strLocalSort);
			}
		//-- Pagineo del ranking
			if (records != null)
				strCmd = String.Format(module.QueryMap["PageCmd"].ToString(), strCmd, records.b, records.a);
		//-- Regresamos el resultado
			return strCmd;
		}

		private bool IsValid(Model.IntRange range)
		{
			if (defaultConnName==null)
                throw new Exception("No hay conexión por default");

            if (range==null)
                throw new Exception("No hay rango especificado");

            if ((range.a < 0) || (range.b < 0))
                throw new Exception("El número de registros solicitado debe ser mayor que 0!");

            return true;
		}

		private bool IsValid(string connName, Model.IntRange rango1, Model.IntRange rango2)
		{
			if (connName==null)
                throw new Exception("No hay conexión establecida");

            if (rango1==null)
                throw new Exception("No hay rango especificado");                

            if ((rango1.a < 0) || (rango1.b < 0))
                throw new Exception("El número de registros solicitado debe ser mayor que 0!");

            if (rango2!=null)
			{
				if ((rango2.a < 0) || (rango2.b < 0))
                    throw new Exception("El número de registros solicitado debe ser mayor que 0!");
			}
			return true;
		}

		private Model.IntRange getRankCount(DAL.IDAL module, string query, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
		{
		//-- Declaracion de variables
			Model.IntRange localRange = new LLNet.Model.IntRange(range);
			string strLocalFilter = Utils.Helpers.Nvl(rankFilter, "").ToString(); 
			string strLocalSort = Utils.Helpers.Nvl(rankSort, "").ToString(); 
			string strRankField = "";
			string strCmd = query;
			object result = null;
		//-- Establecemos los filtros
			if (pList != null)
			{
				strCmd = pList.ReplaceParams(strCmd);
				if (strCmd == null) return null;
			}
		//-- Establecemos las propiedades
			if ((rankType == Model.FilterTypes.TopNPercent) || (rankType == Model.FilterTypes.BottomNPercent))
			{
			//-- Obtenemos el total de registros
				string strTmp = String.Format(module.QueryMap["TotCount"].ToString(), strCmd);
				try	
				{
					result = module.ExecuteScalar(strTmp);
				} 
				catch (Exception ex) 
				{
                    throw new Exception(ex.Message);
				}
				long totRec = Helpers.ObjToInt64(result);
			//-- Establecemos las posiciones
				localRange.a = Convert.ToInt32(Math.Ceiling(Convert.ToDouble((totRec * localRange.a * 1.0)/100 )));
				localRange.b = Convert.ToInt32(Math.Ceiling(Convert.ToDouble((totRec * localRange.b * 1.0)/100 )));
			}
			//-- Establecemos el campo para el orden
			if (rankField != String.Empty)
			{
			//-- Obtenemos el campo para el ranking
				if ((rankType == Model.FilterTypes.TopNRecords) || (rankType == Model.FilterTypes.TopNPercent))
					strRankField = String.Format("ORDER BY {0} DESC NULLS LAST", rankField);
				else
					strRankField = String.Format("ORDER BY {0} NULLS LAST", rankField);
			}
		//-- Preparar comando para ranking
			strCmd = String.Format(module.QueryMap["RankCmd"].ToString(), strCmd, strRankField);
		//-- Ranking
			strCmd = String.Format(module.QueryMap["PageCmd"].ToString(), strCmd, localRange.b, localRange.a);
		//-- Filtramos el ranking
			if(strLocalFilter != String.Empty)
				strCmd = String.Format(module.QueryMap["SelectRankCmd"].ToString(), strCmd, strLocalFilter, String.Empty);

        //-- Obtenemos el total de registros
			strCmd = String.Format(module.QueryMap["TotCount"].ToString(), strCmd);
			result = null;
			try	
			{
				result = module.ExecuteScalar(strCmd);
			} 
			catch (Exception ex) 
			{
                throw new Exception(ex.Message);
			}
			localRange.b = localRange.a + Helpers.ObjToInt64(result);
			if (Helpers.ObjToInt64(result) == 0)
			{
				localRange.a = 0;
				localRange.b = -1;
			}
		//-- Regresamos el resultado
			return localRange;
		}

		private string getTotalCmd(DAL.IDAL module, string[] fields, Model.TotalOperation operation, string query)
		{
		//-- Declaracion de variables
			string strHead = "";
			string strCmd = query;
			string strFormat = "";
		//-- Establecemos el formato segun el caso
			switch(operation)
			{
				case Model.TotalOperation.AbsSum:   strFormat = "sum(abs({0})) {0}";	break;
				case Model.TotalOperation.Average:  strFormat = "avg({0}) {0}";			break;
				case Model.TotalOperation.Minimum:  strFormat = "min({0}) {0}";			break;
				case Model.TotalOperation.Maximum:  strFormat = "max({0}) {0}";			break;
				default:							strFormat = "sum({0}) {0}";			break;
			}
		//-- Recorremos todos los campos
			for(int i = 0; i < fields.Length; i++)
			{
				if (fields[i] != String.Empty)
				{
					if (strHead.Length > 0) strHead += ", ";
					strHead += String.Format(strFormat, fields[i]);
				}
			}
		//-- Preparamos la cosulta
			strCmd = String.Format(module.QueryMap["TotCmd"].ToString(), strHead, strCmd);
		//-- Regresamos el resultado
			return strCmd;
		}
		#endregion

		#region iBLL Members

		#region Properties

		public string DefaultConnName
		{
			get{return defaultConnName;}
			set
			{
				if ( (defaultConnName != null) && (defaultConnName != value))
					loadModules.Clear();

                defaultConnName = value;
			}
		}

        public string ConnectionString
        {
            get 
            { 
                LoadModules("PDV", defaultConnName);
				ModuleDef def = (ModuleDef)loadModules["PDV" + defaultConnName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

                return objModule.ConnectionString(defaultConnName);
            }
        }
		#endregion

		#region GetModuleNameFromDataSet

		/// <summary>
		/// Basado en un Tipo de DataSet devuelve el módulo al que pertenece Ej. Recibos
		/// </summary>
		/// <param name="dsType"></param>
		/// <returns></returns>
		public string GetModuleNameFromDataSet(Type dsType)
		{
			string sType = dsType.ToString();
			int pos1 = sType.LastIndexOf(".");
			string sAux = sType.Substring(0,pos1);
			int pos2 = sAux.LastIndexOf(".");
			return sAux.Substring(pos2+1);
		}


		#endregion

		/// <summary>
		/// los warnings se pierden, no es recomendado usarla desde el cliente, es mas bien para uso de la DAL
		/// </summary>

		public DataSet RemoteExecute(string moduleName, string methodName, DataSet param)
		{
			if (defaultConnName!=null)
				return RemoteExecuteConn(moduleName, methodName, param, defaultConnName);
			else
                throw new Exception("No hay conexión por default");
		}

		public virtual DataSet RemoteExecuteConn(string moduleName, string methodName, DataSet param, string connName)
		{
			try
			{
				LoadModules(moduleName,connName);
				ModuleDef def = (ModuleDef)loadModules[moduleName + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;
				
				Type type = Type.GetType("LLNet.BLL." + moduleName + "." + moduleName,true);
				MethodInfo mi = type.GetMethod(methodName);
				// TODO: Pasar por referencia el dataset param
				mi.Invoke(null, new object[]{this,objModule,param});
				return param;
				
			}
			catch(Exception e)
			{
                string msg;
                if (e.InnerException != null)
                    msg = e.InnerException.Message;
                else
                    msg = e.Message;

                throw new Exception("Error en el llamado al metodo: " + methodName + " del modulo: " + moduleName + " error: " + msg);
			}
		}

        public object[] RemoteExecute(string moduleName, string methodName, object[] pArgs)
        {
            if (defaultConnName != null)
                return RemoteExecuteConn(moduleName, methodName, pArgs, defaultConnName);
            else
                throw new Exception("No hay conexión por default");
        }

        public virtual object[] RemoteExecuteConn(string moduleName, string methodName, object[] pArgs, string connName)
        {
            try
            {
                LoadModules(moduleName, connName);
                ModuleDef def = (ModuleDef)loadModules[moduleName + connName];

                DAL.IDAL objModule = (DAL.IDAL)def.module;

                Type type = Type.GetType("LLNet.BLL." + moduleName + "." + moduleName, true);
                MethodInfo mi = type.GetMethod(methodName);
                // TODO: Pasar por referencia el dataset param
                mi.Invoke(null, new object[] { this, objModule, pArgs });
                return pArgs;

            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                    throw new Exception("Error en el llamado al metodo: " + methodName + " del modulo: " + moduleName + " error: " + e.InnerException);
                else
                    throw new Exception("Error en el llamado al metodo: " + methodName + " del modulo: " + moduleName + " error: " + e.Message);
            }
        }


        #region LoadModules

		public virtual void LoadModules(string[] modules, string connName)
		{
			foreach (string module in modules)
			{
				LoadModules(module,connName);
			}
		}

		public virtual void LoadModules(string module, string connName)
		{
			try 
			{
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				if (def == null)
				{
					DAL.IDAL objInstance;

					string moduleName = getModuleName(connName,module);
					
					objInstance = DAL.ClassFactory.CreateModule(moduleName);
										
					if (!objInstance.Connect(connName))
						throw new Exception("No se ha podido conectar con "+connName);

                    def = new ModuleDef(connName,objInstance);
					loadModules.Add(module + connName,def);
				}
			} 
			catch (Exception ex)
			{
                if (ex.InnerException != null)
                    throw new Exception(ex.InnerException.Message);
                else
                     throw new Exception(ex.Message);
			}
		}

		#endregion

		#region GetSingleValue

		public object GetSingleValue(string queryName, string module)
		{
			if (defaultConnName!=null)
				return GetConnSingleValue(queryName,null,module,defaultConnName);

            throw new Exception("No hay conexión por default");
		}

		public object GetSingleValue(string queryName, Utils.QueryParams pList, string module)
		{
			if (defaultConnName!=null)
				return GetConnSingleValue(queryName,pList,module,defaultConnName);

            throw new Exception("No hay conexión por default");
        }

		public object GetSingleValue(string queryName, Utils.QueryParams pList, string module, bool hidden)
		{
			if (defaultConnName!=null)
				return GetConnSingleValue(queryName,pList,module,defaultConnName, hidden);

            throw new Exception("No hay conexión por default");
        }

		#endregion

		#region GetConnSingleValue

		public object GetConnSingleValue(string queryName, string module, string connName)
		{
			if (defaultConnName!=null)
				return GetConnSingleValue(queryName,null,module,connName);

            throw new Exception("No hay conexión por default");
        }
		
		public object GetConnSingleValue(string queryName, Utils.QueryParams pList, string module, string connName)
		{
			if (defaultConnName!=null)
				return GetConnSingleValue(queryName,pList,module,connName,false);

            throw new Exception("No hay conexión por default");
        }

		public object GetConnSingleValue(string queryName, Utils.QueryParams pList, string module, string connName, bool hidden)
		{
			LoadModules(module,connName);
			ModuleDef def = (ModuleDef)loadModules[module + connName];

			DAL.IDAL objModule = (DAL.IDAL)def.module;
			
			string sql = getCmd(objModule,queryName);

			object result = null;
			
			if (sql == null)
                throw new Exception("No está definido el sql " + queryName);
			else
			{
				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return null;
				}

				try
				{
					result = objModule.ExecuteScalar(sql,hidden);
				} 
				catch (Exception ex)
				{
                    throw new Exception(ex.Message);
				}
			
					
			}
			return result;
		}

		#endregion
		
		#region ExecuteSql

		public int ExecuteSql(string queryName, string module)
		{
			if (defaultConnName!=null)
				return ExecuteSqlConn(queryName,null,module,defaultConnName);

            throw new Exception("No hay conexión por default");
		}

		public int ExecuteSql(string queryName, Utils.QueryParams pList, string module)
		{
			if (defaultConnName!=null)
				return ExecuteSqlConn(queryName,pList,module,defaultConnName);
			
            throw new Exception("No hay conexión por default");
		}

        #endregion

		#region ExecuteSqlConn

		public int ExecuteSqlConn(string queryName, string module, string connName)
		{
			return ExecuteSqlConn(queryName,null,module,connName);
		}

		public int ExecuteSqlConn(string queryName, Utils.QueryParams pList, string module, string connName)
		{
			LoadModules(module,connName);
			ModuleDef def = (ModuleDef)loadModules[module + connName];

			DAL.IDAL objModule = (DAL.IDAL)def.module;
			
			string sql = getCmd(objModule,queryName);

			string tmp_sql = "";

			int result = -1;
			
			if (sql==null)
                throw new Exception("No está definido el sql " + queryName);
			else
			{
				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return result;
				}

				try
				{
					// Removiendo tabs, rc, nl
					tmp_sql = sql.Replace("\r"," ");
					sql = tmp_sql;
					tmp_sql = sql.Replace("\t"," ");
					sql = tmp_sql;
					tmp_sql = sql.Replace("\n"," ");
					sql = tmp_sql;
					
					result = objModule.ExecuteNonQuery(sql);
				} 
				catch (Exception ex)
				{
                    throw new Exception(ex.Message);
				}
			}
			return result;
		}

        #endregion

		#region getDataSet
			public DataSet getDataSet(string module, string queryName, long startRecord, long endRecord, Utils.QueryParams pList )
			{
				if (defaultConnName!=null)
					return getConnDataSet(module,queryName,defaultConnName,startRecord,endRecord,pList);

                throw new Exception("No hay conexión por default");
			}

			public DataSet getDataSet(string module, string queryName, long startRecord, long endRecord)
			{
				if (defaultConnName!=null)
					return getConnDataSet(module,queryName,defaultConnName,startRecord,endRecord);

                throw new Exception("No hay conexión por default");
			}

			public DataSet getDataSet(string module, string queryName, Utils.QueryParams pList )
			{
				if (defaultConnName!=null)
					return getConnDataSet(module,queryName,defaultConnName,pList);

                throw new Exception("No hay conexión por default");
			}

			public DataSet getDataSet(string module, string queryName)
			{
				if (defaultConnName!=null)
					return getConnDataSet(module,queryName,defaultConnName);

                throw new Exception("No hay conexión por default");
            }

			public DataSet getDataSet(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				return getConnDataSet(module, queryName, this.DefaultConnName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}

			public DataSet getDataSet(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort)
			{
				return getConnDataSet(module, queryName, this.DefaultConnName, rankType, range, rankField, records, rankFilter, rankSort);
			}

			public DataSet getDataSet(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList)
			{
				return getConnDataSet(module, queryName, this.DefaultConnName, rankType, range, rankField, records, pList);
			}

			public DataSet getDataSet(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records)
			{
				return getConnDataSet(module, queryName, this.DefaultConnName, rankType, range, rankField, records);
			}

			public DataSet getDataSet(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				return getConnDataSet(module, queryName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public DataSet getDataSet(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort)
			{
				return getConnDataSet(module, queryName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort);
			}

			public DataSet getDataSet(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				return getConnDataSet(module, queryName, this.DefaultConnName, rankType, range, rankField, pList);
			}

			public DataSet getDataSet(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				return getConnDataSet(module, queryName, this.DefaultConnName, rankType, range, rankField);
			}

		#endregion

		#region getConnDataSet
			public DataSet getConnDataSet(string module, string queryName, string connName, long startRecord, long endRecord, Utils.QueryParams pList )
			{
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				string sql = getCmd(objModule,queryName);

				if (sql==null)
                    throw new Exception("No está definido el sql " + queryName);

				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return null;
				}

				sql = objModule.QueryMap["beginPaging"].ToString() + sql + objModule.QueryMap["endPaging"].ToString();

				string err = objModule.SetSelectCommand(sql,startRecord,endRecord);
				DataSet dsResult = null;
				if (err == "")
				{
					dsResult = new DataSet();
					objModule.FillDataSet(dsResult,objModule.PagingAdapter);
				}
				else
                    throw new Exception(err);

				return dsResult;
			}

			public DataSet getConnDataSet(string module, string queryName, string connName, long startRecord, long endRecord)
			{
				return getDataSet(module, queryName, startRecord, endRecord, null);
			}

			public DataSet getConnDataSet(string module, string queryName, string connName, Utils.QueryParams pList )
			{
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				string sql = getCmd(objModule,queryName);

				if (sql==null)
                    throw new Exception("No está definido el sql " + queryName);

				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return null;
				}

				objModule.SetSelectCommand(sql);

				DataSet dsResult = new DataSet();
				objModule.FillDataSet(dsResult,objModule.SelectAdapter);

                return dsResult;
			}

			public DataSet getConnDataSet(string module, string queryName, string connName)
			{
				return getConnDataSet(module, queryName, connName, null);
			}


			public DataSet getConnDataSet(string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
			//-- Validacion inicial
				if (!IsValid(connName, range, records)) return null;
			//-- Declaracion de variables
				string strCmd = "";
			//-- Preparamos la consulta
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getCmd(objModule,queryName);
				strCmd = getRankCmd(objModule, strCmd, rankType, range, rankField, rankFilter, rankSort, records, pList);
			//-- Obtenemos el dataset
				objModule.SetSelectCommand(strCmd);
				DataSet dsResult = new DataSet();
				objModule.FillDataSet(dsResult,objModule.SelectAdapter);
			//-- Regresamos el resultado
				return dsResult;
			}

			public DataSet getConnDataSet(string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort)
			{
				Utils.QueryParams pList = null;
				return getConnDataSet(module, queryName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}

			public DataSet getConnDataSet(string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				return getConnDataSet(module, queryName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}

			public DataSet getConnDataSet(string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				Utils.QueryParams pList = null;
				return getConnDataSet(module, queryName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}


			public DataSet getConnDataSet(string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				Model.IntRange records = null;
				return getConnDataSet(module, queryName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}

			public DataSet getConnDataSet(string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort)
			{
				Utils.QueryParams pList = null;
				return getConnDataSet(module, queryName, connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public DataSet getConnDataSet(string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				return getConnDataSet(module, queryName, connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public DataSet getConnDataSet(string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				Utils.QueryParams pList = null;
				return getConnDataSet(module, queryName, connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

		#endregion

		#region getTypedDataSet
			public DataSet getTypedDataSet(Type dsType)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,defaultConnName);
				}
                throw new Exception("No hay conexión por default");
			}
			
			public DataSet getTypedDataSet(Type dsType, string[] tableNames)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableNames,defaultConnName);
				}
                throw new Exception("No hay conexión por default");
            }
			
			public DataSet getTypedDataSet(Type dsType, string tableName)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName);
				}
                throw new Exception("No hay conexión por default");
			}
			
			public DataSet getTypedDataSet(Type dsType, string tableName, Utils.QueryParams pList)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName,pList);
				}
                throw new Exception("No hay conexión por default");
            }

			public DataSet getTypedDataSet(Type dsType, string tableName, long startRecord, long endRecord)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName,startRecord,endRecord);
				}
                throw new Exception("No hay conexión por default");
            }

			public DataSet getTypedDataSet(Type dsType, string tableName, long startRecord, long endRecord, Utils.QueryParams pList)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName,startRecord,endRecord,pList);
				}
                throw new Exception("No hay conexión por default");
            }

			public DataSet getTypedDataSet(Type dsType, string tableName, long startRecord, long endRecord, QueryParams pList, string pQueryName)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName,startRecord,endRecord,pList,pQueryName);
				}
                throw new Exception("No hay conexión por default");
            }

			public DataSet getTypedDataSet(Type dsType, string tableName, QueryParams pList, string pQueryName)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName,pList,pQueryName);
				}
                throw new Exception("No hay conexión por default");
            }

			public DataSet getTypedDataSet(Type dsType, string tableName, string pQueryName)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName,pQueryName);
				}
                throw new Exception("No hay conexión por default");
            }


			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort, Utils.QueryParams pList, string queryName)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, records, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort, string queryName)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, records, rankFilter, rankSort, queryName);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList, string queryName)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, records, pList, queryName);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string queryName)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, records, queryName);
			}


			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList, string queryName)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, string queryName)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort, queryName);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList, string queryName)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, pList, queryName);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string queryName)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, queryName);
			}


			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, records, rankFilter, rankSort);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, records, pList);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, records);
			}


			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField, pList);
			}

			public DataSet getTypedDataSet(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				return getConnTypedDataSet(dsType, tableName, this.DefaultConnName, rankType, range, rankField);
			}

		#endregion

		#region getConnTypedDataSet
			public DataSet getConnTypedDataSet(Type dsType, string connName)
			{
				string module = GetModuleNameFromDataSet(dsType);
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				DataSet dsResult = getDataSetByType(dsType);

				if (dsResult == null)
				{
					return null;
				}

				foreach(DataTable dt in dsResult.Tables)
				{
					string sql = getTypedCmd(objModule,null,dsResult.DataSetName,dt.TableName,null);

					string err = objModule.SetSelectCommand(sql);
					if (err == "")
					{
						objModule.FillDataSet(dsResult,dt.TableName,objModule.SelectAdapter);
					}
					else
					{
                        throw new Exception(err);
					}
				}

				return dsResult;
			}
			
			public DataSet getConnTypedDataSet(Type dsType, string[] tableNames, string connName)
			{
				string module = GetModuleNameFromDataSet(dsType);
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				DataSet dsResult = getDataSetByType(dsType);

				if (dsResult == null)
				{
					return null;
				}


				foreach(string tableName in tableNames)
				{
					string sql = getTypedCmd(objModule,null,dsResult.DataSetName,tableName,null);

					string err = objModule.SetSelectCommand(sql);
					if (err == "")
					{
						objModule.FillDataSet(dsResult,tableName,objModule.SelectAdapter);
					}
					else
					{
                        throw new Exception(err);
					}
				}

				return dsResult;
			}
			
			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName,null,null);
				}
                throw new Exception("No hay conexión por default");
			}
			
			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Utils.QueryParams pList)
			{
				string module = GetModuleNameFromDataSet(dsType);
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;
				
				DataSet dsResult = getDataSetByType(dsType);

				if (dsResult == null)
				{
					return null;
				}

				string sql = getTypedCmd(objModule,null,dsResult.DataSetName,tableName,pList);

				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return null;
				}

				string err = objModule.SetSelectCommand(sql);
				
				if (err == "")
				{
					dsResult = objModule.FillDataSet(dsResult,tableName,objModule.SelectAdapter);
				}
				else
				{
                    throw new Exception(err);
				}

				return dsResult;
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, long startRecord, long endRecord)
			{
				string module = GetModuleNameFromDataSet(dsType);
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				DataSet dsResult = getDataSetByType(dsType);

				if (dsResult == null)
				{
					return null;
				}

				string sql = getTypedCmd(objModule,null,dsResult.DataSetName,tableName,null);

				sql = objModule.QueryMap["beginPaging"].ToString() + sql + objModule.QueryMap["endPaging"].ToString();

				string err = objModule.SetSelectCommand(sql,startRecord,endRecord);
				if (err == "")
				{
					dsResult = objModule.FillDataSet(dsResult,tableName, objModule.PagingAdapter);
				}
				else
				{
                    throw new Exception(err);
				}

				return dsResult;
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, long startRecord, long endRecord, Utils.QueryParams pList)
			{
				string module = GetModuleNameFromDataSet(dsType);
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				DataSet dsResult = getDataSetByType(dsType);

				if (dsResult == null)
				{
					return null;
				}

				string sql = getTypedCmd(objModule,null,dsResult.DataSetName,tableName,pList);
				
				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return null;
				}

				sql = objModule.QueryMap["beginPaging"].ToString() + sql + objModule.QueryMap["endPaging"].ToString();

				string err = objModule.SetSelectCommand(sql,startRecord,endRecord);
				if (err == "")
				{
					dsResult = getDataSetByType(dsType);
					dsResult = objModule.FillDataSet(dsResult,tableName, objModule.PagingAdapter);
				}
				else
				{
                    throw new Exception(err);
				}

				return dsResult;
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, long startRecord, long endRecord, QueryParams pList, string pQueryName)
			{
				string module = GetModuleNameFromDataSet(dsType);
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				DataSet dsResult = getDataSetByType(dsType);

				if (dsResult == null)
				{
					return null;
				}

				string sql = getTypedCmd(objModule,pQueryName,dsResult.DataSetName,tableName,pList);

				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return null;
				}

				sql = objModule.QueryMap["beginPaging"].ToString() + sql + objModule.QueryMap["endPaging"].ToString();

				string err = objModule.SetSelectCommand(sql,startRecord,endRecord);
				if (err == "")
				{
					dsResult = getDataSetByType(dsType);
					dsResult = objModule.FillDataSet(dsResult,tableName, objModule.PagingAdapter);
				}
				else
				{
                    throw new Exception(err);
				}

				return dsResult;
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, QueryParams pList, string pQueryName)
			{
				string module = GetModuleNameFromDataSet(dsType);
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;
				
				DataSet dsResult = getDataSetByType(dsType);

				if (dsResult == null)
				{
					return null;
				}

				string sql = getTypedCmd(objModule,pQueryName,dsResult.DataSetName,tableName,pList);

				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return null;
				}

				string err = objModule.SetSelectCommand(sql);
				
				if (err == "")
				{
					dsResult = objModule.FillDataSet(dsResult,tableName,objModule.SelectAdapter);
				}
				else
				{
                    throw new Exception(err);
				}

				return dsResult;
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, string pQueryName)
			{
				if (defaultConnName!=null)
				{
					return getConnTypedDataSet(dsType,tableName,defaultConnName,null,pQueryName);
				}
                throw new Exception("No hay conexión por default");
			}


			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort, Utils.QueryParams pList, string queryName)
			{
			//-- Validacion inicial
				if (!IsValid(connName, range, records)) return null;
			//-- Declaracion de variables
				string strCmd = "";
				string module = GetModuleNameFromDataSet(dsType);
				DataSet dsResult = getDataSetByType(dsType);
			//-- Preparamos la consulta
				if (dsResult == null) return null;
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getTypedCmd(objModule, queryName, dsResult.DataSetName, tableName, pList);
				if (strCmd == null) return null;
				strCmd = getRankCmd(objModule, strCmd, rankType, range, rankField, rankFilter, rankSort, records, pList);
			//-- Obtenemos el dataset
				objModule.SetSelectCommand(strCmd);
				dsResult = objModule.FillDataSet(dsResult, tableName, objModule.SelectAdapter);
			//-- Regresamos el resultado
				return dsResult;
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort, string queryName)
			{
				Utils.QueryParams pList = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList, string queryName)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string queryName)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				Utils.QueryParams pList = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList, queryName);
			}


			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList, string queryName)
			{
				Model.IntRange records = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, string queryName)
			{
				Utils.QueryParams pList = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList, string queryName)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string queryName)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				Utils.QueryParams pList = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, rankFilter, rankSort, pList, queryName);
			}


			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				string queryName = String.Empty;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, string rankSort)
			{
				Utils.QueryParams pList = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				Utils.QueryParams pList = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList);
			}


			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				Model.IntRange records = null;
				string queryName = String.Empty;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, records, rankFilter, rankSort, pList, queryName);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort)
			{
				Utils.QueryParams pList = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public DataSet getConnTypedDataSet(Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				Utils.QueryParams pList = null;
				return getConnTypedDataSet(dsType, tableName, connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}
		
		#endregion

		#region GetCount
			public long GetCount(Type dsType, string tableName)
			{
				if (defaultConnName!=null)
				{
					return GetConnCount(dsType,tableName,defaultConnName);
				}
                throw new Exception("No hay conexión por default");
			}

			public long GetCount(Type dsType, string tableName, Utils.QueryParams pList)
			{
				if (defaultConnName!=null)
				{
					return GetConnCount(dsType,tableName,defaultConnName,pList);
				}
                throw new Exception("No hay conexión por default");
			}

			public long GetCount(Type dsType, string tableName, string pQueryName)
			{
				if (defaultConnName!=null)
				{
					return GetConnCount(dsType,tableName,defaultConnName,pQueryName);
				}
                throw new Exception("No hay conexión por default");
			}

			public long GetCount(Type dsType, string tableName, QueryParams pList, string pQueryName)
			{
				if (defaultConnName!=null)
				{
					return GetConnCount(dsType,tableName,defaultConnName,pList,pQueryName);
				}
                throw new Exception("No hay conexión por default");
			}

			public long GetCount(string module, string queryName, QueryParams pList)
			{
				if (defaultConnName!=null)
				{
					return GetConnCount(module,queryName,defaultConnName,pList);
				}
                throw new Exception("No hay conexión por default");
			}

			public Model.IntRange GetCount(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				return GetConnCount(dsType, tableName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public Model.IntRange GetCount(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort)
			{
				return GetConnCount(dsType, tableName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort);
			}

			public Model.IntRange GetCount(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				return GetConnCount(dsType, tableName, this.DefaultConnName, rankType, range, rankField, pList);
			}

			public Model.IntRange GetCount(Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				return GetConnCount(dsType, tableName, this.DefaultConnName, rankType, range, rankField);
			}

			public Model.IntRange GetCount(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
				return GetConnCount(module, queryName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public Model.IntRange GetCount(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort)
			{
				return GetConnCount(module, queryName, this.DefaultConnName, rankType, range, rankField, rankFilter, rankSort);
			}

			public Model.IntRange GetCount(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				return GetConnCount(module, queryName, this.DefaultConnName, rankType, range, rankField, pList);
			}

			public Model.IntRange GetCount(string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				return GetConnCount(module, queryName, this.DefaultConnName, rankType, range, rankField);
			}

		#endregion

		#region GetConnCount
			public long GetConnCount(Type dsType, string tableName, string connName)
			{
				if (defaultConnName!=null)
				{
					return GetConnCount(dsType,tableName,connName,null,null);
				}
                throw new Exception("No hay conexión por default");
			}

			public long GetConnCount(Type dsType, string tableName, string connName, Utils.QueryParams pList)
			{
				if (defaultConnName!=null)
				{
					return GetConnCount(dsType,tableName,connName,pList,null);
				}
                throw new Exception("No hay conexión por default");
			}

			public long GetConnCount(Type dsType, string tableName, string connName, string pQueryName)
			{
				string module = GetModuleNameFromDataSet(dsType);
					
				LoadModules(module,connName);
                ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				string sql = getTypedCmd(objModule,pQueryName,"",tableName,null);

				if (sql == null)
				{
                    throw new Exception("No existe un adapter para la tabla: " + tableName);
				}
					
				object result = null;
				sql = "SELECT ROUND(COUNT(1),0) FROM (" + sql + ") countTable ";

				try
				{
					result = objModule.ExecuteScalar(sql);
				} 
				catch (Exception ex)
				{
                    throw new Exception(ex.Message);
				}

				return Helpers.ObjToInt64(result);
			}

			public long GetConnCount(Type dsType, string tableName, string connName, QueryParams pList, string pQueryName)
			{
				string module = GetModuleNameFromDataSet(dsType);
					
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;
					
				DataSet dsResult = getDataSetByType(dsType);

				if (dsResult == null)
				{
					return -1;
				}

				string sql = getTypedCmd(objModule,pQueryName,dsResult.DataSetName,tableName,pList);

				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return -1;
				}
					
				object result = null;
				sql = "SELECT ROUND(COUNT(1),0) FROM (" + sql + ") cntTable ";

				try
				{
					result = objModule.ExecuteScalar(sql);
				} 
				catch (Exception ex)
				{
                    throw new Exception(ex.Message);
				}

				return Helpers.ObjToInt64(result);
			}

			public long GetConnCount(string module, string queryName, string connName, QueryParams pList)
			{
					
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];

				DAL.IDAL objModule = (DAL.IDAL)def.module;

				string sql = getCmd(objModule,queryName);
	
				if (pList != null && pList.Count > 0)
				{
					if (sql == null)
					{
                        throw new Exception("Debe definir el query " + queryName);
					}
				}

				if (pList != null)
				{
					sql = pList.ReplaceParams(sql);
					if (sql == null) return -1;
				}
					
				object result = null;
				sql = "SELECT ROUND(COUNT(1),0) FROM (" + sql + ") cntTable ";

				try
				{
					result = objModule.ExecuteScalar(sql);
				} 
				catch (Exception ex)
				{
                    throw new Exception(ex.Message);
				}

				return Helpers.ObjToInt64(result);
			}


			public Model.IntRange GetConnCount(Type dsType, string tableName,  string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
			//-- Validacion inicial
				if (!IsValid(connName, range, null)) return null;
			//-- Declaracion de variables
				Model.IntRange result;
				string strCmd = "";
				string module = GetModuleNameFromDataSet(dsType);
				DataSet dsResult = getDataSetByType(dsType);
			//-- Preparamos la consulta
				if (dsResult == null) return null;
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getTypedCmd(objModule, null, dsResult.DataSetName, tableName, pList);
				if (strCmd == null) return null;
				result = getRankCount(objModule, strCmd, rankType, range, rankField, rankFilter, rankSort, pList);
			//-- Regresamos el resultado
				return result;
			}

			public Model.IntRange GetConnCount(Type dsType, string tableName,  string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort)
			{
				Utils.QueryParams pList = null;
				return GetConnCount(dsType, tableName,  connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public Model.IntRange GetConnCount(Type dsType, string tableName,  string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				return GetConnCount(dsType, tableName,  connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public Model.IntRange GetConnCount(Type dsType, string tableName,  string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				Utils.QueryParams pList = null;
				return GetConnCount(dsType, tableName,  connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}


			public Model.IntRange GetConnCount(string module, string queryName,  string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort, Utils.QueryParams pList)
			{
			//-- Validacion inicial
				if (!IsValid(connName, range, null)) return null;
			//-- Declaracion de variables
				Model.IntRange result;
				string strCmd = "";
			//-- Preparamos la consulta
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getCmd(objModule,queryName);
				result = getRankCount(objModule, strCmd, rankType, range, rankField, rankFilter, rankSort, pList);
			//-- Regresamos el resultado
				return result;
			}

			public Model.IntRange GetConnCount(string module, string queryName,  string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, string rankSort)
			{
				Utils.QueryParams pList = null;
				return GetConnCount(module, queryName,  connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public Model.IntRange GetConnCount(string module, string queryName,  string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				return GetConnCount(module, queryName,  connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

			public Model.IntRange GetConnCount(string module, string queryName,  string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				string rankFilter = String.Empty;
				string rankSort = String.Empty;
				Utils.QueryParams pList = null;
				return GetConnCount(module, queryName,  connName, rankType, range, rankField, rankFilter, rankSort, pList);
			}

		#endregion

		#region getTotals (para devolver los totales de los campos de una tabla)

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, long startRecord, long endRecord)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, startRecord, endRecord);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, long startRecord, long endRecord, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, startRecord, endRecord, pList);
			}


			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, rankType, range, rankField, records, rankFilter);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, rankType, range, rankField, records, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, rankType, range, rankField, records);
			}

            public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, rankType, range, rankField, rankFilter, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, rankType, range, rankField, rankFilter);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, rankType, range, rankField, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				return getConnTotals(fields, operation, dsType, tableName, this.defaultConnName, rankType, range, rankField);
			}

            public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, long startRecord, long endRecord)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, startRecord, endRecord);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, long startRecord, long endRecord, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, startRecord, endRecord, pList);
			}


			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, rankType, range, rankField, records, rankFilter);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, rankType, range, rankField, records, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, rankType, range, rankField, records);
			}


			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, rankType, range, rankField, rankFilter, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, rankType, range, rankField, rankFilter);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, rankType, range, rankField, pList);
			}

			public DataSet getTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				return getConnTotals(fields, operation, module, queryName, this.defaultConnName, rankType, range, rankField);
			}

		#endregion

		#region GetConnTotals (para devolver los totales segun los parametros con una conexion específica)

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName)
			{
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, dsType, tableName, connName, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Utils.QueryParams pList)
			{
				//-- Validacion inicial
				if (!IsValid(connName, new Model.IntRange(0, 0), null)) return null;
				//-- Declaracion de variables
				string strCmd = "";
				string module = GetModuleNameFromDataSet(dsType);
				DataSet dsResult = getDataSetByType(dsType);
				//-- Preparamos la consulta
				if (dsResult == null) return null;
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getTypedCmd(objModule, null, dsResult.DataSetName, tableName, pList);
				if (strCmd == null) return null;
				//-- Establecemos los filtros
				if (pList != null)
				{
					strCmd = pList.ReplaceParams(strCmd);
					if (strCmd == null) return null;
				}
				strCmd = getTotalCmd(objModule, fields, operation, strCmd);
				//-- Obtenemos el dataset
				objModule.SetSelectCommand(strCmd);
				dsResult = new DataSet();
				objModule.FillDataSet(dsResult, tableName, objModule.SelectAdapter);
				//-- Regresamos el resultado
				return dsResult;
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, long startRecord, long endRecord)
			{
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, dsType, tableName, connName, startRecord, endRecord, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, long startRecord, long endRecord, Utils.QueryParams pList)
			{
				//-- Validacion inicial
				if (!IsValid(connName, new Model.IntRange(startRecord, endRecord), null)) return null;
				//-- Declaracion de variables
				string strCmd = "";
				string module = GetModuleNameFromDataSet(dsType);
				DataSet dsResult = getDataSetByType(dsType);
				//-- Preparamos la consulta
				if (dsResult == null) return null;
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getTypedCmd(objModule, null, dsResult.DataSetName, tableName, pList);
				if (strCmd == null) return null;
				//-- Establecemos los filtros
				if (pList != null)
				{
					strCmd = pList.ReplaceParams(strCmd);
					if (strCmd == null) return null;
				}
				//-- Pagineo
				strCmd = String.Format(objModule.QueryMap["PageCmd"].ToString(), strCmd, endRecord, startRecord);
				strCmd = getTotalCmd(objModule, fields, operation, strCmd);
				//-- Obtenemos el dataset
				objModule.SetSelectCommand(strCmd);
				dsResult = new DataSet();
				objModule.FillDataSet(dsResult, tableName, objModule.SelectAdapter);
				//-- Regresamos el resultado
				return dsResult;
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, Utils.QueryParams pList)
			{
				//-- Validacion inicial
				if (!IsValid(connName, range, records)) return null;
				//-- Declaracion de variables
				string strCmd = "";
				string module = GetModuleNameFromDataSet(dsType);
				DataSet dsResult = getDataSetByType(dsType);
				//-- Preparamos la consulta
				if (dsResult == null) return null;
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getTypedCmd(objModule, null, dsResult.DataSetName, tableName, pList);
				if (strCmd == null) return null;
				strCmd = getRankCmd(objModule, strCmd, rankType, range, rankField, rankFilter, String.Empty, records, pList);
				strCmd = getTotalCmd(objModule, fields, operation, strCmd);
				//-- Obtenemos el dataset
				objModule.SetSelectCommand(strCmd);
				dsResult = new DataSet();
				objModule.FillDataSet(dsResult, tableName, objModule.SelectAdapter);
				//-- Regresamos el resultado
				return dsResult;
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter)
			{
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, dsType, tableName, connName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				return getConnTotals(fields, operation, dsType, tableName, connName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records)
			{
				string rankFilter = String.Empty;
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, dsType, tableName, connName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, Utils.QueryParams pList)
			{
				Model.IntRange records = null;
				return getConnTotals(fields, operation, dsType, tableName, connName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter)
			{
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, dsType, tableName, connName, rankType, range, rankField, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				return getConnTotals(fields, operation, dsType, tableName, connName, rankType, range, rankField, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, Type dsType, string tableName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				string rankFilter = String.Empty;
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, dsType, tableName, connName, rankType, range, rankField, rankFilter, pList);
			}


			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName)
			{
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, module, queryName, connName, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Utils.QueryParams pList)
			{
				//-- Validacion inicial
				if (!IsValid(connName, new Model.IntRange(0, 0), null)) return null;
				//-- Declaracion de variables
				string strCmd = "";
				//-- Preparamos la consulta
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getCmd(objModule,queryName);

				//-- Establecemos los filtros
				if (pList != null)
				{
					strCmd = pList.ReplaceParams(strCmd);
					if (strCmd == null) return null;
				}
				strCmd = getTotalCmd(objModule, fields, operation, strCmd);
				//-- Obtenemos el dataset
				objModule.SetSelectCommand(strCmd);
				DataSet dsResult = new DataSet();
				objModule.FillDataSet(dsResult,objModule.SelectAdapter);
				//-- Regresamos el resultado
				return dsResult;
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, long startRecord, long endRecord)
			{
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, module, queryName, connName, startRecord, endRecord, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, long startRecord, long endRecord, Utils.QueryParams pList)
			{
				//-- Validacion inicial
				if (!IsValid(connName, new Model.IntRange(startRecord, endRecord), null)) return null;
				//-- Declaracion de variables
				string strCmd = "";
				//-- Preparamos la consulta
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getCmd(objModule,queryName);

				//-- Establecemos los filtros
				if (pList != null)
				{
					strCmd = pList.ReplaceParams(strCmd);
					if (strCmd == null) return null;
				}
				//-- Pagineo
				strCmd = String.Format(objModule.QueryMap["PageCmd"].ToString(), strCmd, endRecord, startRecord);
				strCmd = getTotalCmd(objModule, fields, operation, strCmd);
				//-- Obtenemos el dataset
				objModule.SetSelectCommand(strCmd);
				DataSet dsResult = new DataSet();
				objModule.FillDataSet(dsResult,objModule.SelectAdapter);
				//-- Regresamos el resultado
				return dsResult;
			}
				
			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter, Utils.QueryParams pList)
			{
				//-- Validacion inicial
				if (!IsValid(connName, range, records)) return null;
				//-- Declaracion de variables
				string strCmd = "";
				//-- Preparamos la consulta
				LoadModules(module,connName);
				ModuleDef def = (ModuleDef)loadModules[module + connName];
				DAL.IDAL objModule = (DAL.IDAL)def.module;
				strCmd = getCmd(objModule,queryName);
				strCmd = getRankCmd(objModule, strCmd, rankType, range, rankField, rankFilter, String.Empty, records, pList);
				strCmd = getTotalCmd(objModule, fields, operation, strCmd);
				//-- Obtenemos el dataset
				objModule.SetSelectCommand(strCmd);
				DataSet dsResult = new DataSet();
				objModule.FillDataSet(dsResult,objModule.SelectAdapter);
				//-- Regresamos el resultado
				return dsResult;
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, string rankFilter)
			{
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, module, queryName, connName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				return getConnTotals(fields, operation, module, queryName, connName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Model.IntRange records)
			{
				string rankFilter = String.Empty;
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, module, queryName, connName, rankType, range, rankField, records, rankFilter, pList);
			}


			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter, Utils.QueryParams pList)
			{
				Model.IntRange records = null;
				return getConnTotals(fields, operation, module, queryName, connName, rankType, range, rankField, records, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, string rankFilter)
			{
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, module, queryName, connName, rankType, range, rankField, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField, Utils.QueryParams pList)
			{
				string rankFilter = String.Empty;
				return getConnTotals(fields, operation, module, queryName, connName, rankType, range, rankField, rankFilter, pList);
			}

			public DataSet getConnTotals(string[] fields, Model.TotalOperation operation, string module, string queryName, string connName, Model.FilterTypes rankType, Model.IntRange range, string rankField)
			{
				string rankFilter = String.Empty;
				Utils.QueryParams pList = null;
				return getConnTotals(fields, operation, module, queryName, connName, rankType, range, rankField, rankFilter, pList);
			}

		#endregion

		#region update

		public DataSet updateDataSet(DataSet ds)
		{
			if (defaultConnName!=null)
				return updateConnDataSet(ds,defaultConnName);

            throw new Exception("No hay conexión por default");
		}
		

		public DataSet updateDataSet(DataSet ds, string tableName)
		{
			if (defaultConnName!=null)
				return updateConnDataSet(ds,tableName,defaultConnName);

            throw new Exception("No hay conexión por default");			
		}

        public DataSet updateDataSet(DataSet ds, string[] tablesName)
		{
			if (defaultConnName!=null)
				return updateConnDataSet(ds,tablesName,defaultConnName);

            throw new Exception("No hay conexión por default");			
		}


		public DataSet updateConnDataSet(DataSet ds, string connName)
		{
			DataSet dsToUpdate;

			// Verifica reglas de negocio a través de un merge
			DataSet ruleDataSet = FindRuleDataSetByDsType(ds.GetType());

			if (ruleDataSet != null)
			{
				ruleDataSet.Merge(ds,true);

				if (ruleDataSet.HasErrors)
                    throw new Exception("No se cumplieron las reglas de negocio en " + ds.DataSetName);

                dsToUpdate = new DataSet();
				dsToUpdate.Merge(ruleDataSet,true);
			}
			else
				dsToUpdate = ds;

            // Carga el modulo del dataset si no está cargado
			string sModule = GetModuleNameFromDataSet(ds.GetType());
			LoadModules(sModule,connName);

			ModuleDef def = (ModuleDef)loadModules[sModule + connName];
			DAL.IDAL module = (DAL.IDAL)def.module;

			foreach (DataTable dTable in dsToUpdate.Tables)
			{
				
				if (dTable.GetChanges() != null)
				{
					IDataAdapter ida = module.FindAdapter(dTable.TableName);
					if (ida != null)
					{
						try
						{
							module.Update(ida, ref dsToUpdate);
						} 
						catch (Exception ex)
						{
                            throw new Exception(ex.Message);
						}
					}
					else
                        throw new Exception("No tiene definido un DataAdapter para actualizar la tabla " + dTable.TableName);
                }
			}
			return dsToUpdate;
		}


		public DataSet updateConnDataSet(DataSet ds, string tableName, string connName)
		{
			//
			// TODO: Mejorar el algoritmo de actualizacion para que no sea 3-n
			//

			DataSet dsToUpdate;

			// Verifica reglas de negocio a través de un merge
			DataSet ruleDataSet = FindRuleDataSetByDsType(ds.GetType());

			if (ruleDataSet != null)
			{
				ruleDataSet.Merge(ds,true);

				if (ruleDataSet.HasErrors)
                    throw new Exception("No se cumplieron las reglas de negocio en " + ds.DataSetName);

                dsToUpdate = new DataSet();
				dsToUpdate.Merge(ruleDataSet,true);
			}
			else
				dsToUpdate = ds;

			// Carga el modulo del dataset si no está cargado
			string sModule = GetModuleNameFromDataSet(ds.GetType());
			LoadModules(sModule,connName);

			ModuleDef def = (ModuleDef)loadModules[sModule + connName];
			DAL.IDAL module = (DAL.IDAL)def.module;

			DataTable dTable = ds.Tables[tableName];
				
			if (dTable.Rows.Count > 0)
			{
				IDataAdapter ida = module.FindAdapter(dTable.TableName);
				if (ida != null)
				{
					try
					{
						module.Update(ida, ref dsToUpdate);
					} 
					catch (Exception ex)
					{
                        throw new Exception(ex.Message);
					}
				}
				else
                    throw new Exception("No tiene definido un DataAdapter para actualizar la tabla " + dTable.TableName);
			}
			return dsToUpdate;
		}
	
		
		public DataSet updateConnDataSet(DataSet ds, string[] tablesName, string connName)
		{
			DataSet dsToUpdate;

			// Verifica reglas de negocio a través de un merge
			DataSet ruleDataSet = FindRuleDataSetByDsType(ds.GetType());

			if (ruleDataSet != null)
			{
				ruleDataSet.Merge(ds,true);

				if (ruleDataSet.HasErrors)
                    throw new Exception("No se cumplieron las reglas de negocio en " + ds.DataSetName);

                dsToUpdate = new DataSet();
				dsToUpdate.Merge(ruleDataSet,true);
			}
			else
			{
				dsToUpdate = ds;
			}

			// Carga el modulo del dataset si no está cargado
			string sModule = GetModuleNameFromDataSet(ds.GetType());
			LoadModules(sModule,connName);

			ModuleDef def = (ModuleDef)loadModules[sModule + connName];
			DAL.IDAL module = (DAL.IDAL)def.module;

			DataTable dTable;
			foreach (string tableName in tablesName)
			{
				dTable = ds.Tables[tableName];

				if (dTable.Rows.Count > 0)
				{
					IDataAdapter ida = module.FindAdapter(dTable.TableName);
					if (ida != null)
					{
						try
						{
							module.Update(ida, ref dsToUpdate);
						} 
						catch (Exception ex)
						{
                            throw new Exception(ex.Message);
						}
					}
					else
                        throw new Exception(" No tiene definido un DataAdapter para actualizar la tabla " + dTable.TableName);
				}
			}
			return dsToUpdate;
		}

        #endregion

		#endregion

	}
}