99 lines
3.1 KiB
C#
99 lines
3.1 KiB
C#
using System.Text.Json;
|
|
using Microsoft.Data.Sqlite;
|
|
|
|
namespace ROIEditor
|
|
{
|
|
public class ItemPersistente<T> where T : new()
|
|
{
|
|
private readonly string connectionString;
|
|
private readonly string tableName;
|
|
private T data; // Ahora 'data' es un objeto de tipo T
|
|
public string Clave;
|
|
|
|
public ItemPersistente(string dbPath, string tableName)
|
|
{
|
|
connectionString = $"Data Source={dbPath}";
|
|
this.tableName = tableName;
|
|
InitializeDatabase();
|
|
data = new T(); // Inicializa 'data' con el constructor por defecto de T
|
|
}
|
|
|
|
private void InitializeDatabase()
|
|
{
|
|
using (var connection = new SqliteConnection(connectionString))
|
|
{
|
|
connection.Open();
|
|
var command = connection.CreateCommand();
|
|
command.CommandText = $@"
|
|
CREATE TABLE IF NOT EXISTS {tableName} (
|
|
Id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
Clave TEXT UNIQUE,
|
|
SerializedData TEXT
|
|
)";
|
|
command.ExecuteNonQuery();
|
|
}
|
|
}
|
|
|
|
public void Save() { Save(Clave); }
|
|
|
|
public void Save(string clave)
|
|
{
|
|
if (clave == null) return;
|
|
Clave = clave;
|
|
|
|
string serializedData = JsonSerializer.Serialize(data);
|
|
using (var connection = new SqliteConnection(connectionString))
|
|
{
|
|
connection.Open();
|
|
var command = connection.CreateCommand();
|
|
command.CommandText = $@"
|
|
INSERT INTO {tableName} (Clave, SerializedData)
|
|
VALUES ($Clave, $SerializedData)
|
|
ON CONFLICT(Clave) DO UPDATE SET
|
|
SerializedData = excluded.SerializedData";
|
|
command.Parameters.AddWithValue("$Clave", clave);
|
|
command.Parameters.AddWithValue("$SerializedData", serializedData);
|
|
command.ExecuteNonQuery();
|
|
}
|
|
}
|
|
|
|
public bool Load() { return Load(Clave); }
|
|
|
|
public bool Load(string clave)
|
|
{
|
|
if (clave == null) return false;
|
|
Clave = clave;
|
|
|
|
using (var connection = new SqliteConnection(connectionString))
|
|
{
|
|
connection.Open();
|
|
var command = connection.CreateCommand();
|
|
command.CommandText = $"SELECT SerializedData FROM {tableName} WHERE Clave = $Clave";
|
|
command.Parameters.AddWithValue("$Clave", clave);
|
|
using (var reader = command.ExecuteReader())
|
|
{
|
|
if (reader.Read())
|
|
{
|
|
string serializedData = reader.GetString(0);
|
|
data = JsonSerializer.Deserialize<T>(serializedData);
|
|
return true;
|
|
}
|
|
data = new();
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
public T Get()
|
|
{
|
|
return data;
|
|
}
|
|
|
|
public void Set(T newData)
|
|
{
|
|
data = newData;
|
|
}
|
|
}
|
|
|
|
}
|