public void Basic(ISerializerAdapter adapter) { AssertForDeserialized(adapter, "{ \"key\": \"value\" }", "<key>value</key>", dictionary => { Assert.NotNull(dictionary); Assert.Equal("value", dictionary.GetValueOrDefault("key")); }); }
public void Roundtrip(ISerializerAdapter adapter) { AssertForDeserializedRoundtrip(adapter, new Dictionary<string, object> { { "key", "value" } }, dictionary => { Assert.NotNull(dictionary); Assert.Equal("value", dictionary.GetValueOrDefault("key")); }); }
public void Nested(ISerializerAdapter adapter) { AssertForDeserialized(adapter, "{ \"key\": { \"nested\": \"value\" } }", "<key><nested>value</nested></key>", dictionary => { Assert.NotNull(dictionary); var nested = Assert.IsAssignableFrom<IDictionary<string, object>>(dictionary.GetValueOrDefault("key")); Assert.Equal("value", nested.GetValueOrDefault("nested")); }); }
// ReSharper disable once UnusedParameter.Local private void AssertForDeserialized(ISerializerAdapter adapter, string valueInJson, string valueInXml, Action<IDictionary<string, object>> assert) { var deserialized = adapter.DeserializeJsonOrXml<RootClassWithSingleProperty<IDictionary<string, object>>>( "{ \"Value\": " + valueInJson + " }", "<Root><Value>" + valueInXml + "</Value></Root>" ); assert(deserialized.Value); }
public void PropertyAccess(ISerializerAdapter adapter) { AssertForDeserialized( adapter, "{ \"property\": \"value\" }", "<property>value</property>", d => Assert.Equal("value", (string)d.property) ); }
// ReSharper disable once UnusedParameter.Local private void AssertCanBeRoundtripped<TPropertyType, TActualType>(ISerializerAdapter adapter, TActualType value) where TActualType : TPropertyType, new() { var serialized = adapter.SerializeJsonOrXml(new RootClassWithSingleReadOnlyProperty<TPropertyType, TActualType>(value)); Debug.WriteLine("Serialized:\r\n" + serialized); var deserialized = adapter.DeserializeJsonOrXml<RootClassWithSingleReadOnlyProperty<TPropertyType, TActualType>>(serialized, serialized); Assert.Equal(value, deserialized.Value); }
private void AssertForDeserializedRoundtrip(ISerializerAdapter adapter, IDictionary <string, object> value, Action <IDictionary <string, object> > assert) { var serialized = adapter.SerializeJsonOrXml(new RootClassWithSingleProperty <IDictionary <string, object> > { Value = value }); var deserialized = adapter.DeserializeJsonOrXml <RootClassWithSingleProperty <IDictionary <string, object> > >(serialized, serialized); assert(deserialized.Value); }
// ReSharper disable once UnusedParameter.Local private void AssertCanBeDeserialized <T>(ISerializerAdapter adapter, string valueInJson, string valueInXml, T expected) { var deserialized = adapter.DeserializeJsonOrXml <RootClassWithSingleProperty <T> >( "{ \"Value\": " + valueInJson + " }", "<Root><Value>" + valueInXml + "</Value></Root>" ); Assert.Equal(expected, deserialized.Value); }
// ReSharper disable once UnusedParameter.Local private void AssertForDeserialized(ISerializerAdapter adapter, string valueInJson, string valueInXml, Action <IDictionary <string, object> > assert) { var deserialized = adapter.DeserializeJsonOrXml <RootClassWithSingleProperty <IDictionary <string, object> > >( "{ \"Value\": " + valueInJson + " }", "<Root><Value>" + valueInXml + "</Value></Root>" ); assert(deserialized.Value); }
public void Roundtrip(ISerializerAdapter adapter) { AssertForDeserializedRoundtrip(adapter, new Dictionary <string, object> { { "key", "value" } }, dictionary => { Assert.NotNull(dictionary); Assert.Equal("value", dictionary.GetValueOrDefault("key")); }); }
public void CastToType(ISerializerAdapter adapter) { AssertForDeserialized( adapter, "{ \"Value\": \"test\" }", "<Value>test</Value>", d => Assert.Equal("test", ((ClassWithSingleProperty<string>)d).Value) ); }
/// <summary> /// Builds a new method call result message. /// </summary> /// <param name="serializer">Serializer adapter used to serialize argument values</param> /// <param name="uniqueCallKey">Unique key to correlate RPC call</param> /// <param name="method">Method information of the called method</param> /// <param name="args">Arguments</param> /// <param name="returnValue">Returned return value</param> /// <returns>Method call result message</returns> public MethodCallResultMessage BuildMethodCallResultMessage( ISerializerAdapter serializer, Guid uniqueCallKey, MethodInfo method, object[] args, object returnValue) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } var isReturnValueNull = returnValue == null; var parameterInfos = method.GetParameters(); var message = new MethodCallResultMessage() { IsReturnValueNull = isReturnValueNull, ReturnValue = returnValue }; var outParameters = new List <MethodCallOutParameterMessage>(); for (var i = 0; i < args.Length; i++) { var arg = args[i]; var parameterInfo = parameterInfos[i]; if (!parameterInfo.IsOut) { continue; } var isArgNull = arg == null; var serializedArgValue = serializer.Serialize(parameterInfo.ParameterType, arg); outParameters.Add( new MethodCallOutParameterMessage() { ParameterName = parameterInfo.Name, OutValue = serializedArgValue, IsOutValueNull = isArgNull }); } message.OutParameters = outParameters.ToArray(); message.CallContextSnapshot = CallContext.GetSnapshot(); return(message); }
public PerformanceResult Measure(ISerializerAdapter serializer) { var result = new PerformanceResult(Name, serializer.Name, _measurementCount); try { Measure(serializer, result); } catch (Exception e) { result.Failure = e.Message; } return result; }
// ReSharper disable once UnusedParameter.Local private void AssertCanBeRoundtripped <T>(ISerializerAdapter adapter, T instance, Action <T> assertExtra = null) { var serialized = adapter.SerializeJsonOrXml(instance); Debug.WriteLine("Serialized: " + serialized); var deserialized = adapter.DeserializeJsonOrXml <T>(serialized, serialized); Assert.Equal(instance, deserialized); if (assertExtra != null) { assertExtra(deserialized); } }
public void NestedRoundtrip(ISerializerAdapter adapter) { AssertForDeserializedRoundtrip( adapter, new Dictionary<string, object> { { "key", new Dictionary<string, object> { { "nested", "value" } } } }, dictionary => { Assert.NotNull(dictionary); var nested = Assert.IsAssignableFrom<IDictionary<string, object>>(dictionary.GetValueOrDefault("key")); Assert.Equal("value", nested.GetValueOrDefault("nested")); } ); }
// ReSharper disable once UnusedParameter.Local private void AssertForDeserialized(ISerializerAdapter adapter, string valueInJson, string valueInXml, Action<dynamic> assert) { var deserialized = adapter.DeserializeJsonOrXml<RootClassWithSingleProperty<dynamic>>( "{ \"Value\": " + valueInJson + " }", "<Root><Value>" + valueInXml + "</Value></Root>" ); if (deserialized.Value != null) { Debug.WriteLine("Actual type of deserialized value: " + ((object)deserialized.Value).GetType()); } else { Debug.WriteLine("Deserialized value is null."); } assert(deserialized.Value); }
/// <summary> /// Builds method call parameter messages from arguments for a specified target method. /// </summary> /// <param name="serializer">Serializer adapter used to serialize argument values</param> /// <param name="targetMethod">Target method information</param> /// <param name="args">Array of arguments, which should passed a parameters</param> /// <returns>Enumerable of method call parameter messages</returns> public IEnumerable <MethodCallParameterMessage> BuildMethodParameterInfos( ISerializerAdapter serializer, MethodInfo targetMethod, object[] args) { var parameterInfos = targetMethod.GetParameters(); for (var i = 0; i < parameterInfos.Length; i++) { var arg = args[i]; var parameterInfo = parameterInfos[i]; var useParamArray = args.Length > parameterInfos.Length && i == parameterInfos.Length - 1 && parameterInfos[i].GetCustomAttribute <ParamArrayAttribute>() != null; var paramArrayValues = new List <object>(); if (useParamArray) { for (var j = i; j < args.Length; j++) { paramArrayValues.Add( serializer.EnvelopeNeededForParameterSerialization ? new Envelope(args[j]) : args[j]); } } var isArgNull = arg == null; object parameterValue = useParamArray ? paramArrayValues.ToArray() : serializer.EnvelopeNeededForParameterSerialization ? new Envelope(arg) : arg; yield return (new MethodCallParameterMessage() { IsOut = parameterInfo.IsOut, ParameterName = parameterInfo.Name, ParameterTypeName = parameterInfo.ParameterType.FullName + "," + parameterInfo.ParameterType.Assembly.GetName().Name, Value = parameterValue, IsValueNull = isArgNull }); } }
public PerformanceResult Measure(ISerializerAdapter serializer) { var result = new PerformanceResult(Name, serializer.Name, _measurementCount); try { Measure(serializer, result); } catch (Exception e) { result.Failure = e.Message; } return(result); }
public static BenchResult Run <T>(ISerializerAdapter serializer, T instance) where T : IAssertEquality { BenchResult result = new BenchResult(serializer.GetType().Name, instance.GetType().Name); result.Warmup = TestRunner.TestRun(serializer, instance); for (int i = 0; i < Times; i++) { result.Results.Add(TestRunner.TestRun(serializer, instance)); } return(result); }
public void NestedRoundtrip(ISerializerAdapter adapter) { AssertForDeserializedRoundtrip( adapter, new Dictionary <string, object> { { "key", new Dictionary <string, object> { { "nested", "value" } } } }, dictionary => { Assert.NotNull(dictionary); var nested = Assert.IsAssignableFrom <IDictionary <string, object> >(dictionary.GetValueOrDefault("key")); Assert.Equal("value", nested.GetValueOrDefault("nested")); } ); }
private void ValidateSerializer(ISerializerAdapter serializer, MemoryStream stream, PerformanceResult result) { long operationTime; Serialize(serializer, stream, out operationTime); result.Size = stream.Length; object deserialized = Deserialize(serializer, stream, out operationTime); var deserializedEnumerable = deserialized as IEnumerable; if (deserializedEnumerable != null) { if (!deserializedEnumerable.OfType<object>().SequenceEqual(((IEnumerable)GetValue()).OfType<object>())) throw new Exception("Deserialized object does not equal expected one"); } else if (!Equals(deserialized, GetValue())) throw new Exception("Deserialized object does not equal expected one"); }
// ReSharper disable once UnusedParameter.Local private void AssertForDeserialized(ISerializerAdapter adapter, string valueInJson, string valueInXml, Action <dynamic> assert) { var deserialized = adapter.DeserializeJsonOrXml <RootClassWithSingleProperty <dynamic> >( "{ \"Value\": " + valueInJson + " }", "<Root><Value>" + valueInXml + "</Value></Root>" ); if (deserialized.Value != null) { Debug.WriteLine("Actual type of deserialized value: " + ((object)deserialized.Value).GetType()); } else { Debug.WriteLine("Deserialized value is null."); } assert(deserialized.Value); }
// ReSharper disable once UnusedParameter.Local private void AssertCanBeDeserialized <TCollection>(ISerializerAdapter adapter, string valueInJson, TCollection expected) where TCollection : IEnumerable { var serialized = adapter.SerializeJsonOrXml(new RootClassWithSingleProperty <TCollection> { Value = expected }); Debug.WriteLine("Expected by serializer:\r\n" + serialized); // since there is no standard way to represent lists in XML, it just tests roundtrip var deserialized = adapter.DeserializeJsonOrXml <RootClassWithSingleProperty <TCollection> >( "{ \"Value\": " + valueInJson + " }", serialized ); Assert.Equal( expected.Cast <object>().ToArray(), deserialized.Value.Cast <object>().ToArray() ); }
/// <summary> /// Gets decrypted data from a wire message. /// </summary> /// <param name="message">Wire message</param> /// <param name="serializer">Serializer used to deserialized the signed content</param> /// <param name="sharedSecret">Shared secret (null, if the wire message is not encrypted)</param> /// <param name="sendersPublicKeyBlob">Public key of the sender used for RSA signature verification</param> /// <param name="sendersPublicKeySize">Sender's public key size</param> /// <returns>Decrypted raw data</returns> public byte[] GetDecryptedMessageData( WireMessage message, ISerializerAdapter serializer, byte[] sharedSecret = null, byte[] sendersPublicKeyBlob = null, int sendersPublicKeySize = 0) { if (message.Iv.Length > 0 && sharedSecret != null) { var decryptedRawData = AesEncryption.Decrypt( encryptedData: message.Data, sharedSecret: sharedSecret, iv: message.Iv); var signedMessageData = serializer.Deserialize <SignedMessageData>(decryptedRawData); if (sendersPublicKeyBlob != null && signedMessageData.Signature != null) { if (RsaSignature.VerifySignature( keySize: sendersPublicKeySize, sendersPublicKeyBlob: sendersPublicKeyBlob, rawData: signedMessageData.MessageRawData, signature: signedMessageData.Signature)) { return(signedMessageData.MessageRawData); } else { throw new SecurityException("Verification of message signature failed."); } } else { return(decryptedRawData); } } else { return(message.Data); } }
internal SerializationService(IInputOutputFactory inputOutputFactory, int version, IDictionary <int, IDataSerializableFactory> dataSerializableFactories, IDictionary <int, IPortableFactory> portableFactories, ICollection <IClassDefinition> classDefinitions, SerializerHooks hooks, IEnumerable <ISerializerDefinitions> definitions, bool checkClassDefErrors, IPartitioningStrategy partitioningStrategy, int initialOutputBufferSize, ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger <SerializationService>(); _inputOutputFactory = inputOutputFactory; GlobalPartitioningStrategy = partitioningStrategy; _outputBufferSize = initialOutputBufferSize; _bufferPoolThreadLocal = new BufferPoolThreadLocal(this); _portableContext = new PortableContext(this, version); // create data serializer (will be added as constant) var dataSerializer = new DataSerializer(hooks, dataSerializableFactories, loggerFactory); _dataSerializerAdapter = CreateSerializerAdapter <IIdentifiedDataSerializable>(dataSerializer); // create portable serializer (will be added as constant) _portableSerializer = new PortableSerializer(_portableContext, portableFactories); _portableSerializerAdapter = CreateSerializerAdapter <IPortable>(_portableSerializer); // create the serializer of null objects (will be added as constant) _nullSerializerAdapter = CreateSerializerAdapter <object>(new NullSerializer()); // create the serializable adapter (will be added as constant) _serializableSerializerAdapter = CreateSerializerAdapter <object>(new SerializableSerializer()); // add defined serializers foreach (var definition in definitions) { definition.AddSerializers(this); } // add constant serializers AddMoreSerializers(); // add class definitions RegisterClassDefinitions(classDefinitions, checkClassDefErrors); }
private void Measure(ISerializerAdapter serializer, PerformanceResult result) { GC.Collect(); using (var stream = new MemoryStream()) { ValidateSerializer(serializer, stream, result); for (int i = 0; i < _measurementCount; ++i) { long operationTime; Serialize(serializer, stream, out operationTime); result.SerializeTime.Add(operationTime); Deserialize(serializer, stream, out operationTime); result.DeserializeTime.Add(operationTime); } } result.SerializeTime.Compact(); result.DeserializeTime.Compact(); }
public static RunResult TestRun <T>(ISerializerAdapter serializer, T instance) where T : IAssertEquality { RunResult result = new RunResult(); var w = Stopwatch.StartNew(); byte[] data; T output = default(T); try { using (MemoryStream ms = new MemoryStream()) { var serW = Stopwatch.StartNew(); serializer.Serialize(new IndisposableStream(ms), instance); result.Serialization = serW.Elapsed; data = ms.ToArray(); } using (MemoryStream ms = new MemoryStream(data)) { ms.Seek(0, SeekOrigin.Begin); var deserW = Stopwatch.StartNew(); output = (T)serializer.Deserialize(new IndisposableStream(ms), typeof(T)); result.Deserialization = deserW.Elapsed; } result.TotalTime = w.Elapsed; instance.AssertEquality(output); } catch (Exception x) { Console.WriteLine(x.Message); result.Serialization = TimeSpan.FromSeconds(0); result.Deserialization = TimeSpan.FromSeconds(0); result.TotalTime = TimeSpan.FromSeconds(0); } return(result); }
private void ValidateSerializer(ISerializerAdapter serializer, MemoryStream stream, PerformanceResult result) { long operationTime; Serialize(serializer, stream, out operationTime); result.Size = stream.Length; object deserialized = Deserialize(serializer, stream, out operationTime); var deserializedEnumerable = deserialized as IEnumerable; if (deserializedEnumerable != null) { if (!deserializedEnumerable.OfType <object>().SequenceEqual(((IEnumerable)GetValue()).OfType <object>())) { throw new Exception("Deserialized object does not equal expected one"); } } else if (!Equals(deserialized, GetValue())) { throw new Exception("Deserialized object does not equal expected one"); } }
internal SerializationService(IInputOutputFactory inputOutputFactory, int version, IDictionary <int, IDataSerializableFactory> dataSerializableFactories, IDictionary <int, IPortableFactory> portableFactories, ICollection <IClassDefinition> classDefinitions, bool checkClassDefErrors, IManagedContext managedContext, IPartitioningStrategy partitionStrategy, int initialOutputBufferSize, bool enableCompression, bool enableSharedObject) { this.inputOutputFactory = inputOutputFactory; this.managedContext = managedContext; globalPartitioningStrategy = partitionStrategy; outputBufferSize = initialOutputBufferSize; dataOutputQueue = new ThreadLocalOutputCache(this); portableContext = new PortableContext(this, version); dataSerializerAdapter = CreateSerializerAdapterByGeneric <IDataSerializable>(new DataSerializer(dataSerializableFactories)); portableSerializer = new PortableSerializer(portableContext, portableFactories); portableSerializerAdapter = CreateSerializerAdapterByGeneric <IPortable>(portableSerializer); RegisterConstantSerializers(); RegisterDefaultSerializers(); RegisterClassDefinitions(classDefinitions, checkClassDefErrors); }
private void SafeRegister(Type type, ISerializerAdapter serializer) { if (constantTypesMap.ContainsKey(type)) { throw new ArgumentException("[" + type + "] serializer cannot be overridden!"); } var current = typeMap.GetOrAdd(type, serializer); if (current != null && current.GetImpl().GetType() != serializer.GetImpl().GetType()) { throw new InvalidOperationException("Serializer[" + current.GetImpl() + "] has been already registered for type: " + type); } current = idMap.GetOrAdd(serializer.GetTypeId(), serializer); if (current != null && current.GetImpl().GetType() != serializer.GetImpl().GetType()) { throw new InvalidOperationException("Serializer [" + current.GetImpl() + "] has been already registered for type-id: " + serializer.GetTypeId()); } }
internal SerializationService(IInputOutputFactory inputOutputFactory, int version, IDictionary <int, IDataSerializableFactory> dataSerializableFactories, IDictionary <int, IPortableFactory> portableFactories, ICollection <IClassDefinition> classDefinitions, bool checkClassDefErrors, IPartitioningStrategy partitionStrategy, int initialOutputBufferSize) { _inputOutputFactory = inputOutputFactory; GlobalPartitioningStrategy = partitionStrategy; _outputBufferSize = initialOutputBufferSize; _bufferPoolThreadLocal = new BufferPoolThreadLocal(this); _portableContext = new PortableContext(this, version); _dataSerializerAdapter = CreateSerializerAdapterByGeneric <IIdentifiedDataSerializable>( new DataSerializer(dataSerializableFactories)); _portableSerializer = new PortableSerializer(_portableContext, portableFactories); _portableSerializerAdapter = CreateSerializerAdapterByGeneric <IPortable>(_portableSerializer); _nullSerializerAdapter = CreateSerializerAdapterByGeneric <object>(new ConstantSerializers.NullSerializer()); _serializableSerializerAdapter = CreateSerializerAdapterByGeneric <object>(new DefaultSerializers.SerializableSerializer()); RegisterConstantSerializers(); RegisterDefaultSerializers(); RegisterClassDefinitions(classDefinitions, checkClassDefErrors); }
private static void RunListTest(Type serializerType) { ISerializerAdapter serializer = (ISerializerAdapter)Activator.CreateInstance(serializerType); List <TestCustomObject> messages = new List <TestCustomObject> { new TestCustomObject { Value = 10 } }; Type messagesType = typeof(List <TestCustomObject>); using (MemoryStream ms = new MemoryStream()) { object output = null; bool ex = false; try { serializer.Serialize(new IndisposableStream(ms), messages); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); output = serializer.Deserialize(new IndisposableStream(ms), messagesType); } catch (Exception x) { Assert.Inconclusive("The the serializer has at least thrown an exception instead of unexpected results {0}", x); ex = true; } if (!ex) { Assert.IsInstanceOfType(messagesType, output); List <TestCustomObject> deserialized = output as List <TestCustomObject>; Assert.AreEqual(messages.Single().Value.ToString(), deserialized.Single().Value.ToString()); } } }
public void Run(ISerializerAdapter serializer, string[] args) { var iterations = args.Length > 0 ? int.Parse(args[0]) : _defaultIterations; var adapterName = serializer.GetType().Namespace.Split('.').Last(); var tests = typeof(ISerializationTest).Assembly .GetTypes() .Where(t => t.IsClass && typeof(ISerializationTest).IsAssignableFrom(t)) .Select(t => (ISerializationTest)Activator.CreateInstance(t)); foreach (var test in tests) { Console.Write("{0}\t{1}\t", adapterName, test.GetType().Name); var graph = test.Graph; // Warmup RunTest(serializer, graph); if (!Stopwatch.IsHighResolution) { Console.Error.WriteLine("Stopwatch is not high resolution!"); } var timer = Stopwatch.StartNew(); for (var i = 0; i < iterations; ++i) { RunTest(serializer, graph); } var duration = timer.Elapsed; Console.WriteLine("{0}", duration.TotalMilliseconds / iterations); } }
public void Run(ISerializerAdapter serializer, string[] args) { var iterations = args.Length > 0 ? int.Parse(args[0]) : _defaultIterations; var adapterName = serializer.GetType().Namespace.Split('.').Last(); var tests = typeof(ISerializationTest).Assembly .GetTypes() .Where(t => t.IsClass && typeof(ISerializationTest).IsAssignableFrom(t)) .Select(t => (ISerializationTest)Activator.CreateInstance(t)); foreach(var test in tests) { Console.Write("{0}\t{1}\t", adapterName, test.GetType().Name); var graph = test.Graph; // Warmup RunTest(serializer, graph); if(!Stopwatch.IsHighResolution) { Console.Error.WriteLine("Stopwatch is not high resolution!"); } var timer = Stopwatch.StartNew(); for (var i = 0; i < iterations; ++i) { RunTest(serializer, graph); } var duration = timer.Elapsed; Console.WriteLine("{0}", duration.TotalMilliseconds / iterations); } }
public SqlEventStoreRepository(IConfiguration configuration, ISerializerAdapter serializer) { _sqlConnectionString = configuration.GetConnectionString("EventStoreDb"); _serializer = serializer; }
private void AssertForDeserializedRoundtrip(ISerializerAdapter adapter, IDictionary<string, object> value, Action<IDictionary<string, object>> assert) { var serialized = adapter.SerializeJsonOrXml(new RootClassWithSingleProperty<IDictionary<string, object>> { Value = value }); var deserialized = adapter.DeserializeJsonOrXml<RootClassWithSingleProperty<IDictionary<string, object>>>(serialized, serialized); assert(deserialized.Value); }
private void RunTest(ISerializerAdapter serializer, object graph) { var buffer = new StringWriter(); serializer.Serialize(buffer, graph); }
protected abstract void Serialize(ISerializerAdapter serializer, Stream stream, out long operationTime);
public DataSerializer(ISerializerAdapter serializer) { _serializer = serializer; }
public void CastToInt32(ISerializerAdapter adapter) { AssertForDeserialized(adapter, "5", "5", d => Assert.Equal(5, (int)d)); }
public void CastToString(ISerializerAdapter adapter) { AssertForDeserialized(adapter, "\"x\"", "x", d => Assert.Equal("x", (string)d)); }
public IZer0MqBuilder SetSerializer(ISerializerAdapter adapter) { _serializer = adapter; return(this); }