using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml.Serialization; namespace RecrownedAthenaeum.Persistence { /// /// Manages a bundle of preferences. /// public class PreferencesManager { private readonly Dictionary preferenceList; string savePath; XmlSerializer xmlSerializer; /// /// Constructs the preference manager. /// /// The path of the directory in which the preferences should be saved. /// The preferences to be serialized and unserialized in XML format. public PreferencesManager(string savePath, params object[] preferences) { this.savePath = savePath; Directory.CreateDirectory(savePath); preferenceList = new Dictionary(); Debug.WriteLine("Preference manager setting up..."); Type[] preferenceTypes = new Type[preferences.Length]; for (int prefID = 0; prefID < preferences.Length; prefID++) { preferenceList.Add(preferences[prefID].GetType(), preferences[prefID]); preferenceTypes[prefID] = preferences[prefID].GetType(); Debug.WriteLine(preferences[prefID] + " added to list of preferences"); } xmlSerializer = new XmlSerializer(typeof(object), preferenceTypes); } /// /// Returns the preference by type. /// /// The preference needed. /// The preference needed. public T GetPreferences() { return (T)preferenceList[typeof(T)]; } /// /// Loads preferences. /// public void Load() { List keys = new List(preferenceList.Keys); foreach (Type key in keys) { if (!LoadSpecific(key)) { SaveSpecific(key); } } } /// /// Saves preferences. /// public void Save() { foreach (KeyValuePair prefs in preferenceList) { SaveSpecific(prefs.Key); } } private bool LoadSpecific(Type preference) { string path = savePath + "/" + preference.Name + ".xml"; try { if (File.Exists(path)) { Stream stream = new FileStream(path, FileMode.Open); preferenceList[preference] = xmlSerializer.Deserialize(stream); stream.Close(); return true; } } catch (InvalidOperationException) { return false; } return false; } private void SaveSpecific(Type preference) { Stream stream = new FileStream(savePath + "/" + preference.Name + ".xml", FileMode.Create); xmlSerializer.Serialize(stream, preferenceList[preference]); stream.Close(); } } }