itadp033_kucher_inna /EH/EngineerHalp/DataSerializerHelper.cs

Language C# Lines 377
MD5 Hash d2cf86b983bbde100fd0509e78816dbd Estimated Cost $3,867 (why?)
Repository https://bitbucket.org/kinna/itadp033_kucher_inna.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// -----------------------------------------------------------------------
// <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
    }
}
Back to Top