437 lines
17 KiB
C#
437 lines
17 KiB
C#
using System.Data.SQLite;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace ADSUtileriasService.Helpers.ADSSqlite
|
|
{
|
|
|
|
public class SqlLiteBase : IDisposable
|
|
{
|
|
private SQLiteConnection conexion;
|
|
private string ConnectionString;
|
|
private SqlLiteConnectionEnum BDTypecon;
|
|
private bool isopened;
|
|
private SQLiteCommand comando;
|
|
private SQLiteTransaction transaccion;
|
|
public SQLiteCommand command { get { return comando; } }
|
|
public bool Isopen { get { return isopened; } }
|
|
public SqlLiteConnectionEnum BDType { get { return BDTypecon; } }
|
|
/// <summary>
|
|
/// Crear variable de conexion a la BD de la aplicacion empresa (SqLiteBaseConection.Empresa)
|
|
/// </summary>
|
|
public SqlLiteBase() : this(SqlLiteConnectionEnum.Empresa, -2)
|
|
{ }
|
|
/// <summary>
|
|
/// Crear variable de conexion a la BD
|
|
/// </summary>
|
|
/// <param name="bdtypecon">Empresa o configuracion</param>
|
|
public SqlLiteBase(SqlLiteConnectionEnum bdtypecon, int CveEmpresa)
|
|
{
|
|
if (CveEmpresa == -2)
|
|
{
|
|
CveEmpresa = GlobalVars.user.CveEmpresa;
|
|
}
|
|
switch (bdtypecon)
|
|
{
|
|
case SqlLiteConnectionEnum.AppConfig:
|
|
ConnectionString = string.Format("Data Source={0}AppConfig.db;Version=3;", ADSNetLibrary.Helpers.ModVars.FilesDir);
|
|
break;
|
|
case SqlLiteConnectionEnum.Empresa:
|
|
string dir = string.Format("{0}Empresas\\{1}\\", ADSNetLibrary.Helpers.ModVars.FilesDir, CveEmpresa);
|
|
if (!System.IO.Directory.Exists(dir))
|
|
{
|
|
System.IO.Directory.CreateDirectory(dir);
|
|
}
|
|
ConnectionString = string.Format("Data Source={0}EmpresaBD.db;Version=3;", dir);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
this.BDTypecon = bdtypecon;
|
|
isopened = false;
|
|
try
|
|
{
|
|
conexion = new SQLiteConnection(ConnectionString);//;Version=3;
|
|
conexion.Open();
|
|
isopened = true;
|
|
}
|
|
catch (Exception e) {
|
|
Mod.GuardaLog(e,"Error al inicializar la base de datos local", LogsNames.LocalRepository); }
|
|
}
|
|
public SQLiteTransaction BeginTransaction()
|
|
{
|
|
if(transaccion == null)
|
|
{
|
|
transaccion= conexion.BeginTransaction();
|
|
}
|
|
return transaccion;
|
|
}
|
|
public void Commit()
|
|
{
|
|
transaccion.Commit();
|
|
transaccion = null;
|
|
}
|
|
public void Rollback()
|
|
{
|
|
transaccion.Rollback();
|
|
transaccion = null;
|
|
}
|
|
public bool ClearCommand(string query)
|
|
{
|
|
try
|
|
{
|
|
if (comando == null)
|
|
{
|
|
comando = conexion.CreateCommand();
|
|
}
|
|
comando.CommandText = query;
|
|
comando.Parameters.Clear();
|
|
return true;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Mod.GuardaLog(e, "Error al inicializar Comando", LogsNames.LocalRepository);
|
|
return false;
|
|
}
|
|
}
|
|
public int ExecuteNonQuery()
|
|
{
|
|
return comando.ExecuteNonQuery();
|
|
}
|
|
|
|
public int RunExecuteNonQuery(string query)
|
|
{
|
|
int retorno = -1;
|
|
ClearCommand(query);
|
|
retorno = comando.ExecuteNonQuery();
|
|
return retorno;
|
|
}
|
|
public SQLiteDataReader ExecuteReader()
|
|
{
|
|
return comando.ExecuteReader();
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
/// Obtiene una lista de objetos es necesario ejecutar el metodo ClearCommand y agregar los parametros antes.
|
|
/// </summary>
|
|
/// <typeparam name="T">Clase genérica en donde se obtiene la información del SqlDataReader.</typeparam>
|
|
/// <returns>Lista de objetos "T".</returns>
|
|
public List<T> QueryToList<T>() where T : class, new()
|
|
{
|
|
List<T> retorno = null;
|
|
using (SQLiteDataReader reader = comando.ExecuteReader())
|
|
{
|
|
retorno = CreateList<T>(reader);
|
|
}
|
|
return retorno;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Obtiene un Objeto es necesario ejecutar el metodo ClearCommand y agregar los parametros antes.
|
|
/// </summary>
|
|
/// <typeparam name="T">Clase genérica en donde se obtiene la información de la consulta.</typeparam>
|
|
/// <returns>Objeto "T".</returns>
|
|
public T QueryToObject<T>() where T : class, new()
|
|
{
|
|
T retorno = null;
|
|
using (SQLiteDataReader reader = comando.ExecuteReader())
|
|
{
|
|
retorno = CreateObject<T>(reader);
|
|
}
|
|
return retorno;
|
|
}
|
|
|
|
|
|
#region mapperReader
|
|
|
|
/// <summary>
|
|
/// Obtiene una lista de objetos a partir de un SqlDataReader.
|
|
/// </summary>
|
|
/// <typeparam name="T">Clase genérica en donde se obtiene la información del SqlDataReader.</typeparam>
|
|
/// <param name="dataReader">SqlDataReader a leer.</param>
|
|
/// <returns>Lista de objetos.</returns>
|
|
public static List<T> CreateList<T>(SQLiteDataReader dataReader) where T : class, new()
|
|
{
|
|
var results = new List<T>();
|
|
var properties = typeof(T).GetProperties();
|
|
List<System.Reflection.PropertyInfo> propinobj = new List<System.Reflection.PropertyInfo>();
|
|
foreach (var property in properties)
|
|
{
|
|
|
|
if (IsColumnExists(dataReader, property.Name))
|
|
{
|
|
propinobj.Add(property);
|
|
}
|
|
}
|
|
while (dataReader.Read())
|
|
{
|
|
var item = Activator.CreateInstance<T>();
|
|
foreach (var property in propinobj)
|
|
{
|
|
if (!dataReader.IsDBNull(dataReader.GetOrdinal(property.Name)))
|
|
{
|
|
Type convertTo = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
|
|
object objvalue;
|
|
switch (property.PropertyType.Name)
|
|
{
|
|
case "Boolean":
|
|
{
|
|
objvalue = (dataReader[property.Name].ToString().ToUpper().Contiene(new string[] { "1", "TRUE"}));
|
|
property.SetValue(item, objvalue, null);
|
|
break;
|
|
}
|
|
case "DateTime":
|
|
{
|
|
/*
|
|
*
|
|
* DateTime.Ticks
|
|
*
|
|
*/
|
|
try
|
|
{
|
|
property.SetValue(item, Convert.ChangeType(dataReader[property.Name], convertTo), null);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
property.SetValue(item, new DateTime(dataReader[property.Name].ToString().ToEntero()), null);
|
|
}
|
|
break;
|
|
}
|
|
|
|
default:
|
|
property.SetValue(item, Convert.ChangeType(dataReader[property.Name], convertTo), null);
|
|
break;
|
|
}
|
|
|
|
{
|
|
/*
|
|
case "Byte":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "Char":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "DateTime":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "Decimal":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "Double":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "Guid":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "Int16":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "Int32":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "Int64":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "SByte":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "Single":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "String":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "TimeSpan":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "UInt16":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "UInt32":
|
|
{
|
|
break;
|
|
}
|
|
|
|
case "UInt64":
|
|
{
|
|
break;
|
|
}
|
|
*
|
|
*/
|
|
}
|
|
|
|
|
|
}
|
|
}
|
|
|
|
results.Add(item);
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Obtiene un objeto a partir de un SqlDataReader.
|
|
/// </summary>
|
|
/// <typeparam name="T">Clase genérica en donde se obtiene la información del SqlDataReader.</typeparam>
|
|
/// <param name="dataReader">SqlDataReader a leer.</param>
|
|
/// <returns>Objeto T.</returns>
|
|
public static T CreateObject<T>(SQLiteDataReader dataReader) where T : class, new()
|
|
{
|
|
var properties = typeof(T).GetProperties();
|
|
while (dataReader.Read())
|
|
{
|
|
var item = Activator.CreateInstance<T>();
|
|
foreach (var property in properties)
|
|
{
|
|
if (IsColumnExists(dataReader, property.Name))
|
|
{
|
|
if (!dataReader.IsDBNull(dataReader.GetOrdinal(property.Name)))
|
|
{
|
|
Type convertTo = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
|
|
property.SetValue(item, Convert.ChangeType(dataReader[property.Name], convertTo), null);
|
|
}
|
|
}
|
|
}
|
|
|
|
return item;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Valida si existe un nombre de porpiedad como campo de el IDataReader.
|
|
/// </summary>
|
|
/// <param name="dataReader">IDataReader a validar.</param>
|
|
/// <param name="columnName">Nombre de la columna.</param>
|
|
/// <returns>True = si existe, False = no existe.</returns>
|
|
private static bool IsColumnExists(SQLiteDataReader dataReader, string columnName)
|
|
{
|
|
try
|
|
{
|
|
if (dataReader.GetSchemaTable().Select($"ColumnName= '{columnName}'").Count() > 0)
|
|
{
|
|
dataReader.GetOrdinal(columnName);
|
|
return true;
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
|
|
#endregion
|
|
public void Dispose()
|
|
{
|
|
|
|
if (transaccion != null)
|
|
{
|
|
transaccion.Rollback();
|
|
transaccion.Dispose();
|
|
transaccion=null;
|
|
}
|
|
if (comando != null)
|
|
{
|
|
try { comando.Dispose(); }
|
|
catch (Exception) { }
|
|
comando = null;
|
|
}
|
|
if (conexion != null)
|
|
{
|
|
try { conexion.Close(); }
|
|
catch (Exception e)
|
|
{
|
|
Mod.GuardaLog(e, "Error al cerrar base de datos", LogsNames.LocalRepository);
|
|
}
|
|
try { conexion.Dispose(); }
|
|
catch (Exception e) { Mod.GuardaLog(e, "Error al liberar recursos de base de datos", LogsNames.LocalRepository); }
|
|
conexion = null;
|
|
}
|
|
isopened = false;
|
|
}
|
|
//static void CreateTable(SQLiteConnection conn)
|
|
//{
|
|
|
|
// SQLiteCommand sqlite_cmd;
|
|
// string Createsql = "CREATE TABLE SampleTable (Col1 VARCHAR(20), Col2 INT)";
|
|
// string Createsql1 = "CREATE TABLE SampleTable1 (Col1 VARCHAR(20), Col2 INT)";
|
|
// sqlite_cmd = conn.CreateCommand();
|
|
// sqlite_cmd.CommandText = Createsql;
|
|
// sqlite_cmd.ExecuteNonQuery();
|
|
// sqlite_cmd.CommandText = Createsql1;
|
|
// sqlite_cmd.ExecuteNonQuery();
|
|
|
|
//}
|
|
|
|
//static void InsertData(SQLiteConnection conn)
|
|
//{
|
|
// SQLiteCommand sqlite_cmd;
|
|
// sqlite_cmd = conn.CreateCommand();
|
|
// sqlite_cmd.CommandText = "INSERT INTO SampleTable (Col1, Col2) VALUES('Test Text ', 1); ";
|
|
// sqlite_cmd.ExecuteNonQuery();
|
|
// sqlite_cmd.CommandText = "INSERT INTO SampleTable (Col1, Col2) VALUES('Test1 Text1 ', 2); ";
|
|
// sqlite_cmd.ExecuteNonQuery();
|
|
// sqlite_cmd.CommandText = "INSERT INTO SampleTable (Col1, Col2) VALUES('Test2 Text2 ', 3); ";
|
|
// sqlite_cmd.ExecuteNonQuery();
|
|
|
|
|
|
// sqlite_cmd.CommandText = "INSERT INTO SampleTable1 (Col1, Col2) VALUES('Test3 Text3 ', 3); ";
|
|
// sqlite_cmd.ExecuteNonQuery();
|
|
|
|
//}
|
|
|
|
//static void ReadData(SQLiteConnection conn)
|
|
//{
|
|
// SQLiteDataReader sqlite_datareader;
|
|
// SQLiteCommand sqlite_cmd;
|
|
// sqlite_cmd = conn.CreateCommand();
|
|
// sqlite_cmd.CommandText = "SELECT * FROM SampleTable";
|
|
|
|
// sqlite_datareader = sqlite_cmd.ExecuteReader();
|
|
// while (sqlite_datareader.Read())
|
|
// {
|
|
// string myreader = sqlite_datareader.GetString(0);
|
|
// Console.WriteLine(myreader);
|
|
// }
|
|
// conn.Close();
|
|
//}
|
|
}
|
|
}
|