ROIEditor/ListaPersistente.cs

129 lines
3.5 KiB
C#
Raw Normal View History

2024-04-15 08:38:56 -03:00
using System.Text.Json;
2024-04-12 18:06:46 -03:00
using Microsoft.Data.Sqlite;
namespace ROIEditor
{
2024-04-14 04:47:56 -03:00
public class ListaPersistente<T>
2024-04-12 18:06:46 -03:00
{
private readonly string connectionString;
private readonly string tableName;
private List<T> data = new();
2024-04-12 19:55:02 -03:00
public string Clave;
2024-04-12 18:06:46 -03:00
public void Add(T item)
{
data.Add(item);
}
2024-04-12 19:55:02 -03:00
public void Remove(T item)
{
data.Remove(item);
}
2024-04-12 18:06:46 -03:00
public void Clear()
{
data.Clear();
}
public List<T> GetList()
{
return data;
}
public int IndexOf(T item)
{
return data.IndexOf(item);
}
public int Count => data.Count;
2024-04-14 04:47:56 -03:00
public ListaPersistente(string dbPath, string tableName)
2024-04-12 18:06:46 -03:00
{
connectionString = $"Data Source={dbPath}";
this.tableName = tableName;
InitializeDatabase();
}
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,
SerializeData TEXT
)";
command.ExecuteNonQuery();
}
}
2024-04-12 19:55:02 -03:00
public void Save()
{
Save(Clave);
}
public void Save(string clave)
2024-04-12 18:06:46 -03:00
{
2024-04-12 19:55:02 -03:00
if (clave == null) return;
Clave = clave;
2024-04-12 18:06:46 -03:00
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var deleteCommand = connection.CreateCommand();
deleteCommand.CommandText = $"DELETE FROM {tableName} WHERE Clave = $Clave";
deleteCommand.Parameters.AddWithValue("$Clave", clave);
deleteCommand.ExecuteNonQuery();
foreach (var elemento in data)
{
string serializedData = JsonSerializer.Serialize(elemento);
var command = connection.CreateCommand();
command.CommandText = $"INSERT INTO {tableName} (Clave, SerializeData) VALUES ($Clave, $SerializedData)";
command.Parameters.AddWithValue("$Clave", clave);
command.Parameters.AddWithValue("$SerializedData", serializedData);
command.ExecuteNonQuery();
}
}
}
2024-04-12 19:55:02 -03:00
public void Load() { Load(Clave); }
public void Load(string clave)
2024-04-12 18:06:46 -03:00
{
data.Clear();
2024-04-12 19:55:02 -03:00
if (clave == null) return;
Clave = clave;
2024-04-12 18:06:46 -03:00
using (var connection = new SqliteConnection(connectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $"SELECT SerializeData FROM {tableName} WHERE Clave = $Clave";
command.Parameters.AddWithValue("$Clave", clave);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string serializedData = reader.GetString(0);
data.Add( JsonSerializer.Deserialize<T>(serializedData) );
}
}
}
}
}
2024-04-15 08:38:56 -03:00
2024-04-12 18:06:46 -03:00
}