using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace E
{
[Serializable]
public struct ST_Log
{
public int ProjectId;
public int ChannelNumber;
public int Value;
public DateTime CreationTime;
public bool Delete;
public bool Invalid;
}
internal static class SerUtil<T>
{
public static byte[] Object2ByteArray(T o)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, o);
return ms.ToArray();
}
public static string Object2String(T o)
{
return Convert.ToBase64String(Object2ByteArray(o));
}
public static T ByteArray2Object(byte[] b)
{
MemoryStream ms = new MemoryStream(b);
BinaryFormatter bf = new BinaryFormatter();
ms.Position = 0;
return (T)bf.Deserialize(ms);
}
public static T String2Object(string s)
{
return ByteArray2Object(Convert.FromBase64String(s));
}
}
public class Program
{
// this does not compile
/*
public static byte[] Proposed<T>(List<T> data)
{
return data.SelectMany(s => Encoding.UTF8.GetBytes(s)).ToArray();
}
*/
public static byte[] ProposedModified<T>(List<T> data)
{
return data.SelectMany(elm => Encoding.UTF8.GetBytes(elm.ToString())).ToArray();
}
public static byte[] PlainBinarySerialization<T>(List<T> data)
{
return SerUtil<List<T>>.Object2ByteArray(data);
}
public static byte[] CompressingBinarySerialization<T>(List<T> data)
{
MemoryStream ms = new MemoryStream();
GZipStream cmp = new GZipStream(ms, CompressionMode.Compress);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(cmp, data);
cmp.Close();
return ms.ToArray();
}
public static void Test<T>(List<T> data, Func<List<T>, byte[]> f, string lbl)
{
byte[] b = f(data);
Console.WriteLine("{0} : {1}", lbl, b.Length);
}
public static void Main(string[] args)
{
List<ST_Log> data = new List<ST_Log> { new ST_Log { ProjectId=1, ChannelNumber=1, Value=123, CreationTime=DateTime.Now, Delete=false, Invalid=false },
new ST_Log { ProjectId=2, ChannelNumber=1, Value=456, CreationTime=DateTime.Now, Delete=false, Invalid=false },
new ST_Log { ProjectId=3, ChannelNumber=1, Value=789, CreationTime=DateTime.Now, Delete=false, Invalid=false },
new ST_Log { ProjectId=4, ChannelNumber=1, Value=123, CreationTime=DateTime.Now, Delete=false, Invalid=false },
new ST_Log { ProjectId=5, ChannelNumber=1, Value=456, CreationTime=DateTime.Now, Delete=false, Invalid=false } };
//Test(data, Proposed, "Proposed for List<string>"); // can't call a method not compiling
Test(data, ProposedModified, "Proposed for List<string> modified to List<T>");
// but let us see if it is possible to get back original data
Console.WriteLine("Try get back original data from this: {0}", Encoding.UTF8.GetString(ProposedModified(data)));
// OK - let us try to be serious
Test(data, PlainBinarySerialization, "Plain binary serializer");
Test(data, CompressingBinarySerialization, "Compressing binary serializer");
Console.ReadKey();
}
}
}