|
|
|
@ -0,0 +1,63 @@
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Diagnostics;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Runtime.Serialization;
|
|
|
|
|
using System.Xml;
|
|
|
|
|
using System.Xml.Serialization;
|
|
|
|
|
using Models.Game;
|
|
|
|
|
using Models.Interfaces;
|
|
|
|
|
|
|
|
|
|
namespace DataContractPersistence
|
|
|
|
|
{
|
|
|
|
|
public class DataContractXml : IPersistence
|
|
|
|
|
{
|
|
|
|
|
public string FileName { get; set; } = "data.xml";
|
|
|
|
|
public string FilePath { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
|
|
|
|
|
|
|
|
|
|
public (List<Player>, List<Game>, List<Map>, List<BestScore>) LoadData()
|
|
|
|
|
{
|
|
|
|
|
var serializer = new DataContractSerializer(typeof(DataToPersist));
|
|
|
|
|
DataToPersist? data = new DataToPersist();
|
|
|
|
|
|
|
|
|
|
using (Stream s = File.OpenRead(Path.Combine(FilePath, FileName)))
|
|
|
|
|
{
|
|
|
|
|
data = serializer.ReadObject(s) as DataToPersist;
|
|
|
|
|
}
|
|
|
|
|
Console.WriteLine("Data loaded: " + Path.Combine(FilePath, FileName));
|
|
|
|
|
return (data.Players, data.Games, data.Maps, data.BestScores);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void SaveData(List<Player> players, List<Game> games, List<Map> maps, List<BestScore> bestScores)
|
|
|
|
|
{
|
|
|
|
|
if(!Directory.Exists(FilePath))
|
|
|
|
|
{
|
|
|
|
|
Debug.WriteLine("Directory created");
|
|
|
|
|
Debug.WriteLine(Directory.GetDirectoryRoot(FilePath));
|
|
|
|
|
Debug.WriteLine(FilePath);
|
|
|
|
|
Directory.CreateDirectory(FilePath);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var serializer = new DataContractSerializer(typeof(DataToPersist));
|
|
|
|
|
DataToPersist? data = new DataToPersist();
|
|
|
|
|
|
|
|
|
|
data.Players = players;
|
|
|
|
|
data.Games = games;
|
|
|
|
|
data.Maps = maps;
|
|
|
|
|
data.BestScores = bestScores;
|
|
|
|
|
|
|
|
|
|
var settings = new XmlWriterSettings() { Indent = true };
|
|
|
|
|
using (TextWriter tw = File.CreateText(Path.Combine(FilePath, FileName)))
|
|
|
|
|
{
|
|
|
|
|
using (XmlWriter writer = XmlWriter.Create(tw, settings))
|
|
|
|
|
{
|
|
|
|
|
serializer.WriteObject(writer, data);
|
|
|
|
|
Console.WriteLine("Data saved: " + Path.Combine(FilePath, FileName));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|