PageRenderTime 43ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Halp/EngineerHalp/DataSerializerHelper.cs

https://bitbucket.org/kinna/demo
C# | 376 lines | 156 code | 63 blank | 157 comment | 20 complexity | d2cf86b983bbde100fd0509e78816dbd MD5 | raw file
Possible License(s): BSD-3-Clause
  1. // -----------------------------------------------------------------------
  2. // <copyright file="DataSerializerHelper.cs" company="">
  3. // TODO: Update copyright text.
  4. // </copyright>
  5. // -----------------------------------------------------------------------
  6. namespace Application.Entity.Infrastructure.Helpers
  7. {
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Data.SqlTypes;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Reflection;
  14. using System.Runtime.Serialization;
  15. using System.Runtime.Serialization.Formatters.Binary;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Xml;
  19. using System.Xml.Linq;
  20. using System.Xml.Serialization;
  21. /// <summary>
  22. /// Class for data serialization
  23. /// </summary>
  24. public static class DataSerializerHelper
  25. {
  26. #region Xml serialization
  27. /// <summary>
  28. /// Serializes T type instance
  29. /// </summary>
  30. /// <typeparam name="T">Type of instance to serialize</typeparam>
  31. /// <param name="obj">Instance to serialize</param>
  32. /// <returns>Serialized object in stream</returns>
  33. /// <exception cref="ArgumentNullException">If input object equals to null</exception>
  34. public static SqlXml XmlSerialize<T>(T obj)
  35. {
  36. if (obj == null)
  37. throw new ArgumentNullException("Null object");
  38. using (Stream memory = new MemoryStream())
  39. {
  40. DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T));
  41. dataContractSerializer.WriteObject(memory, obj);
  42. memory.Flush();
  43. memory.Position = 0;
  44. return new SqlXml(XmlReader.Create(memory));
  45. }
  46. }
  47. /// <summary>
  48. /// Deserializes T type instance
  49. /// </summary>
  50. /// <typeparam name="T">Type of instance to deserialize</typeparam>
  51. /// <param name="reader">SqlXml object (data source)</param>
  52. /// <returns>Decerialized T type instance</returns>
  53. /// <exception cref="ArgumentNullException">If input object equals to null</exception>
  54. public static T XmlDeserialize<T>(SqlXml reader)
  55. {
  56. if (reader == null || reader.IsNull)
  57. throw new ArgumentNullException("Null or Nullable Stream");
  58. if (reader.Value.Length < 1)
  59. return default(T);
  60. DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T));
  61. return (T)dataContractSerializer.ReadObject(reader.CreateReader());
  62. }
  63. #endregion
  64. ///// <summary>
  65. ///// Writes collection to end of the Xml file
  66. ///// </summary>
  67. ///// <typeparam name="T">Type</typeparam>
  68. ///// <param name="newRecords">Collection to write</param>
  69. //public static void AddCollection<T>(IEnumerable<T> newRecords)
  70. //{
  71. // if (newRecords == null)
  72. // {
  73. // throw new ArgumentNullException("new Records is null");
  74. // }
  75. // XDocument doc = new XDocument();
  76. // using (var writer = doc.CreateWriter())
  77. // {
  78. // List<T> lst = LoadCollection<T>().ToList();
  79. // lst.AddRange(newRecords);
  80. // var serializer = new DataContractSerializer(lst.GetType());
  81. // serializer.WriteObject(writer, lst);
  82. // }
  83. // string filePath = GetFilePath<T>();
  84. // doc.Save(filePath);
  85. //}
  86. ///// <summary>
  87. ///// Writes domain to XML
  88. ///// </summary>
  89. ///// <typeparam name="T"></typeparam>
  90. ///// <param name="newRecord"></param>
  91. //public static void AddDomain<T>(T newRecord)
  92. //{
  93. // if (newRecord == null)
  94. // {
  95. // throw new ArgumentNullException("new Records is null");
  96. // }
  97. // XDocument doc = new XDocument();
  98. // using (var writer = doc.CreateWriter())
  99. // {
  100. // List<T> lst = LoadCollection<T>().ToList();
  101. // lst.Add(newRecord);
  102. // var serializer = new DataContractSerializer(lst.GetType());
  103. // serializer.WriteObject(writer, lst);
  104. // }
  105. // string filePath = GetFilePath<T>();
  106. // doc.Save(filePath);
  107. //}
  108. /// <summary>
  109. /// Rewrites XML file with new collection
  110. /// </summary>
  111. /// <typeparam name="T">Domain</typeparam>
  112. /// <param name="newRecords">Collection for recording</param>
  113. public static void ReWriteCollection<T>(IEnumerable<T> newRecords)
  114. {
  115. if (newRecords == null)
  116. {
  117. throw new ArgumentNullException("newRecords is null");
  118. }
  119. XDocument doc = new XDocument();
  120. using (var writer = doc.CreateWriter())
  121. {
  122. List<T> lst = new List<T>();
  123. lst.AddRange(newRecords);
  124. var serializer = new DataContractSerializer(lst.GetType());
  125. serializer.WriteObject(writer, lst);
  126. }
  127. string filePath = @"D:\\test.xml";
  128. doc.Save(filePath);
  129. //string filePath = GetFilePath<T>();
  130. //doc.Save(filePath);
  131. }
  132. ///// <summary>
  133. ///// Reads collection from Xml storage
  134. ///// </summary>
  135. ///// <typeparam name="T">Type</typeparam>
  136. ///// <returns>Collection from file</returns>
  137. public static IEnumerable<T> LoadCollection<T>( string filePath)
  138. {
  139. var ds = new DataContractSerializer(typeof(T[]));
  140. T[] arr = new T[] { };
  141. //string filePath = GetFilePath<T>();
  142. using (var r = XmlReader.Create(filePath))
  143. {
  144. arr = ds.ReadObject(r) as T[];
  145. }
  146. List<int> das = new List<int>();
  147. return arr;
  148. }
  149. ///// <summary>
  150. ///// Replaces older domain by the new one
  151. ///// </summary>
  152. ///// <typeparam name="T">domain type</typeparam>
  153. ///// <param name="newDomain">Domain</param>
  154. //public static void UpdateDomain<T>(T newDomain, object id) where T : IStorageEntity
  155. //{
  156. // List<T> list = LoadCollection<T>().ToList();
  157. // var q = (from l in list
  158. // where l.EqualsKey(id)
  159. // select l).FirstOrDefault();
  160. // list[list.IndexOf(q)] = newDomain;
  161. // ReWriteCollection<T>(list);
  162. //}
  163. public static void XmlWrite<T>(T obj, string path)
  164. {
  165. //string path = GetFilePath<T>();
  166. if (!Path.HasExtension(path))
  167. throw new ArgumentException("Invalid file name");
  168. if (obj == null)
  169. throw new ArgumentNullException("Null object");
  170. DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T[]));
  171. XmlWriterSettings settings = new XmlWriterSettings();
  172. settings.Indent = true;
  173. using (XmlWriter writer = XmlWriter.Create(path, settings))
  174. {
  175. dataContractSerializer.WriteObject(writer, new T[] { obj });
  176. }
  177. }
  178. ///// <summary>
  179. ///// Remove domain of selected type
  180. ///// </summary>
  181. ///// <typeparam name="T">Domain type</typeparam>
  182. ///// <param name="newDomain">Domain</param>
  183. //public static void RemoveDomain<T>(object id) where T : IStorageEntity
  184. //{
  185. // List<T> list = LoadCollection<T>().ToList();
  186. // if (list.IndexOf(GetElementFrom(list, id)) != -1)
  187. // {
  188. // list.Remove(GetElementFrom(list, id));
  189. // }
  190. // ReWriteCollection(list);
  191. //}
  192. //public static T GetDomain<T>(object id) where T : IStorageEntity
  193. //{
  194. // return GetElementFrom(LoadCollection<T>().ToList(), id);
  195. //}
  196. //private static T GetElementFrom<T>(IEnumerable<T> list, object id) where T : IStorageEntity
  197. //{
  198. // T q = (from l in list
  199. // where l.EqualsKey(id)
  200. // select l).FirstOrDefault();
  201. // return q;
  202. //}
  203. //private static string GetFilePath<T>()
  204. //{
  205. // string filePath = @"E:\Bakery\Project\Solution\Testing\Models.Test\AppData\xml-models\en-US\Valid\ProccessManager.xml";//PathResolver.ResolvePath(typeof(T).Name);
  206. // if (!File.Exists(Path.GetFullPath(filePath)))
  207. // filePath = PathResolver.ResolvePath(typeof(T).Name);
  208. // if (!File.Exists(Path.GetFullPath(filePath)))
  209. // throw new ArgumentException("File doesn't exist");
  210. // return filePath;
  211. //}
  212. #region All Binary
  213. /// <summary>
  214. /// Serializes T type instance
  215. /// </summary>
  216. /// <typeparam name="T">Type of instance to serialize</typeparam>
  217. /// <param name="value">Instance to serialize</param>
  218. /// <returns>SqlBytes object</returns>
  219. /// <exception cref="ArgumentNullException">If input object equals to null</exception>
  220. public static SqlBytes BinarySerialize<T>(T value)
  221. {
  222. if (value == null)
  223. throw new ArgumentNullException("Null object");
  224. using (Stream memory = new MemoryStream())
  225. {
  226. BinaryFormatter bf = new BinaryFormatter();
  227. bf.Serialize(memory, value);
  228. memory.Flush();
  229. memory.Position = 0;
  230. return new SqlBytes(memory);
  231. }
  232. }
  233. /// <summary>
  234. /// Deserializes T type instance
  235. /// </summary>
  236. /// <typeparam name="T">Type of instance to deserialize</typeparam>
  237. /// <param name="value">SqlBytes object (data source)</param>
  238. /// <returns>Decerialized T type instance</returns>
  239. /// <exception cref="ArgumentNullException">If input object equals to null</exception>
  240. public static T BinaryDeserialize<T>(SqlBytes value)
  241. {
  242. /// Check the argument value
  243. if (value == null || value.IsNull)
  244. throw new ArgumentNullException("Null or Nullable Stream");
  245. if (value.Length < 1)
  246. return default(T);
  247. using (MemoryStream memory = new MemoryStream())
  248. {
  249. BinaryFormatter bf = new BinaryFormatter();
  250. return (T)bf.Deserialize(memory);
  251. }
  252. }
  253. /// <summary>
  254. /// Reads object from binare formated file
  255. /// </summary>
  256. /// <typeparam name="T">Object type</typeparam>
  257. /// <param name="path">File path</param>
  258. /// <returns>Object value</returns>
  259. /// <exception cref="IOException">If file doesn't exist</exception>
  260. public static T BinaryRead<T>(string path)
  261. {
  262. if (!File.Exists(path))
  263. throw new IOException("File doesn't exist");
  264. using (StreamReader reader = new StreamReader(path))
  265. {
  266. return BinaryDeserialize<T>(new SqlBytes(new MemoryStream(Encoding.UTF8.GetBytes(reader.ReadToEnd()))));
  267. }
  268. }
  269. /// <summary>
  270. /// Writes serialized binary object into file
  271. /// </summary>
  272. /// <typeparam name="T">Object type</typeparam>
  273. /// <param name="obj">Object value</param>
  274. /// <param name="path">File path</param>
  275. /// <exception cref="ArgumentException">If input file name is invalid</exception>
  276. public static void BinaryWrite<T>(T obj, string path)
  277. {
  278. if (!Directory.Exists(Path.GetDirectoryName(path)))
  279. throw new ArgumentException("Directory doesn't exist");
  280. if (!Path.HasExtension(path))
  281. throw new ArgumentException("Invalid file name");
  282. SqlBytes sertilizedObject = BinarySerialize(obj);
  283. using (StreamWriter writer = new StreamWriter(path))
  284. {
  285. writer.Write(sertilizedObject.Buffer);
  286. }
  287. }
  288. #endregion
  289. #region Serialization to and from XDocument
  290. public static XDocument ToXmlDocument<EntityType>(object itemEntity)
  291. {
  292. XDocument doc = new XDocument();
  293. using (var writer = doc.CreateWriter())
  294. {
  295. var serializer = new DataContractSerializer(itemEntity.GetType());
  296. serializer.WriteObject(writer, itemEntity);
  297. }
  298. return doc;
  299. }
  300. public static EntityType FromXmlDocument<EntityType>(XDocument xmlDoc)
  301. {
  302. EntityType itemEntity;
  303. using (var reader = xmlDoc.CreateReader())
  304. {
  305. var serializer = new DataContractSerializer(typeof(EntityType));
  306. var item = serializer.ReadObject(reader);
  307. itemEntity = (EntityType)item;
  308. }
  309. return itemEntity;
  310. }
  311. #endregion
  312. }
  313. }