Ejemplo n.º 1
0
        public void AzureQueueBatchContainer_VerifyBothMessageTypesCanBeDeserialized()
        {
            var container = new AzureQueueBatchContainer(Guid.NewGuid(), "namespace", new List <object> {
                "item"
            }, new Dictionary <string, object>()
            {
                { "key", "value" }
            }, new EventSequenceToken(long.MaxValue, int.MaxValue));
            var writer = new BinaryTokenStreamWriter();

            SerializationManager.Serialize(container, writer);
            var bytes = writer.ToByteArray();

            writer = new BinaryTokenStreamWriter();
            var container2 = new AzureQueueBatchContainerV2(Guid.NewGuid(), "namespace", new List <object> {
                "item"
            }, new Dictionary <string, object>()
            {
                { "key", "value" }
            }, new EventSequenceTokenV2(long.MaxValue, int.MaxValue));

            SerializationManager.Serialize(container2, writer);
            var bytes2 = writer.ToByteArray();

            var msg  = new CloudQueueMessage(bytes);
            var msg2 = new CloudQueueMessage(bytes2);
            var bc1  = (IBatchContainer)AzureQueueBatchContainer.FromCloudQueueMessage(msg, 0);
            var bc2  = (IBatchContainer)AzureQueueBatchContainer.FromCloudQueueMessage(msg2, 0);

            Assert.NotNull(bc1);
            Assert.NotNull(bc2);
        }
Ejemplo n.º 2
0
        internal static void Serialize(object obj, BinaryTokenStreamWriter stream, Type unused)
        {
            var envelope = (RequestEnvelope)obj;

            stream.Write(envelope.Target);
            MessageEnvelope.Serializer.Serialize(envelope.Message, stream);
        }
Ejemplo n.º 3
0
        private static byte[] GetTokenBytes(StreamSequenceToken token)
        {
            var bodyStream = new BinaryTokenStreamWriter();

            SerializationManager.Serialize(token, bodyStream);
            return(bodyStream.ToByteArray());
        }
Ejemplo n.º 4
0
        internal static void Serialize(object obj, BinaryTokenStreamWriter stream, Type expected)
        {
            var envelope = (RequestEnvelope)obj;

            SerializationManager.SerializeInner(envelope.Target, stream, typeof(ActorPath));
            SerializationManager.SerializeInner(MessageEnvelope.Serializer(envelope.Message), stream, typeof(byte[]));
        }
        public void AzureQueueBatchContainerV2_Serialize_IfNotNull()
        {
            var container = CreateAzureQueueBatchContainer();
            var writer    = new SerializationContext
            {
                StreamWriter = new BinaryTokenStreamWriter()
            };

            AzureQueueBatchContainerV2.Serialize(container, writer, null);
            var reader = new DeserializationContext
            {
                StreamReader = new BinaryTokenStreamReader(writer.StreamWriter.ToByteArray())
            };

            var deserialized = AzureQueueBatchContainerV2.Deserialize(typeof(AzureQueueBatchContainer), reader) as AzureQueueBatchContainerV2;

            ValidateIdenticalQueueBatchContainerButNotSame(container, deserialized);

            var streamWriter = new BinaryTokenStreamWriter();

            SerializationManager.Serialize(container, streamWriter);
            var streamReader = new BinaryTokenStreamReader(streamWriter.ToByteArray());

            deserialized = SerializationManager.Deserialize <AzureQueueBatchContainerV2>(streamReader);
            ValidateIdenticalQueueBatchContainerButNotSame(container, deserialized);
        }
Ejemplo n.º 6
0
        internal static void Serialize(object obj, BinaryTokenStreamWriter stream, Type t)
        {
            var envelope = (NotificationEnvelope)obj;

            SerializationManager.SerializeInner(envelope.Sender, stream, typeof(ActorPath));
            SerializationManager.SerializeInner(MessageEnvelope.Serializer(envelope.Message), stream, typeof(byte[]));
        }
