/EH/EngineerHalp/DataSerializerHelper.cs
C# | 376 lines | 156 code | 63 blank | 157 comment | 20 complexity | d2cf86b983bbde100fd0509e78816dbd MD5 | raw file
Possible License(s): BSD-3-Clause
- // -----------------------------------------------------------------------
- // <copyright file="DataSerializerHelper.cs" company="">
- // TODO: Update copyright text.
- // </copyright>
- // -----------------------------------------------------------------------
- namespace Application.Entity.Infrastructure.Helpers
- {
- using System;
- using System.Collections.Generic;
- using System.Data.SqlTypes;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Text;
- using System.Threading;
- using System.Xml;
- using System.Xml.Linq;
- using System.Xml.Serialization;
- /// <summary>
- /// Class for data serialization
- /// </summary>
- public static class DataSerializerHelper
- {
- #region Xml serialization
- /// <summary>
- /// Serializes T type instance
- /// </summary>
- /// <typeparam name="T">Type of instance to serialize</typeparam>
- /// <param name="obj">Instance to serialize</param>
- /// <returns>Serialized object in stream</returns>
- /// <exception cref="ArgumentNullException">If input object equals to null</exception>
- public static SqlXml XmlSerialize<T>(T obj)
- {
- if (obj == null)
- throw new ArgumentNullException("Null object");
- using (Stream memory = new MemoryStream())
- {
- DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T));
- dataContractSerializer.WriteObject(memory, obj);
- memory.Flush();
- memory.Position = 0;
- return new SqlXml(XmlReader.Create(memory));
- }
- }
- /// <summary>
- /// Deserializes T type instance
- /// </summary>
- /// <typeparam name="T">Type of instance to deserialize</typeparam>
- /// <param name="reader">SqlXml object (data source)</param>
- /// <returns>Decerialized T type instance</returns>
- /// <exception cref="ArgumentNullException">If input object equals to null</exception>
- public static T XmlDeserialize<T>(SqlXml reader)
- {
- if (reader == null || reader.IsNull)
- throw new ArgumentNullException("Null or Nullable Stream");
- if (reader.Value.Length < 1)
- return default(T);
- DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T));
- return (T)dataContractSerializer.ReadObject(reader.CreateReader());
- }
- #endregion
- ///// <summary>
- ///// Writes collection to end of the Xml file
- ///// </summary>
- ///// <typeparam name="T">Type</typeparam>
- ///// <param name="newRecords">Collection to write</param>
- //public static void AddCollection<T>(IEnumerable<T> newRecords)
- //{
- // if (newRecords == null)
- // {
- // throw new ArgumentNullException("new Records is null");
- // }
- // XDocument doc = new XDocument();
- // using (var writer = doc.CreateWriter())
- // {
- // List<T> lst = LoadCollection<T>().ToList();
- // lst.AddRange(newRecords);
- // var serializer = new DataContractSerializer(lst.GetType());
- // serializer.WriteObject(writer, lst);
- // }
- // string filePath = GetFilePath<T>();
- // doc.Save(filePath);
- //}
- ///// <summary>
- ///// Writes domain to XML
- ///// </summary>
- ///// <typeparam name="T"></typeparam>
- ///// <param name="newRecord"></param>
- //public static void AddDomain<T>(T newRecord)
- //{
- // if (newRecord == null)
- // {
- // throw new ArgumentNullException("new Records is null");
- // }
- // XDocument doc = new XDocument();
- // using (var writer = doc.CreateWriter())
- // {
- // List<T> lst = LoadCollection<T>().ToList();
- // lst.Add(newRecord);
- // var serializer = new DataContractSerializer(lst.GetType());
- // serializer.WriteObject(writer, lst);
- // }
- // string filePath = GetFilePath<T>();
- // doc.Save(filePath);
- //}
- /// <summary>
- /// Rewrites XML file with new collection
- /// </summary>
- /// <typeparam name="T">Domain</typeparam>
- /// <param name="newRecords">Collection for recording</param>
- public static void ReWriteCollection<T>(IEnumerable<T> newRecords)
- {
- if (newRecords == null)
- {
- throw new ArgumentNullException("newRecords is null");
- }
- XDocument doc = new XDocument();
- using (var writer = doc.CreateWriter())
- {
- List<T> lst = new List<T>();
- lst.AddRange(newRecords);
- var serializer = new DataContractSerializer(lst.GetType());
- serializer.WriteObject(writer, lst);
- }
- string filePath = @"D:\\test.xml";
- doc.Save(filePath);
- //string filePath = GetFilePath<T>();
- //doc.Save(filePath);
- }
- ///// <summary>
- ///// Reads collection from Xml storage
- ///// </summary>
- ///// <typeparam name="T">Type</typeparam>
- ///// <returns>Collection from file</returns>
- public static IEnumerable<T> LoadCollection<T>( string filePath)
- {
- var ds = new DataContractSerializer(typeof(T[]));
- T[] arr = new T[] { };
- //string filePath = GetFilePath<T>();
- using (var r = XmlReader.Create(filePath))
- {
- arr = ds.ReadObject(r) as T[];
- }
- List<int> das = new List<int>();
- return arr;
- }
- ///// <summary>
- ///// Replaces older domain by the new one
- ///// </summary>
- ///// <typeparam name="T">domain type</typeparam>
- ///// <param name="newDomain">Domain</param>
- //public static void UpdateDomain<T>(T newDomain, object id) where T : IStorageEntity
- //{
- // List<T> list = LoadCollection<T>().ToList();
- // var q = (from l in list
- // where l.EqualsKey(id)
- // select l).FirstOrDefault();
- // list[list.IndexOf(q)] = newDomain;
- // ReWriteCollection<T>(list);
- //}
- public static void XmlWrite<T>(T obj, string path)
- {
- //string path = GetFilePath<T>();
- if (!Path.HasExtension(path))
- throw new ArgumentException("Invalid file name");
- if (obj == null)
- throw new ArgumentNullException("Null object");
- DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T[]));
- XmlWriterSettings settings = new XmlWriterSettings();
- settings.Indent = true;
- using (XmlWriter writer = XmlWriter.Create(path, settings))
- {
- dataContractSerializer.WriteObject(writer, new T[] { obj });
- }
- }
- ///// <summary>
- ///// Remove domain of selected type
- ///// </summary>
- ///// <typeparam name="T">Domain type</typeparam>
- ///// <param name="newDomain">Domain</param>
- //public static void RemoveDomain<T>(object id) where T : IStorageEntity
- //{
- // List<T> list = LoadCollection<T>().ToList();
- // if (list.IndexOf(GetElementFrom(list, id)) != -1)
- // {
- // list.Remove(GetElementFrom(list, id));
- // }
- // ReWriteCollection(list);
- //}
- //public static T GetDomain<T>(object id) where T : IStorageEntity
- //{
- // return GetElementFrom(LoadCollection<T>().ToList(), id);
- //}
- //private static T GetElementFrom<T>(IEnumerable<T> list, object id) where T : IStorageEntity
- //{
- // T q = (from l in list
- // where l.EqualsKey(id)
- // select l).FirstOrDefault();
- // return q;
- //}
- //private static string GetFilePath<T>()
- //{
- // string filePath = @"E:\Bakery\Project\Solution\Testing\Models.Test\AppData\xml-models\en-US\Valid\ProccessManager.xml";//PathResolver.ResolvePath(typeof(T).Name);
-
- // if (!File.Exists(Path.GetFullPath(filePath)))
- // filePath = PathResolver.ResolvePath(typeof(T).Name);
- // if (!File.Exists(Path.GetFullPath(filePath)))
- // throw new ArgumentException("File doesn't exist");
- // return filePath;
- //}
- #region All Binary
- /// <summary>
- /// Serializes T type instance
- /// </summary>
- /// <typeparam name="T">Type of instance to serialize</typeparam>
- /// <param name="value">Instance to serialize</param>
- /// <returns>SqlBytes object</returns>
- /// <exception cref="ArgumentNullException">If input object equals to null</exception>
- public static SqlBytes BinarySerialize<T>(T value)
- {
- if (value == null)
- throw new ArgumentNullException("Null object");
- using (Stream memory = new MemoryStream())
- {
- BinaryFormatter bf = new BinaryFormatter();
- bf.Serialize(memory, value);
- memory.Flush();
- memory.Position = 0;
- return new SqlBytes(memory);
- }
- }
- /// <summary>
- /// Deserializes T type instance
- /// </summary>
- /// <typeparam name="T">Type of instance to deserialize</typeparam>
- /// <param name="value">SqlBytes object (data source)</param>
- /// <returns>Decerialized T type instance</returns>
- /// <exception cref="ArgumentNullException">If input object equals to null</exception>
- public static T BinaryDeserialize<T>(SqlBytes value)
- {
- /// Check the argument value
- if (value == null || value.IsNull)
- throw new ArgumentNullException("Null or Nullable Stream");
- if (value.Length < 1)
- return default(T);
- using (MemoryStream memory = new MemoryStream())
- {
- BinaryFormatter bf = new BinaryFormatter();
- return (T)bf.Deserialize(memory);
- }
- }
- /// <summary>
- /// Reads object from binare formated file
- /// </summary>
- /// <typeparam name="T">Object type</typeparam>
- /// <param name="path">File path</param>
- /// <returns>Object value</returns>
- /// <exception cref="IOException">If file doesn't exist</exception>
- public static T BinaryRead<T>(string path)
- {
- if (!File.Exists(path))
- throw new IOException("File doesn't exist");
- using (StreamReader reader = new StreamReader(path))
- {
- return BinaryDeserialize<T>(new SqlBytes(new MemoryStream(Encoding.UTF8.GetBytes(reader.ReadToEnd()))));
- }
- }
- /// <summary>
- /// Writes serialized binary object into file
- /// </summary>
- /// <typeparam name="T">Object type</typeparam>
- /// <param name="obj">Object value</param>
- /// <param name="path">File path</param>
- /// <exception cref="ArgumentException">If input file name is invalid</exception>
- public static void BinaryWrite<T>(T obj, string path)
- {
- if (!Directory.Exists(Path.GetDirectoryName(path)))
- throw new ArgumentException("Directory doesn't exist");
- if (!Path.HasExtension(path))
- throw new ArgumentException("Invalid file name");
- SqlBytes sertilizedObject = BinarySerialize(obj);
- using (StreamWriter writer = new StreamWriter(path))
- {
- writer.Write(sertilizedObject.Buffer);
- }
- }
- #endregion
- #region Serialization to and from XDocument
-
- public static XDocument ToXmlDocument<EntityType>(object itemEntity)
- {
- XDocument doc = new XDocument();
- using (var writer = doc.CreateWriter())
- {
- var serializer = new DataContractSerializer(itemEntity.GetType());
- serializer.WriteObject(writer, itemEntity);
- }
- return doc;
- }
- public static EntityType FromXmlDocument<EntityType>(XDocument xmlDoc)
- {
- EntityType itemEntity;
- using (var reader = xmlDoc.CreateReader())
- {
- var serializer = new DataContractSerializer(typeof(EntityType));
- var item = serializer.ReadObject(reader);
- itemEntity = (EntityType)item;
- }
- return itemEntity;
- }
- #endregion
- }
- }