60 lines
2.1 KiB
C#
60 lines
2.1 KiB
C#
|
using AutoWorkshopFileImplement.Models;
|
|||
|
using System.Xml.Linq;
|
|||
|
|
|||
|
namespace AutoWorkshopFileImplement
|
|||
|
{
|
|||
|
public class DataFileSingleton
|
|||
|
{
|
|||
|
private static DataFileSingleton? _instance;
|
|||
|
|
|||
|
private readonly string ComponentFileName = "Component.xml";
|
|||
|
private readonly string OrderFileName = "Order.xml";
|
|||
|
private readonly string RepairFileName = "Repair.xml";
|
|||
|
|
|||
|
public List<Component> Components { get; private set; }
|
|||
|
|
|||
|
public List<Order> Orders { get; private set; }
|
|||
|
|
|||
|
public List<Repair> Repairs { get; private set; }
|
|||
|
|
|||
|
private DataFileSingleton()
|
|||
|
{
|
|||
|
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
|
|||
|
Repairs = LoadData(RepairFileName, "Repair", x => Repair.Create(x)!)!;
|
|||
|
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
|
|||
|
}
|
|||
|
|
|||
|
public static DataFileSingleton GetInstance()
|
|||
|
{
|
|||
|
if (_instance == null)
|
|||
|
{
|
|||
|
_instance = new DataFileSingleton();
|
|||
|
}
|
|||
|
|
|||
|
return _instance;
|
|||
|
}
|
|||
|
|
|||
|
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
|
|||
|
public void SaveRepairs() => SaveData(Repairs, RepairFileName, "Repairs", x => x.GetXElement);
|
|||
|
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
|
|||
|
|
|||
|
private static List<T>? LoadData<T>(string FileName, string XmlNodeName, Func<XElement, T> SelectFunction)
|
|||
|
{
|
|||
|
if (File.Exists(FileName))
|
|||
|
{
|
|||
|
return XDocument.Load(FileName)?.Root?.Elements(XmlNodeName)?.Select(SelectFunction)?.ToList();
|
|||
|
}
|
|||
|
|
|||
|
return new List<T>();
|
|||
|
}
|
|||
|
|
|||
|
private static void SaveData<T>(List<T> Data, string FileName, string XmlNodeName, Func<T, XElement> SelectFunction)
|
|||
|
{
|
|||
|
if (Data != null)
|
|||
|
{
|
|||
|
new XDocument(new XElement(XmlNodeName, Data.Select(SelectFunction).ToArray())).Save(FileName);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|