Ejemplo n.º 7
0
        private static void VerifyUsingFallbackSerializer(object ob)
        {
            var writer = new BinaryTokenStreamWriter();

            SerializationManager.FallbackSerializer(ob, writer, ob.GetType());
            var bytes = writer.ToByteArray();

            byte[] defaultFormatterBytes;
            var    formatter = new BinaryFormatter();

            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, ob);
                stream.Flush();
                defaultFormatterBytes = stream.ToArray();
            }

            var reader   = new BinaryTokenStreamReader(bytes);
            var serToken = reader.ReadToken();

            Assert.Equal(SerializationTokenType.Fallback, serToken);
            var length = reader.ReadInt();

            Assert.Equal(length, defaultFormatterBytes.Length);
            var segment = new ArraySegment <byte>(bytes, reader.CurrentPosition, bytes.Length - reader.CurrentPosition);

            Assert.True(segment.SequenceEqual(defaultFormatterBytes));
        }
Ejemplo n.º 8
0
        public void ILSerializer_NonSerializedFields()
        {
            var input = new FieldTest
            {
                One = 1,
                Two = 2,
                NonSerializedInt = 1098
            };
            var generator   = new ILSerializerGenerator();
            var serializers = generator.GenerateSerializer(input.GetType());
            var writer      = new BinaryTokenStreamWriter();
            var context     = new SerializationContext(this.fixture.SerializationManager)
            {
                StreamWriter = writer
            };

            serializers.Serialize(input, context, input.GetType());
            var reader = new DeserializationContext(this.fixture.SerializationManager)
            {
                StreamReader = new BinaryTokenStreamReader(writer.ToByteArray())
            };
            var deserialized = (FieldTest)serializers.Deserialize(input.GetType(), reader);

            Assert.Equal(input.One, deserialized.One);
            Assert.Equal(input.Two, deserialized.Two);
            Assert.NotEqual(input.NonSerializedInt, deserialized.NonSerializedInt);
            Assert.Equal(default(int), deserialized.NonSerializedInt);
        }
Ejemplo n.º 9
0
        public static byte[] SerializeProperties(this IDictionary <string, object> properties)
        {
            var writeStream = new BinaryTokenStreamWriter();

            SerializationManager.Serialize(properties, writeStream);
            return(writeStream.ToByteArray());
        }
Ejemplo n.º 10
0
        void IMessageSerializer.Serialize(object message, BinaryTokenStreamWriter stream)
        {
            var json  = JsonConvert.SerializeObject(message, Formatting.None, settings);
            var bytes = Encoding.Default.GetBytes(json);

            SerializationManager.SerializeInner(bytes, stream, typeof(byte[]));
        }
        /// <summary>
        /// Serializes event data properties
        /// </summary>
        /// <param name="eventData"></param>
        /// <returns></returns>
        public static byte[] SerializeProperties(this EventData eventData)
        {
            var writeStream = new BinaryTokenStreamWriter();

            SerializationManager.Serialize(eventData.Properties.Where(kvp => !SkipProperties.Contains(kvp.Key)).ToList(), writeStream);
            return(writeStream.ToByteArray());
        }
Ejemplo n.º 12
0
        public void UniqueKeySerializationShouldReproduceAnIdenticalObject()
        {
            {
                var expected = UniqueKey.NewKey(Guid.NewGuid());
                BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
                writer.Write(expected);
                BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
                var actual = reader.ReadUniqueKey();
                Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #1).
            }

            {
                var kx       = random.Next().ToString(CultureInfo.InvariantCulture);
                var expected = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx);
                BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
                writer.Write(expected);
                BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
                var actual = reader.ReadUniqueKey();
                Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #2).
            }

            {
                var kx       = random.Next().ToString(CultureInfo.InvariantCulture) + new String('*', 400);
                var expected = UniqueKey.NewKey(Guid.NewGuid(), category: UniqueKey.Category.KeyExtGrain, keyExt: kx);
                BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();
                writer.Write(expected);
                BinaryTokenStreamReader reader = new BinaryTokenStreamReader(writer.ToBytes());
                var actual = reader.ReadUniqueKey();
                Assert.Equal(expected, actual); // UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #3).
            }
        }
