public void TestSerializeUndefinedEnum() { SomeEnumEntity dee = new SomeEnumEntity { Enum = 0 }; Serializer.Serialize(Stream.Null, dee); }
static void WriteToFile(string path, Database database) { using (Stream fs = File.Create(path)) { Serializer.Serialize(fs, database); fs.Close(); } }
public void TestNotAContract() { NotAContract nac = new NotAContract { X = 4 }; Serializer.Serialize(Stream.Null, nac); }
public void MultiByteUTF8Len128() // started failing... { Test2 t2 = new Test2 { B = new string('ä', 128) }; MemoryStream ms = new MemoryStream(); Serializer.Serialize(ms, t2); ms.Position = 0; byte[] raw = ms.ToArray(); Test2 clone = Serializer.Deserialize <Test2>(ms); Assert.IsNotNull(clone); Assert.AreEqual(t2.B, clone.B); }
static Database ReadFromDatabase(this NorthwindDataContext ctx, string path) { Database db = new Database(); DataLoadOptions opt = new DataLoadOptions(); opt.AssociateWith <Order>(order => order.Lines); ctx.LoadOptions = opt; db.Orders.AddRange(ctx.Orders); using (FileStream fs = File.Create(path)) { Serializer.Serialize(fs, db); } return(db); }
private void ExchangeKeys(Stream baseStream, ISymmetricAlgorithmDescriptor transportAlgorithmDescriptor, IKeyExchangeAlgorithm keyExchangeAlgorithm, out ICryptoTransform decryptor, out ICryptoTransform encryptor) { var encryptionAlgorithm = transportAlgorithmDescriptor.Build(); var key = new byte[encryptionAlgorithm.KeySize / 8]; var iv = new byte[encryptionAlgorithm.BlockSize / 8]; prng.GetBytes(key); prng.GetBytes(iv); encryptionAlgorithm.Key = key; encryptionAlgorithm.IV = iv; var keyPackage = new KeyPackage { Key = encryptionAlgorithm.Key, InitializationVector = encryptionAlgorithm.IV, }; byte[] keyBuffer; using (var memoryStream = new MemoryStream()) { Serializer.Serialize(memoryStream, keyPackage); keyBuffer = keyExchangeAlgorithm.Encrypt(memoryStream.ToArray()); } var buffer = bitConverter.GetBytes(keyBuffer.Length); baseStream.Write(buffer, 0, buffer.Length); baseStream.Write(keyBuffer, 0, keyBuffer.Length); buffer = new byte[sizeof(int)]; baseStream.Read(buffer, 0, buffer.Length); var length = bitConverter.ToInt32(buffer); if (0 > length) { throw new InvalidDataException(); } buffer = new byte[length]; baseStream.Read(buffer, 0, buffer.Length); buffer = keyExchangeAlgorithm.Decrypt(buffer); var decryptionAlgorithm = transportAlgorithmDescriptor.Build(); KeyPackage remoteKeyPackage; using (var memoryStream = new MemoryStream(buffer)) remoteKeyPackage = Serializer.Deserialize <KeyPackage>(memoryStream); decryptionAlgorithm.Key = remoteKeyPackage.Key; decryptionAlgorithm.IV = remoteKeyPackage.InitializationVector; encryptor = encryptionAlgorithm.CreateEncryptor(); decryptor = decryptionAlgorithm.CreateDecryptor(); }
/// <summary> /// Сериализует заголовок. /// </summary> /// <param name="stream"></param> /// <param name="headerSize"></param> public void SerializeProtoBuf(Stream stream, out int headerSize) { int initialPos = (int)stream.Position; // Сериализуем хедэр. ProtoBufSerializer.Serialize(stream, this); headerSize = (int)stream.Position - initialPos; Debug.Assert(headerSize <= HeaderMaxSize); if (headerSize <= HeaderMaxSize) { return; } ThrowHelper.ThrowVRpcException(HeaderSizeExceededException); }
private void WriteAlgorithms <T>(Stream target, T[] algorithms, IKeyExchangeAlgorithm encryptionAlgorithm) where T : IAlgorithmDescriptor { byte[] buffer; using (var outputStream = new MemoryStream()) { buffer = bitConverter.GetBytes(algorithms.Length); outputStream.Write(buffer, 0, buffer.Length); foreach (var algorithm in algorithms.Select(MakePackage)) { //this.LogDebug("TX: Algorithm {0}", algorithm.AlgorithmIdentifier); Serializer.Serialize(outputStream, algorithm); } buffer = encryptionAlgorithm.Encrypt(outputStream.ToArray()); } var lengthBytes = bitConverter.GetBytes(buffer.Length); target.Write(lengthBytes, 0, lengthBytes.Length); target.Write(buffer, 0, buffer.Length); }
public bool PerfTestArray(int count, bool log) { int[] data = new int[1000]; for (int i = 0; i < 1000; i++) { data[i] = i; } Test5 t5 = new Test5 { Data = data }; using (MemoryStream ms = new MemoryStream()) { Serializer.Serialize(ms, t5); ms.Position = 0; Test5 clone = Serializer.Deserialize <Test5>(ms); if (t5.Data.Length != clone.Data.Length) { return(false); } for (int i = 0; i < t5.Data.Length; i++) { if (t5.Data[i] != clone.Data[i]) { return(false); } } Stopwatch watch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { ms.Position = 0; Serializer.Deserialize <Test5>(ms); } watch.Stop(); if (log) { Console.WriteLine("array x {0}; {1} ms", count, watch.ElapsedMilliseconds); } } return(true); }
// serialize an object to protobuf private bool protoBufSerialize <T>(T obj, string filePath) where T : class { // try to serialize, log any errors if they occurred try { using (var file = File.Create(filePath)) { ProtoBufSerializer.Serialize(file, obj); } } catch (UnauthorizedAccessException e) { Debug.LogError($"Serialization error: Could not serialize to \"{filePath}\", incorrect permission or readonly file"); Debug.LogException(e); } catch (ArgumentException e) { Debug.LogError($"Serialization error: Could not serialize to \"{filePath}\", malformed path"); Debug.LogException(e); } catch (DirectoryNotFoundException e) { Debug.LogError($"Serialization error: Could not serialize to \"{filePath}\", directory not found or path invalid"); Debug.LogException(e); } catch (IOException e) { Debug.LogError($"Serialization error: Could not serialize to \"{filePath}\", error occurred creating the file"); Debug.LogException(e); } catch (NotSupportedException e) { Debug.LogError($"Serialization error: Could not serialize to \"{filePath}\", path is in invalid format"); Debug.LogException(e); } return(true); }
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { Serializer.Serialize <DatabaseCompatRem>(info, this); }
public static bool LoadTestItem <T>(T item, int count, int protoCount, bool testBinary, bool testSoap, bool testXml, bool testProtoSharp, bool writeJson, bool testNetDcs, params byte[] expected) where T : class, new() { bool pass = true; string name = typeof(T).Name; Console.WriteLine("\t{0}", name); Stopwatch serializeWatch, deserializeWatch; T pbClone, psClone = null; Console.WriteLine("\t(times based on {0} iterations ({1} for .proto))", count, protoCount); Console.WriteLine("||*Serializer*||*size*||*serialize*||*deserialize*||"); byte[] pbnetBuffer; using (MemoryStream ms = new MemoryStream()) { Serializer.Serialize(ms, item); ms.Position = 0; pbClone = Serializer.Deserialize <T>(ms); byte[] data = ms.ToArray(); if (expected != null && !Program.ArraysEqual(data, expected)) { Console.WriteLine("\t*** serialization failure"); WriteBytes("Binary", data); } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); serializeWatch = Stopwatch.StartNew(); for (int i = 0; i < protoCount; i++) { Serializer.Serialize(Stream.Null, item); } serializeWatch.Stop(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); deserializeWatch = Stopwatch.StartNew(); for (int i = 0; i < protoCount; i++) { ms.Position = 0; Serializer.Deserialize <T>(ms); } deserializeWatch.Stop(); Console.WriteLine("||protobuf-net||{0:###,###,###}||{1:###,###,###}||{2:###,###,###}||", ms.Length, serializeWatch.ElapsedMilliseconds, deserializeWatch.ElapsedMilliseconds); pbnetBuffer = ms.ToArray(); } /*if (testProtoSharp) * { * using (MemoryStream ms = new MemoryStream()) * { * ProtoSharp.Core.Serializer.Serialize(ms, item); * ms.Position = 0; * * byte[] buffer = ms.ToArray(); * * psClone = ProtoSharp.Core.Serializer.Deserialize<T>(ms); * if (expected != null && !Program.ArraysEqual(buffer, expected)) * { * Console.WriteLine("\t*** serialization failure"); * WriteBytes("Binary", buffer); * } * GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); * serializeWatch = Stopwatch.StartNew(); * for (int i = 0; i < protoCount; i++) * { * ProtoSharp.Core.Serializer.Serialize(Stream.Null, item); * } * serializeWatch.Stop(); * * GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); * deserializeWatch = Stopwatch.StartNew(); * for (int i = 0; i < protoCount; i++) * { * ms.Position = 0; * ProtoSharp.Core.Serializer.Deserialize<T>(ms); * } * deserializeWatch.Stop(); * Console.WriteLine("||[http://code.google.com/p/protosharp/ proto#]||{0:###,###,###}||{1:###,###,###}||{2:###,###,###}||", * buffer.Length, serializeWatch.ElapsedMilliseconds, deserializeWatch.ElapsedMilliseconds); * } * }*/ if (testBinary) { using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, item); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); serializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { bf.Serialize(Stream.Null, item); } serializeWatch.Stop(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); deserializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { ms.Position = 0; bf.Deserialize(ms); } deserializeWatch.Stop(); Console.WriteLine("||`BinaryFormatter`||{0:###,###,###}||{1:###,###,###}||{2:###,###,###}||", ms.Length, serializeWatch.ElapsedMilliseconds, deserializeWatch.ElapsedMilliseconds); } } if (testSoap) { using (MemoryStream ms = new MemoryStream()) { SoapFormatter sf = new SoapFormatter(); sf.Serialize(ms, item); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); serializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { sf.Serialize(Stream.Null, item); } serializeWatch.Stop(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); deserializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { ms.Position = 0; sf.Deserialize(ms); } deserializeWatch.Stop(); Console.WriteLine("||`SoapFormatter`||{0:###,###,###}||{1:###,###,###}||{2:###,###,###}||", ms.Length, serializeWatch.ElapsedMilliseconds, deserializeWatch.ElapsedMilliseconds); } } if (testXml) { using (MemoryStream ms = new MemoryStream()) { XmlSerializer xser = new XmlSerializer(typeof(T)); xser.Serialize(ms, item); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); serializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { xser.Serialize(Stream.Null, item); } serializeWatch.Stop(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); deserializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { ms.Position = 0; xser.Deserialize(ms); } deserializeWatch.Stop(); Console.WriteLine("||`XmlSerializer`||{0:###,###,###}||{1:###,###,###}||{2:###,###,###}||", ms.Length, serializeWatch.ElapsedMilliseconds, deserializeWatch.ElapsedMilliseconds); } } if (testNetDcs) { using (MemoryStream ms = new MemoryStream()) { NetDataContractSerializer nxser = new NetDataContractSerializer(); nxser.WriteObject(ms, item); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); serializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { nxser.WriteObject(Stream.Null, item); } serializeWatch.Stop(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); deserializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { ms.Position = 0; nxser.ReadObject(ms); } deserializeWatch.Stop(); Console.WriteLine("||`NetDataContractSerializer`||{0:###,###,###}||{1:###,###,###}||{2:###,###,###}||", ms.Length, serializeWatch.ElapsedMilliseconds, deserializeWatch.ElapsedMilliseconds); } } if (!(item is ISerializable)) { using (MemoryStream ms = new MemoryStream()) { DataContractSerializer xser = new DataContractSerializer(typeof(T)); xser.WriteObject(ms, item); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); serializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { xser.WriteObject(Stream.Null, item); } serializeWatch.Stop(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); deserializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { ms.Position = 0; xser.ReadObject(ms); } deserializeWatch.Stop(); Console.WriteLine("||`DataContractSerializer`||{0:###,###,###}||{1:###,###,###}||{2:###,###,###}||", ms.Length, serializeWatch.ElapsedMilliseconds, deserializeWatch.ElapsedMilliseconds); } #if NET_3_5 using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializer xser = new DataContractJsonSerializer(typeof(T)); xser.WriteObject(ms, item); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); serializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { xser.WriteObject(Stream.Null, item); } serializeWatch.Stop(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); deserializeWatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { ms.Position = 0; xser.ReadObject(ms); } deserializeWatch.Stop(); Console.WriteLine("||`DataContractJsonSerializer`||{0:###,###,###}||{1:###,###,###}||{2:###,###,###}||", ms.Length, serializeWatch.ElapsedMilliseconds, deserializeWatch.ElapsedMilliseconds); string originalJson = Encoding.UTF8.GetString(ms.ToArray()), pbJson, psJson = null; using (MemoryStream ms2 = new MemoryStream()) { xser.WriteObject(ms2, pbClone); pbJson = Encoding.UTF8.GetString(ms.ToArray()); } if (testProtoSharp) { using (MemoryStream ms3 = new MemoryStream()) { xser.WriteObject(ms3, psClone); psJson = Encoding.UTF8.GetString(ms.ToArray()); } } if (writeJson) { Console.WriteLine("\tJSON: {0}", originalJson); } if (originalJson != pbJson) { pass = false; Console.WriteLine("\t**** json comparison fails (protobuf-net)!"); Console.WriteLine("\tClone JSON: {0}", pbJson); } if (testProtoSharp && (originalJson != psJson)) { pass = false; Console.WriteLine("\t**** json comparison fails (proto#)!"); Console.WriteLine("\tClone JSON: {0}", psJson); } } #endif } Console.WriteLine("\t[end {0}]", name); Console.WriteLine(); return(pass); }
public override void PerformSerializationTest(Serializer serializer, Stream target) { foreach(var msg in m_Data)//<------ The whole point of this test is THIS LOOP that calls serialize MANY times serializer.Serialize(msg, target); }
static void Main() { Database db; Console.WriteLine("Using groups: {0}", Database.SubObjectFormat == DataFormat.Group); // if have a Northwind handy... using (var ctx = new NorthwindDataContext()) { db = ctx.ReadFromDatabase("nwind.proto.bin"); DbMetrics("Database", db); } string proto = Serializer.GetProto <Database>(); File.WriteAllText("nwind.proto", proto); Console.WriteLine(proto); // otherwise... using (MemoryStream ms = new MemoryStream(File.ReadAllBytes("nwind.proto.bin"))) { db = Serializer.Deserialize <Database>(ms); for (int i = 0; i < 3; i++) { Serializer.Serialize(Stream.Null, db); } } /* * for (int i = 0; i < 1; i++) * { * using (Stream ms = new MemoryStream()) * { * Serializer.Serialize(ms, db); * //ms.Position = 0; * //db = Serializer.Deserialize<Database>(ms); * } * } */ using (MemoryStream ms = new MemoryStream()) { new DataContractSerializer(db.GetType()).WriteObject(ms, db); Console.WriteLine("DataContractSerializer length: {0:###,###,000}", ms.Length); } using (MemoryStream ms = new MemoryStream()) { using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { new DataContractSerializer(db.GetType()).WriteObject(zip, db); zip.Close(); } Console.WriteLine("GZip/DataContractSerializer length: {0:###,###,000}", ms.Length); } using (MemoryStream ms = new MemoryStream()) { using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { Serializer.Serialize(zip, db); zip.Close(); } Console.WriteLine("GZip/proto length: {0:###,###,000}", ms.Length); } using (MemoryStream ms = new MemoryStream()) { Serializer.Serialize(ms, db); ms.Position = 0; Console.WriteLine("proto length: {0:###,###,000}", ms.Length); Database pbnet = Serializer.Deserialize <Database>(ms); DbMetrics("protobuf-net", pbnet); //Database psharp = MessageReader.Read<Database>(ms.ToArray()); //DbMetrics("proto#", psharp); } Console.WriteLine(); Console.WriteLine("[press any key]"); Console.ReadKey(); /* * Console.WriteLine("{0}={1} bytes", path, new FileInfo(path).Length); * * Database db = null; * Stopwatch watch = Stopwatch.StartNew(); * for (int i = 0; i < COUNT; i++) * { * db = ReadFromFile(path); * } * watch.Stop(); * Console.WriteLine("Load x{0}: {1}ms", COUNT, watch.ElapsedMilliseconds); * watch = Stopwatch.StartNew(); * for (int i = 0; i < COUNT; i++) * { * WriteToFile(path, db); * } * watch.Stop(); * Console.WriteLine("Save x{0}: {1}ms", COUNT, watch.ElapsedMilliseconds); */ }
public static void Serialize(FileStream file, object data) { ProtoSerializer.Serialize(file, data); }
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { Serializer.Serialize(writer, this); }
public override void PerformSerializationTest(Serializer serializer, Stream target) { var root = m_List ? (object)m_Data : m_Data[0]; serializer.Serialize(root, target); }
public override void PerformSerializationTest(Serializer serializer, Stream target) { serializer.Serialize(m_Data, target); }