ISEbd_21_Kuklew_M.I._Softwa.../SoftwareInstallationFileImplement/DataFileSingleton.cs

69 lines
2.4 KiB
C#
Raw Permalink Normal View History

2024-04-07 17:05:30 +04:00
using SoftwareInstallationFileImplement.Models;
using System.Xml.Linq;
namespace SoftwareInstallationFileImplement
{
2024-05-12 14:38:32 +04:00
internal class DataFileSingleton
2024-04-07 17:05:30 +04:00
{
private static DataFileSingleton? instance;
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
private readonly string ComponentFileName = "Component.xml";
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
private readonly string OrderFileName = "Order.xml";
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
private readonly string PackageFileName = "Package.xml";
2024-05-12 14:38:32 +04:00
private readonly string ShopFileName = "Shop.xml";
2024-04-07 17:05:30 +04:00
public List<Component> Components { get; private set; }
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
public List<Order> Orders { get; private set; }
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
public List<Package> Packages { get; private set; }
2024-05-12 14:38:32 +04:00
public List<Shop> Shops { get; private set; }
2024-04-07 17:05:30 +04:00
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
public void SavePackages() => SaveData(Packages, PackageFileName, "Packages", x => x.GetXElement);
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
2024-05-12 14:38:32 +04:00
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
2024-04-07 17:05:30 +04:00
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Packages = LoadData(PackageFileName, "Package", x => Package.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
2024-05-12 14:38:32 +04:00
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
2024-04-07 17:05:30 +04:00
}
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
2024-05-12 14:38:32 +04:00
return XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
2024-04-07 17:05:30 +04:00
}
return new List<T>();
}
2024-05-12 14:38:32 +04:00
2024-04-07 17:05:30 +04:00
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);
}
}
}
}