Ejemplo n.º 13
0
        //[Benchmark]
        public object OrleansClassRoundTrip()
        {
            var writer = new BinaryTokenStreamWriter();

            this.orleansSerializer.Serialize(this.value, writer);
            return(this.orleansSerializer.Deserialize(new BinaryTokenStreamReader(writer.ToBytes())));
        }
Ejemplo n.º 14
0
        //[Benchmark]
        public object OrleansSerialize()
        {
            var writer = new BinaryTokenStreamWriter();

            this.orleansSerializer.Serialize(this.value, writer);
            return(writer);
        }
Ejemplo n.º 15
0
        internal byte[] ToByteArray()
        {
            var writer = new BinaryTokenStreamWriter();

            writer.Write(this);
            return(writer.ToByteArray());
        }
        private ILExceptionSerializerTestException TestExceptionSerialization(ILExceptionSerializerTestException expected)
        {
            var writer = new BinaryTokenStreamWriter();

            // Deep copies should be reference-equal.
            Assert.Equal(
                expected,
                SerializationManager.DeepCopyInner(expected, new SerializationContext(this.environment.SerializationManager)),
                ReferenceEqualsComparer.Instance);

            this.environment.SerializationManager.Serialize(expected, writer);
            var reader = new DeserializationContext(this.environment.SerializationManager)
            {
                StreamReader = new BinaryTokenStreamReader(writer.ToByteArray())
            };

            var actual = (ILExceptionSerializerTestException)this.environment.SerializationManager.Deserialize(null, reader.StreamReader);

            Assert.Equal(expected.BaseField.Value, actual.BaseField.Value, StringComparer.Ordinal);
            Assert.Equal(expected.SubClassField, actual.SubClassField, StringComparer.Ordinal);
            Assert.Equal(expected.OtherField.Value, actual.OtherField.Value, StringComparer.Ordinal);

            // Check for referential equality in the two fields which happened to be reference-equals.
            Assert.Equal(actual.BaseField, actual.OtherField, ReferenceEqualsComparer.Instance);

            return(actual);
        }
            public static void Serializer(object untypedInput, BinaryTokenStreamWriter stream, Type expected)
            {
                var    input = (JObject)(untypedInput);
                string str   = input.ToString();

                SerializationManager.Serialize(str, stream);
            }
Ejemplo n.º 18
0
        protected internal static void SerializeGrainReference(object obj, BinaryTokenStreamWriter stream, Type expected)
        {
            var input = (GrainReference)obj;

            stream.Write(input.GrainId);
            if (input.IsSystemTarget)
            {
                stream.Write((byte)1);
                stream.Write(input.SystemTargetSilo);
            }
            else
            {
                stream.Write((byte)0);
            }

            if (input.IsObserverReference)
            {
                input.observerId.SerializeToStream(stream);
            }

            // store as null, serialize as empty.
            var genericArg = String.Empty;

            if (input.HasGenericArgument)
            {
                genericArg = input.genericArguments;
            }
            stream.Write(genericArg);
        }
Ejemplo n.º 19
0
        public void ILSerializer_AllowCopiedFieldsToDifferFromSerializedFields()
        {
            var input = new FieldTest
            {
                One   = 1,
                Two   = 2,
                Three = 3
            };

            var generator   = new ILSerializerGenerator();
            var serializers = generator.GenerateSerializer(input.GetType(), f => f.Name != "One", f => f.Name != "Three");
            var writer      = new BinaryTokenStreamWriter();
            var context     = new SerializationContext(this.fixture.SerializationManager)
            {
                StreamWriter = writer
            };
            var copy = (FieldTest)serializers.DeepCopy(input, context);

            Assert.Equal(1, copy.One);
            Assert.Equal(2, copy.Two);
            Assert.Equal(0, copy.Three);

            serializers.Serialize(input, context, input.GetType());
            var reader = new DeserializationContext(this.fixture.SerializationManager)
            {
                StreamReader = new BinaryTokenStreamReader(writer.ToByteArray())
            };
            var deserialized = (FieldTest)serializers.Deserialize(input.GetType(), reader);

            Assert.Equal(0, deserialized.One);
            Assert.Equal(2, deserialized.Two);
            Assert.Equal(3, deserialized.Three);
        }
