using System; using System.IO; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace Configuration { public static class Serialization { #region Private Delegates, Events, Enums, Properties, Indexers and Fields private static XmlSerializer ConfigurationSerializer { get; } = new XmlSerializer(typeof(Settings)); private static XmlReaderSettings XmlReaderSettings { get; } = new XmlReaderSettings { Async = true, ValidationType = ValidationType.Schema, IgnoreWhitespace = true, ValidationFlags = XmlSchemaValidationFlags .ProcessInlineSchema | XmlSchemaValidationFlags .ProcessSchemaLocation | XmlSchemaValidationFlags .ReportValidationWarnings, DtdProcessing = DtdProcessing.Parse }; private static XmlWriterSettings XmlWriterSettings { get; } = new XmlWriterSettings { Async = true, Indent = true, IndentChars = " ", OmitXmlDeclaration = false }; #endregion #region Public Methods public static async Task Serialize(this Settings settings, string file) { try { using (var streamWriter = new StreamWriter(file)) { using (var xmlWriter = XmlWriter.Create(streamWriter, XmlWriterSettings)) { await xmlWriter.WriteDocTypeAsync("Configuration", null, null, ""); ConfigurationSerializer.Serialize(xmlWriter, settings); } } return new SerializationSuccess(); } catch (Exception ex) { return new SerializationFailure {Exception = ex}; } } public static SerializationState Deserialize(string file) { try { Settings configuration; using (var streamReader = new StreamReader(file)) { using (var xmlReader = XmlReader.Create(streamReader, XmlReaderSettings)) { configuration = (Settings) ConfigurationSerializer.Deserialize(xmlReader); } } return new SerializationSuccess { Result = configuration }; } catch (Exception ex) { return new SerializationFailure { Exception = ex }; } } #endregion } }