public override void PerformDeserializationTest(Serializer serializer, Stream target) { var got = serializer.Deserialize(target); var originalRoot = m_List ? (object)m_Data : m_Data[0]; serializer.AssertPayloadEquality(this, originalRoot, got); }
private static void Main() { // Сериализация var person = new Person { Id = 12345, Name = "Fred", Address = new Address { Line1 = "Flat 1", Line2 = "The Meadows" } }; using (Stream file = File.Create("person.bin")) { ProtocolBufferSerializer.Serialize(file, person); } // Десериализация using (Stream file = File.OpenRead("person.bin")) { var newPerson = ProtocolBufferSerializer.Deserialize <Person>(file); Console.WriteLine(newPerson); } }
private IEnumerable <IAlgorithmDescriptor> ReadRemoteAlgorithms(Stream source, IKeyExchangeAlgorithm encryptionAlgorithm) { var buffer = new byte[sizeof(int)]; source.Read(buffer, 0, buffer.Length); var length = bitConverter.ToInt32(buffer); if (0 > length) { throw new InvalidDataException(); } buffer = new byte[length]; source.Read(buffer, 0, buffer.Length); buffer = encryptionAlgorithm.Decrypt(buffer); var result = new List <IAlgorithmDescriptor>(); using (var outputStream = new MemoryStream(buffer)) { var lengthBuffer = new byte[sizeof(int)]; outputStream.Read(lengthBuffer, 0, lengthBuffer.Length); var algorithmCount = bitConverter.ToInt32(lengthBuffer); for (var i = 0; i < algorithmCount; ++i) { var algorithm = Serializer.Deserialize <AlgorithmDescriptorPackage>(outputStream); result.Add(algorithm); //this.LogDebug("RX: Algorithm {0}", algorithm.AlgorithmIdentifier); } } return(result); }
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 TestSerializeUndefinedEnum() { SomeEnumEntity dee = new SomeEnumEntity { Enum = 0 }; Serializer.Serialize(Stream.Null, dee); }
public void MultiByteUTF8() { Test2 t2 = new Test2 { B = "Toms Spezialitäten" }, clone = Serializer.DeepClone(t2); Assert.AreEqual(t2.B, clone.B); }
public static T LoadDatabaseFromFile <T>() where T : class, new() { // otherwise... using (Stream fs = File.OpenRead(@"NWind\nwind.proto.bin")) { return(Serializer.Deserialize <T>(fs)); } }
public void PerfTestEnumOnce() { Test4 t4 = new Test4 { D = TestEnum.D }; Assert.IsTrue(Program.CheckBytes(t4, 0x20, 0x03)); Assert.AreEqual(t4.D, Serializer.DeepClone(t4).D); }
/// <returns>Может быть Null если не удалось десериализовать.</returns> public static HeaderDto DeserializeProtoBuf(byte[] buffer, int offset, int count) { HeaderDto header; using (var mem = new MemoryStream(buffer, offset, count)) header = ProtoBufSerializer.Deserialize <HeaderDto>(mem); header.ValidateDeserializedHeader(); return(header); }
static Database ReadFromFile(string path) { Database database; using (Stream fs = File.OpenRead(path)) { database = Serializer.Deserialize <Database>(fs); fs.Close(); } return(database); }
public void Blob() { ItemWithBlob blob = new ItemWithBlob(), clone = Serializer.DeepClone(blob); Assert.IsTrue(Program.CheckBytes(blob, new byte[0]), "Empty serialization"); Assert.IsTrue(Program.ArraysEqual(blob.Foo, clone.Foo), "Clone should be empty"); blob.Foo = new byte[] { 0x01, 0x02, 0x03 }; clone = Serializer.DeepClone(blob); Assert.IsTrue(Program.ArraysEqual(blob.Foo, clone.Foo), "Clone should match"); Assert.IsTrue(Program.CheckBytes(blob, 0x0A, 0x03, 0x01, 0x02, 0x03), "Stream should match"); }
public static bool TryReadLengthPrefix(Stream source, out int length) { long pos = source.Position; // Заголовок сообщения находится в самом начале. source.Position = 0; bool success = ProtoBufSerializer.TryReadLengthPrefix(source, HeaderLengthPrefix, out length); source.Position = pos; return(success); }
public void MultiByteUTF8KnownProblemLength() { // 513 triggers buffer resize; specific problem case (i.e. bug) char mb = 'ä'; Assert.AreEqual(2, Encoding.UTF8.GetByteCount(new char[] { mb }), "is multibyte"); int i = 513; Test2 t2 = new Test2 { B = new string(mb, i) }, clone = Serializer.DeepClone(t2); Assert.AreEqual(i, t2.B.Length, "len"); Assert.AreEqual(t2.B, clone.B, "Count: " + i.ToString()); }
// deserialize from protobuf private T protoBufDeserialize <T>(string filePath) where T : class { // try to deserialize from protobuf, and log any errors that occur try { using (var file = File.OpenRead(filePath)) { return(ProtoBufSerializer.Deserialize <T>(file)); } } catch (ArgumentException e) { Debug.LogError($"Deserialization error: Could not deserialize from \"{filePath}\", malformed path"); Debug.LogException(e); return(null); } catch (DirectoryNotFoundException e) { Debug.LogError( $"Deserialization error: Could not deserialize from \"{filePath}\", directory not found or path invalid"); Debug.LogException(e); return(null); } catch (UnauthorizedAccessException e) { Debug.LogError( $"Deserialization error: Could not deserialize from \"{filePath}\", path was directory or caller does not have required permission"); Debug.LogException(e); return(null); } catch (FileNotFoundException e) { Debug.LogError($"Deserialization error: Could not deserialize from \"{filePath}\", file not found"); Debug.LogException(e); return(null); } catch (NotSupportedException e) { Debug.LogError( $"Deserialization error: Could not deserialize from \"{filePath}\", path is in invalid format"); Debug.LogException(e); return(null); } catch (IOException e) { Debug.LogError($"Deserialization error: Could not deserialize from \"{filePath}\", an error occurred opening the file"); Debug.LogException(e); return(null); } }
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); }
public void MultiByteUTF8VariousLengths() { char mb = 'ä'; Assert.AreEqual(2, Encoding.UTF8.GetByteCount(new char[] { mb }), "is multibyte"); for (int i = 0; i < 1024; i++) { try { Test2 t2 = new Test2 { B = new string(mb, i) }, clone = Serializer.DeepClone(t2); Assert.AreEqual(i, t2.B.Length, "len"); Assert.AreEqual(t2.B, clone.B, "Count: " + i.ToString()); } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); Assert.Fail(i.ToString() + ": " + ex.Message); } } }
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { Serializer.Merge(reader, this); }
public override void PerformDeserializationTest(Serializer serializer, Stream target) { foreach(var msg in m_Data) { var got = serializer.Deserialize(target); serializer.AssertPayloadEquality(this, msg, got); } }
public void TestProtoGen() { // just show it can do *something*! string proto = Serializer.GetProto <Database>(); }
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); }
public static T DeserializeWithLengthPrefix <T>(FileStream file) { return(ProtoSerializer.DeserializeWithLengthPrefix <T>(file, PrefixStyle.Fixed32)); }
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) { var root = m_List ? (object)m_Data : m_Data[0]; serializer.Serialize(root, target); }
public override void PerformDeserializationTest(Serializer serializer, Stream target) { var deserialized = serializer.Deserialize(target); serializer.AssertPayloadEquality(this, m_Data, deserialized); }
public override void PerformSerializationTest(Serializer serializer, Stream target) { serializer.Serialize(m_Data, target); }
protected DatabaseCompatRem(SerializationInfo info, StreamingContext context) : this() { Serializer.Merge <DatabaseCompatRem>(info, this); }
public void TestProtoGen() { string proto = Serializer.GetProto <Database>(); }
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { Serializer.Serialize <DatabaseCompatRem>(info, this); }
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer) { Serializer.Serialize(writer, this); }