Ejemplo n.º 20
0
        public static byte[] SerializeProperties(this IDictionary <string, object> properties)
        {
            var writeStream = new BinaryTokenStreamWriter();

            SerializationManager.Serialize(properties.Where(kvp => !SkipProperties.Contains(kvp.Key)).ToList(), writeStream);
            return(writeStream.ToByteArray());
        }
        public void ExceptionSerializer_NestedReferenceCycle()
        {
            // Throw an exception so that is has a stack trace.
            var exception = GetNewException();
            var expected  = new Outer
            {
                SomeFunObject = exception.OtherField,
                Object        = exception,
            };

            // Create a reference cycle.
            exception.SomeObject = expected;

            var writer = new BinaryTokenStreamWriter();

            this.environment.SerializationManager.Serialize(expected, writer);
            var reader = new DeserializationContext(this.environment.SerializationManager)
            {
                StreamReader = new BinaryTokenStreamReader(writer.ToByteArray())
            };

            var actual = (Outer)this.environment.SerializationManager.Deserialize(null, reader.StreamReader);

            Assert.Equal(expected.Object.BaseField.Value, actual.Object.BaseField.Value, StringComparer.Ordinal);
            Assert.Equal(expected.Object.SubClassField, actual.Object.SubClassField, StringComparer.Ordinal);
            Assert.Equal(expected.Object.OtherField.Value, actual.Object.OtherField.Value, StringComparer.Ordinal);

            // Check for referential equality in the fields which happened to be reference-equals.
            Assert.Equal(actual.Object.BaseField, actual.Object.OtherField, ReferenceEqualsComparer.Instance);
            Assert.Equal(actual, actual.Object.SomeObject, ReferenceEqualsComparer.Instance);
            Assert.Equal(actual.SomeFunObject, actual.Object.OtherField, ReferenceEqualsComparer.Instance);
        }
Ejemplo n.º 22
0
 internal uint GetUniformHashCode()
 {
     // Disabling this ReSharper warning; hashCache is a logically read-only variable, so accessing them in GetHashCode is safe.
     // ReSharper disable NonReadonlyFieldInGetHashCode
     if (uniformHashCache == 0)
     {
         JenkinsHash jenkinsHash = JenkinsHash.Factory.GetHashGenerator();
         uint        n;
         if (HasKeyExt && KeyExt != null)
         {
             var writer = new BinaryTokenStreamWriter();
             writer.Write(this);
             byte[] bytes = writer.ToByteArray();
             writer.ReleaseBuffers();
             n = jenkinsHash.ComputeHash(bytes);
         }
         else
         {
             n = jenkinsHash.ComputeHash(TypeCodeData, N0, N1);
         }
         // Unchecked is required because the Jenkins hash is an unsigned 32-bit integer,
         // which we need to convert to a signed 32-bit integer.
         uniformHashCache = n;
     }
     return(uniformHashCache);
     // ReSharper restore NonReadonlyFieldInGetHashCode
 }
Ejemplo n.º 23
0
        //[Benchmark]
        public SimpleStruct OrleansStructRoundTrip()
        {
            var writer = new BinaryTokenStreamWriter();

            this.orleansSerializer.Serialize(this.structValue, writer);
            return((SimpleStruct)this.orleansSerializer.Deserialize(new BinaryTokenStreamReader(writer.ToBytes())));
        }
Ejemplo n.º 24
0
 private static byte[] GetTokenBytes(SerializationManager serializationManager, StreamSequenceToken token)
 {
     var bodyStream = new BinaryTokenStreamWriter();
     serializationManager.Serialize(token, bodyStream);
     var result = bodyStream.ToByteArray();
     bodyStream.ReleaseBuffers();
     return result;
 }
        internal static void SerializeGrainCancellationToken(object obj, BinaryTokenStreamWriter stream, Type expected)
        {
            var ctw      = (GrainCancellationToken)obj;
            var canceled = ctw.CancellationToken.IsCancellationRequested;

            stream.Write(canceled);
            stream.Write(ctw.Id);
        }
Ejemplo n.º 26
0
        private static void Serialize(object input, BinaryTokenStreamWriter stream, Type expected)
        {
            SerializeCounter++;
            var obj = input as ClassWithCustomSerializer;

            stream.Write(obj.IntProperty);
            stream.Write(obj.StringProperty);
        }
Ejemplo n.º 27
0
 public override void Serialize(object message, BinaryTokenStreamWriter stream)
 {
     using (var ms = new MemoryStream())
     {
         new BinaryFormatter().Serialize(ms, message);
         SerializationManager.SerializeInner(ms.ToArray(), stream, typeof(byte[]));
     }
 }
Ejemplo n.º 28
0
        public ComplexTypeBenchmarks()
        {
            _orleansSerializer = new ClientBuilder()
                                 .ConfigureDefaults()
                                 .UseLocalhostClustering()
                                 .ConfigureServices(s => s.ToList().ForEach(r =>
            {
                if (r.ServiceType == typeof(IConfigurationValidator))
                {
                    _ = s.Remove(r);
                }
            }))
                                 .Configure <ClusterOptions>(o => o.ClusterId = o.ServiceId = "test")
                                 .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(SimpleClass).Assembly).WithCodeGeneration())
                                 .Build().ServiceProvider.GetRequiredService <SerializationManager>();
            var services = new ServiceCollection();

            _ = services
                .AddHagar(hagar => hagar.AddISerializableSupport().AddAssembly(typeof(Program).Assembly));
            var serviceProvider = services.BuildServiceProvider();

            _hagarSerializer  = serviceProvider.GetRequiredService <Serializer <ComplexClass> >();
            _structSerializer = serviceProvider.GetRequiredService <Serializer <SimpleStruct> >();
            _sessionPool      = serviceProvider.GetRequiredService <SerializerSessionPool>();
            _value            = new ComplexClass
            {
                BaseInt = 192,
                Int     = 501,
                String  = "bananas",
                //Array = Enumerable.Range(0, 60).ToArray(),
                //MultiDimensionalArray = new[,] {{0, 2, 4}, {1, 5, 6}}
            };
            _value.AlsoSelf = _value.BaseSelf = _value.Self = _value;

            _structValue = new SimpleStruct
            {
                Int  = 42,
                Bool = true,
                Guid = Guid.NewGuid()
            };
            _session = _sessionPool.GetSession();
            var writer = HagarBuffer.CreateWriter(_session);

            _hagarSerializer.Serialize(_value, ref writer);
            var bytes = new byte[writer.Output.GetMemory().Length];

            writer.Output.GetReadOnlySequence().CopyTo(bytes);
            _hagarBytes = new ReadOnlySequence <byte>(bytes);
            HagarBuffer.Reset();

            var writer2 = new BinaryTokenStreamWriter();

            _orleansSerializer.Serialize(_value, writer2);
            _orleansBytes = writer2.ToBytes();

            _readBytesLength = Math.Min(bytes.Length, _orleansBytes.Sum(x => x.Count));
        }
Ejemplo n.º 29
0
        public T RoundTripSerialization <T>(T source)
        {
            BinaryTokenStreamWriter writer = new BinaryTokenStreamWriter();

            SerializationManager.Serialize(source, writer);
            T output = (T)SerializationManager.Deserialize(new BinaryTokenStreamReader(writer.ToByteArray()));

            return(output);
        }
Ejemplo n.º 30
0
        private uint GetUniformHashCode(JenkinsHash jenkinsHash, int extraBit)
        {
            var writer = new BinaryTokenStreamWriter();

            writer.Write(this);
            writer.Write(extraBit);
            byte[] bytes = writer.ToByteArray();
            return(jenkinsHash.ComputeHash(bytes));
        }