예제 #1
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Test.Interfaces.PersonalAttributes input = ((Test.Interfaces.PersonalAttributes)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.FirstName, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Gender, stream, typeof(GenderType));
     Orleans.Serialization.SerializationManager.SerializeInner(input.LastName, stream, typeof(String));
 }
예제 #2
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     HrGrainInterfaces.GreetingData input = ((HrGrainInterfaces.GreetingData)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Count, stream, typeof(int));
     Orleans.Serialization.SerializationManager.SerializeInner(input.From, stream, typeof(long));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Message, stream, typeof(string));
 }
예제 #3
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     IoT.GrainInterfaces.TemperatureReading input = ((IoT.GrainInterfaces.TemperatureReading)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.DeviceId, stream, typeof(Int64));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Time, stream, typeof(DateTime));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Value, stream, typeof(Double));
 }
예제 #4
0
        /// <summary>
        /// Serializes an object to a binary stream
        /// </summary>
        /// <param name="item">The object to serialize</param>
        /// <param name="writer">The <see cref="BinaryTokenStreamWriter"/></param>
        /// <param name="expectedType">The type the deserializer should expect</param>
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (item == null)
            {
                writer.WriteNull();
                return;
            }

            var typeHandle = item.GetType().TypeHandle;
            var serializer = GetSerializer(typeHandle);

            if (serializer == null)
            {
                LogWarning(2, "no serializer found for type {0}", item.GetType());
                throw new ArgumentOutOfRangeException("no serializer provided for the selected type", "untypedInput");
            }

            var outputStream = OutputStream.Create(writer);
            var bondWriter   = new BondBinaryWriter(outputStream);

            serializer.Serialize(item, bondWriter);
        }
예제 #5
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Orleans.Runtime.TickStatus input = ((Orleans.Runtime.TickStatus)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.CurrentTickTime, stream, typeof(System.DateTime));
     Orleans.Serialization.SerializationManager.SerializeInner(input.FirstTickTime, stream, typeof(System.DateTime));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Period, stream, typeof(System.TimeSpan));
 }
예제 #6
0
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (item == null)
            {
                writer.WriteNull();
                return;
            }

            var formatter = new BinaryFormatter();

            byte[] bytes;
            using (var memoryStream = new MemoryStream())
            {
                formatter.Serialize(memoryStream, item);
                memoryStream.Flush();
                bytes = memoryStream.ToArray();
            }

            writer.Write(bytes.Length);
            writer.Write(bytes);
        }
예제 #7
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 copy = (FieldTest)serializers.DeepCopy(input);
            Assert.Equal(1, copy.One);
            Assert.Equal(2, copy.Two);
            Assert.Equal(0, copy.Three);

            var writer = new BinaryTokenStreamWriter();
            serializers.Serialize(input, writer, input.GetType());
            var reader = 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);
        }
예제 #8
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Orleans.EventSourcing.SimpleInterface.TransferTransactionInfo input = ((Orleans.EventSourcing.SimpleInterface.TransferTransactionInfo)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Amount, stream, typeof(decimal));
     Orleans.Serialization.SerializationManager.SerializeInner(input.FromAccountId, stream, typeof(System.Guid));
     Orleans.Serialization.SerializationManager.SerializeInner(input.ToAccountId, stream, typeof(System.Guid));
 }
예제 #9
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     OrleansInterfaces.GrainInformation input = ((OrleansInterfaces.GrainInformation)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.DeviceId, stream, typeof(string));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Time, stream, typeof(System.DateTime));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Value, stream, typeof(string));
 }
예제 #10
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     FDD.OrleansGPSTracker.GrainInterfaces.DeviceInfo input = ((FDD.OrleansGPSTracker.GrainInterfaces.DeviceInfo)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Id, stream, typeof(System.Guid));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Latitude, stream, typeof(double));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Longitude, stream, typeof(double));
 }
예제 #11
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);
 }
예제 #12
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Orleans.Samples.ClassScheduler.Data.ClassInfo input = ((Orleans.Samples.ClassScheduler.Data.ClassInfo)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Name, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Subject, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Teacher, stream, typeof(Guid));
 }
예제 #13
0
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (item == null)
            {
                writer.WriteNull();
                return;
            }

            var formatter = new BinaryFormatter();
            byte[] bytes;
            using (var memoryStream = new MemoryStream())
            {
                formatter.Serialize(memoryStream, item);
                memoryStream.Flush();
                bytes = memoryStream.ToArray();
            }
            
            writer.Write(bytes.Length);
            writer.Write(bytes);
        }
예제 #14
0
        private void ReserializeFallback(RemoteNonDeserializableException fallbackException, ISerializationContext outerContext)
        {
            var outerWriter = outerContext.StreamWriter;

            // Write the type name directly.
            var key = new TypeSerializer.TypeKey(fallbackException.OriginalTypeName);

            TypeSerializer.WriteTypeKey(key, outerWriter);

            // Create a nested context which will be written to the outer context at an int-length offset from the current position.
            // This is because the inner context will be copied with a length prefix to the outer context.
            var innerWriter  = new BinaryTokenStreamWriter();
            var innerContext = outerContext.CreateNestedContext(sizeof(int), innerWriter);

            // Serialize the only accepted fields from the base Exception class.
            this.fallbackBaseExceptionSerializer.Serialize(fallbackException, innerContext, null);

            // Write the length of the serialized exception, then write the serialized bytes.
            var additionalDataLength = fallbackException.AdditionalData?.Length ?? 0;

            outerWriter.Write(innerWriter.CurrentOffset + additionalDataLength);
            outerWriter.Write(innerWriter.ToBytes());

            if (additionalDataLength > 0)
            {
                outerWriter.Write(fallbackException.AdditionalData);
            }
        }
예제 #15
0
        public void Serialize(object item, ISerializationContext outerContext, Type expectedType)
        {
            var outerWriter = outerContext.StreamWriter;

            var actualType = item.GetType();

            // To support loss-free serialization where possible, instances of the fallback exception type are serialized in a
            // semi-manual fashion.
            var fallbackException = item as RemoteNonDeserializableException;

            if (fallbackException != null)
            {
                this.ReserializeFallback(fallbackException, outerContext);
                return;
            }

            // Write the concrete type directly.
            this.typeSerializer.WriteNamedType(actualType, outerWriter);

            // Create a nested context which will be written to the outer context at an int-length offset from the current position.
            // This is because the inner context will be copied with a length prefix to the outer context.
            var innerWriter  = new BinaryTokenStreamWriter();
            var innerContext = outerContext.CreateNestedContext(position: outerContext.CurrentOffset + sizeof(int), writer: innerWriter);

            // Serialize the exception itself.
            var methods = this.GetSerializerMethods(actualType);

            methods.Serialize(item, innerContext, null);

            // Write the serialized exception to the output stream.
            outerContext.StreamWriter.Write(innerWriter.CurrentOffset);
            outerContext.StreamWriter.Write(innerWriter.ToBytes());
        }
예제 #16
0
 public static ISerializationContext CreateNestedContext(
     this ISerializationContext context,
     int position,
     BinaryTokenStreamWriter writer)
 {
     return(new SerializationContext.NestedSerializationContext(context, position, writer));
 }
예제 #17
0
        /// <summary>
        /// Serializes an object to a binary stream
        /// </summary>
        /// <param name="item">The object to serialize</param>
        /// <param name="writer">The <see cref="BinaryTokenStreamWriter"/></param>
        /// <param name="expectedType">The type the deserializer should expect</param>
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (item == null)
            {
                // Special handling for null value. 
                // Since in this ProtobufSerializer we are usualy writing the data lengh as 4 bytes
                // we also have to write the Null object as 4 bytes lengh of zero.
                writer.Write(0);
                return;
            }

            IMessage iMessage = item as IMessage;
            if (iMessage == null)
            {
                throw new ArgumentException("The provided item for serialization in not an instance of " + typeof(IMessage), "item");
            }
            // The way we write the data is potentially in-efficinet, 
            // since we are first writing to ProtoBuff's internal CodedOutputStream
            // and then take its internal byte[] and write it into out own BinaryTokenStreamWriter.
            // Writing byte[] to BinaryTokenStreamWriter may sometimes copy the byte[] and sometimes just append ass ArraySegment without copy.
            // In the former case it will be a secodnd copy.
            // It would be more effecient to write directly into BinaryTokenStreamWriter
            // but protobuff does not currently support writing directly into a given arbitary stream
            // (it does support System.IO.Steam but BinaryTokenStreamWriter is not compatible with System.IO.Steam).
            // Alternatively, we could force to always append to BinaryTokenStreamWriter, but that could create a lot of small ArraySegments.
            // The plan is to ask the ProtoBuff team to add support for some "InputStream" interface, like Bond does.
            byte[] outBytes = iMessage.ToByteArray();
            writer.Write(outBytes.Length);
            writer.Write(outBytes);
        }
예제 #18
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.AreEqual(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.AreEqual(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.AreEqual(expected, actual, "UniqueKey.Serialize() and UniqueKey.Deserialize() failed to reproduce an identical object (case #3).");
            }
        }
예제 #19
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Example.InventoryItemDetails input = ((Example.InventoryItemDetails)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Active, stream, typeof(bool));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Name, stream, typeof(string));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Total, stream, typeof(int));
 }
예제 #20
0
        private void WriteNamedType(Type type, BinaryTokenStreamWriter writer)
        {
            var key = this.typeCache.GetOrAdd(type, t => new TypeKey(Encoding.UTF8.GetBytes(t.AssemblyQualifiedName)));

            writer.Write(key.HashCode);
            writer.Write((ushort)key.TypeName.Length);
            writer.Write(key.TypeName);
        }
예제 #21
0
 /// <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);
     var result = writeStream.ToByteArray();
     writeStream.ReleaseBuffers();
     return result;
 }
예제 #22
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     GPSTracker.Common.DeviceMessage input = ((GPSTracker.Common.DeviceMessage)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.DeviceId, stream, typeof(Guid));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Latitude, stream, typeof(Double));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Longitude, stream, typeof(Double));
     Orleans.Serialization.SerializationManager.SerializeInner(input.MessageId, stream, typeof(Int32));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Timestamp, stream, typeof(DateTime));
 }
예제 #23
0
        internal static OutputStream Create(BinaryTokenStreamWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            return(new OutputStream(writer));
        }
예제 #24
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     GPSTracker.Common.Device input = ((GPSTracker.Common.Device)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Description, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.DeviceId, stream, typeof(Guid));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Direction, stream, typeof(Double));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Lat, stream, typeof(Double));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Lon, stream, typeof(Double));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Speed, stream, typeof(Double));
 }
예제 #25
0
        public static void VerifyUsingFallbackSerializer(object ob)
        {
            var writer = new BinaryTokenStreamWriter();
            SerializationManager.FallbackSerializer(ob, writer, ob.GetType());
            var bytes = writer.ToByteArray();

            var reader = new BinaryTokenStreamReader(bytes);
            var serToken = reader.ReadToken();
            Assert.Equal(SerializationTokenType.Fallback, serToken);
        }
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Kirnau.Social.TwitterGrainInterfaces.Totals input = ((Kirnau.Social.TwitterGrainInterfaces.Totals)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Hashtag, stream, typeof(string));
     Orleans.Serialization.SerializationManager.SerializeInner(input.LastTweet, stream, typeof(string));
     Orleans.Serialization.SerializationManager.SerializeInner(input.LastUpdated, stream, typeof(System.DateTime));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Negative, stream, typeof(int));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Positive, stream, typeof(int));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Total, stream, typeof(int));
 }
예제 #27
0
        /// <summary>
        /// Serialize the event sequence token.
        /// </summary>
        /// <param name="untypedInput">The object to serialize.</param>
        /// <param name="writer">The writer to write the binary stream to.</param>
        /// <param name="expected">The expected type.</param>
        public static void Serialize(object untypedInput, BinaryTokenStreamWriter writer, Type expected)
        {
            var typed = untypedInput as EventSequenceTokenV2;
            if (typed == null)
            {
                writer.WriteNull();
                return;
            }

            writer.Write(typed.SequenceNumber);
            writer.Write(typed.EventIndex);
        }
예제 #28
0
        /// <summary>
        /// Tries to serialize an item.
        /// </summary>
        /// <param name="item">The instance of the object being serialized</param>
        /// <param name="writer">The writer used for serialization</param>
        /// <param name="expectedType">The type that the deserializer will expect</param>
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (item == null)
            {
                writer.WriteNull();
                return;
            }

            var actualType = item.GetType();
            this.WriteType(actualType, expectedType, writer);
            this.serializers.Get(actualType).Serialize(item, writer, expectedType);
        }
 public void EventSequenceTokenV2_Serialize_IfNotNull()
 {
     var writer = new BinaryTokenStreamWriter();
     var token = new EventSequenceTokenV2(long.MaxValue, int.MaxValue);
     EventSequenceTokenV2.Serialize(token, writer, null);
     var reader = new BinaryTokenStreamReader(writer.ToByteArray());
     var deserialized = EventSequenceTokenV2.Deserialize(typeof(EventSequenceTokenV2), reader) as EventSequenceTokenV2;
     Assert.NotNull(deserialized);
     Assert.NotSame(token, deserialized);
     Assert.Equal(token.EventIndex, deserialized.EventIndex);
     Assert.Equal(token.SequenceNumber, deserialized.SequenceNumber);
 }
예제 #30
0
 private void WriteType(Type actualType, Type expectedType, BinaryTokenStreamWriter writer)
 {
     if (actualType == expectedType)
     {
         writer.Write((byte)SerializationTokenType.ExpectedType);
     }
     else
     {
         writer.Write((byte)SerializationTokenType.NamedType);
         writer.Write(actualType.AssemblyQualifiedName);
     }
 }
예제 #31
0
 private void WriteType(Type actualType, Type expectedType, BinaryTokenStreamWriter writer)
 {
     if (actualType == expectedType)
     {
         writer.Write((byte)SerializationTokenType.ExpectedType);
     }
     else
     {
         writer.Write((byte)SerializationTokenType.NamedType);
         this.WriteNamedType(actualType, writer);
     }
 }
예제 #32
0
        /// <summary>
        /// Creates a deep copy of an object
        /// </summary>
        /// <param name="source">The source object to be copy</param>
        /// <returns>The copy that was created</returns>
        public object DeepCopy(object source)
        {
            if (source == null)
            {
                return null;
            }

            var writer = new BinaryTokenStreamWriter();
            Serialize(source, writer, source.GetType());
            var retVal = Deserialize(source.GetType(), new BinaryTokenStreamReader(writer.ToByteArray()));
            return retVal;
        }
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     EventJournal.Event input = ((EventJournal.Event)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.AdditionalData, stream, typeof(System.Collections.Generic.IDictionary <System.String, Newtonsoft.Json.Linq.JToken>));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Arguments, stream, typeof(object[]));
     Orleans.Serialization.SerializationManager.SerializeInner(input.CorrelationId, stream, typeof(System.Guid));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Extras, stream, typeof(System.Collections.Generic.Dictionary <System.String, System.Object>));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Id, stream, typeof(long));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Time, stream, typeof(System.DateTime));
     Orleans.Serialization.SerializationManager.SerializeInner(input.To, stream, typeof(EventJournal.Address));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Type, stream, typeof(string));
     Orleans.Serialization.SerializationManager.SerializeInner(input.UserId, stream, typeof(System.Nullable <System.Guid>));
 }
예제 #34
0
        internal static void Serialize(object obj, BinaryTokenStreamWriter stream, Type unused)
        {
            var envelope = (ResponseEnvelope)obj;

            if (envelope.Result == null)
            {
                stream.Write(ResultToken.Null);
                return;
            }

            stream.Write(ResultToken.Some);
            MessageEnvelope.Serializer.Serialize(envelope.Result, stream);
        }
예제 #35
0
        internal static object Reserialize(IMessageSerializer serializer, object message)
        {
            if (serializer == null)
                return message;

            var writer = new BinaryTokenStreamWriter();
            serializer.Serialize(message, writer);

            var bytes = writer.ToByteArray();
            var reader = new BinaryTokenStreamReader(bytes);

            return serializer.Deserialize(reader);
        }
예제 #36
0
        /// <summary>
        /// Tries to serialize an item.
        /// </summary>
        /// <param name="item">The instance of the object being serialized</param>
        /// <param name="writer">The writer used for serialization</param>
        /// <param name="expectedType">The type that the deserializer will expect</param>
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (item == null)
            {
                writer.WriteNull();
                return;
            }

            var actualType = item.GetType();

            this.WriteType(actualType, expectedType, writer);
            this.serializers.GetOrAdd(actualType, this.generateSerializer).Methods.Serialize(item, writer, expectedType);
        }
예제 #37
0
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Microsoft.AspNet.SignalR.Messaging.Message input = ((Microsoft.AspNet.SignalR.Messaging.Message)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.CommandId, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Encoding, stream, typeof(Encoding));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Filter, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.IsAck, stream, typeof(Boolean));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Key, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.MappingId, stream, typeof(UInt64));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Source, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.StreamIndex, stream, typeof(Int32));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Value, stream, typeof(ArraySegment <Byte>));
     Orleans.Serialization.SerializationManager.SerializeInner(input.WaitForAck, stream, typeof(Boolean));
 }
예제 #38
0
        /// <summary>
        /// Creates a deep copy of an object
        /// </summary>
        /// <param name="source">The source object to be copy</param>
        /// <returns>The copy that was created</returns>
        public object DeepCopy(object source)
        {
            if (source == null)
            {
                return(null);
            }

            var writer = new BinaryTokenStreamWriter();

            Serialize(source, writer, source.GetType());
            var retVal = Deserialize(source.GetType(), new BinaryTokenStreamReader(writer.ToByteArray()));

            return(retVal);
        }
        public void AzureQueueBatchContainerV2_Serialize_IfNotNull()
        {
            var container = CreateAzureQueueBatchContainer();
            var writer = new BinaryTokenStreamWriter();
            AzureQueueBatchContainerV2.Serialize(container, writer, null);
            var reader = new BinaryTokenStreamReader(writer.ToByteArray());
            var deserialized = AzureQueueBatchContainerV2.Deserialize(typeof(AzureQueueBatchContainer), reader) as AzureQueueBatchContainerV2;
            ValidateIdenticalQueueBatchContainerButNotSame(container, deserialized);

            writer = new BinaryTokenStreamWriter();
            SerializationManager.Serialize(container, writer);
            reader = new BinaryTokenStreamReader(writer.ToByteArray());
            deserialized = SerializationManager.Deserialize<AzureQueueBatchContainerV2>(reader);
            ValidateIdenticalQueueBatchContainerButNotSame(container, deserialized);
        }
예제 #40
0
        /// <summary>
        /// Serializes an object to a binary stream
        /// </summary>
        /// <param name="item">The object to serialize</param>
        /// <param name="writer">The <see cref="BinaryTokenStreamWriter"/></param>
        /// <param name="expectedType">The type the deserializer should expect</param>
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (item == null)
            {
                writer.WriteNull();
                return;
            }

            var str = JsonConvert.SerializeObject(item, expectedType, defaultSettings);

            writer.Write(str);
        }
        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);
        }
        public void EventSequenceTokenV2_DeepCopy_IfNotNull()
        {
            var token = new EventSequenceTokenV2(long.MaxValue, int.MaxValue);
            var copy = EventSequenceTokenV2.DeepCopy(token) as EventSequenceToken;
            Assert.NotNull(copy);
            Assert.NotSame(token, copy);
            Assert.Equal(token.EventIndex, copy.EventIndex);
            Assert.Equal(token.SequenceNumber, copy.SequenceNumber);

            var writer = new BinaryTokenStreamWriter();
            SerializationManager.Serialize(token, writer);
            var bytes = writer.ToByteArray();

            var reader = new BinaryTokenStreamReader(bytes);
            copy = SerializationManager.Deserialize(reader) as EventSequenceToken;
            Assert.NotNull(copy);
            Assert.NotSame(token, copy);
            Assert.Equal(token.EventIndex, copy.EventIndex);
            Assert.Equal(token.SequenceNumber, copy.SequenceNumber);
        }
        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));
        }
예제 #44
0
        /// <inheritdoc />
        public object DeepCopy(object source, ICopyContext context)
        {
            if (source == null)
            {
                return null;
            }

            var outputWriter = new BinaryTokenStreamWriter();
            var serializationContext = new SerializationContext(context.GetSerializationManager())
            {
                StreamWriter = outputWriter
            };

            Serialize(source, serializationContext, source.GetType());
            var deserializationContext = new DeserializationContext(context.GetSerializationManager())
            {
                StreamReader = new BinaryTokenStreamReader(outputWriter.ToBytes())
            };

            var retVal = Deserialize(source.GetType(), deserializationContext);
            outputWriter.ReleaseBuffers();
            return retVal;
        }
        /// <summary>
        /// Serializes an object to a binary stream
        /// </summary>
        /// <param name="item">The object to serialize</param>
        /// <param name="writer">The <see cref="BinaryTokenStreamWriter"/></param>
        /// <param name="expectedType">The type the deserializer should expect</param>
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (item == null)
            {
                // Special handling for null value.
                // Since in this ProtobufSerializer we are usualy writing the data lengh as 4 bytes
                // we also have to write the Null object as 4 bytes lengh of zero.
                writer.Write(0);
                return;
            }

            IMessage iMessage = item as IMessage;

            if (iMessage == null)
            {
                throw new ArgumentException("The provided item for serialization in not an instance of " + typeof(IMessage), "item");
            }
            // The way we write the data is potentially in-efficinet,
            // since we are first writing to ProtoBuff's internal CodedOutputStream
            // and then take its internal byte[] and write it into out own BinaryTokenStreamWriter.
            // Writing byte[] to BinaryTokenStreamWriter may sometimes copy the byte[] and sometimes just append ass ArraySegment without copy.
            // In the former case it will be a secodnd copy.
            // It would be more effecient to write directly into BinaryTokenStreamWriter
            // but protobuff does not currently support writing directly into a given arbitary stream
            // (it does support System.IO.Steam but BinaryTokenStreamWriter is not compatible with System.IO.Steam).
            // Alternatively, we could force to always append to BinaryTokenStreamWriter, but that could create a lot of small ArraySegments.
            // The plan is to ask the ProtoBuff team to add support for some "InputStream" interface, like Bond does.
            byte[] outBytes = iMessage.ToByteArray();
            writer.Write(outBytes.Length);
            writer.Write(outBytes);
        }
예제 #46
0
        public void Serialize_CustomSerializer()
        {
            var original = new ClassWithCustomSerializer() { IntProperty = -3, StringProperty = "Goodbye" };
            var writeStream = new BinaryTokenStreamWriter();
            SerializationManager.Serialize(original, writeStream);
            Assert.AreEqual(1, ClassWithCustomSerializer.SerializeCounter, "Custom serializer was not called");

            var readStream = new BinaryTokenStreamReader(writeStream.ToBytes());
            var obj = SerializationManager.Deserialize(readStream);
            Assert.AreEqual(1, ClassWithCustomSerializer.DeserializeCounter, "Custom deserializer was not called");
        }
예제 #47
0
 private OutputStream(BinaryTokenStreamWriter writer)
 {
     this.writer = writer;
 }
 private static byte[] GetTokenBytes(StreamSequenceToken token)
 {
     var bodyStream = new BinaryTokenStreamWriter();
     SerializationManager.Serialize(token, bodyStream);
     return bodyStream.ToByteArray();
 }
 public static void Serializer(object untypedInput, BinaryTokenStreamWriter stream, Type expected)
 {
     var input = (JObject)(untypedInput);
     string str = input.ToString();
     SerializationManager.Serialize(str, stream);
 }
예제 #50
0
        private List<ArraySegment<byte>> Serialize_Impl(out int headerLengthOut, out int bodyLengthOut)
        {
            var headerStream = new BinaryTokenStreamWriter();
            SerializationManager.SerializeMessageHeaders(Headers, headerStream);

            if (bodyBytes == null)
            {
                var bodyStream = new BinaryTokenStreamWriter();
                SerializationManager.Serialize(bodyObject, bodyStream);
                // We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
                // being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
                // serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
                // pretty high (an array allocation plus a bunch of copying).
                bodyBytes = bodyStream.ToBytes() as List<ArraySegment<byte>>;
            }

            if (headerBytes != null)
            {
                BufferPool.GlobalPool.Release(headerBytes);
            }
            headerBytes = headerStream.ToBytes() as List<ArraySegment<byte>>;
            int headerLength = headerBytes.Sum(ab => ab.Count);
            int bodyLength = bodyBytes.Sum(ab => ab.Count);

            var bytes = new List<ArraySegment<byte>>();
            bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(headerLength)));
            bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(bodyLength)));
           
            bytes.AddRange(headerBytes);
            bytes.AddRange(bodyBytes);

            if (headerLength + bodyLength > LargeMessageSizeThreshold)
            {
                logger.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}",
                    headerLength + bodyLength + LENGTH_HEADER_SIZE, headerLength, bodyLength, bytes.Count, this.ToString());
                if (logger.IsVerbose3) logger.Verbose3("Sending large message {0}", this.ToLongString());
            }

            headerLengthOut = headerLength;
            bodyLengthOut = bodyLength;
            return bytes;
        }
예제 #51
0
 public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
 {
     SerializeCalled = true;
     writer.WriteNull();
 }
예제 #52
0
            public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
            {
                TestTypeA input = ((TestTypeA)(untypedInput));

                Orleans.Serialization.SerializationManager.SerializeInner(input.Collection, stream, typeof(System.Collections.Generic.ICollection <TestTypeA>));
            }
 public static void Serializer(object untypedInput, BinaryTokenStreamWriter stream, Type expected)
 {
     byte[] buffer = Serialize(untypedInput);
     stream.Write(buffer.Length);
     stream.Write(buffer);
 }
예제 #54
0
 /// <summary>
 /// Called from generated code.
 /// </summary>
 /// <param name="stream">Stream to serialize this grain state object to.</param>
 public void SerializeTo(BinaryTokenStreamWriter stream)
 {
     var values = this.AsDictionaryInternal();
     SerializationManager.SerializeInner(values, stream, wireFormatType);
 }
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Frontend.Library.Models.PlayerInfo input = ((Frontend.Library.Models.PlayerInfo)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.PlayerName, stream, typeof(String));
     Orleans.Serialization.SerializationManager.SerializeInner(input.Strength, stream, typeof(Int32));
 }
 public static void Serializer(object untypedInput, Orleans.Serialization.BinaryTokenStreamWriter stream, System.Type expected)
 {
     Frontend.Library.Models.GameServerID input = ((Frontend.Library.Models.GameServerID)(untypedInput));
     Orleans.Serialization.SerializationManager.SerializeInner(input.ID, stream, typeof(Guid));
 }
예제 #57
0
 private static void Serialize(object input, BinaryTokenStreamWriter stream, Type expected)
 {
     SerializeWasCalled = true;
 }
예제 #58
0
        /// <summary>
        /// Serializes an object to a binary stream
        /// </summary>
        /// <param name="item">The object to serialize</param>
        /// <param name="writer">The <see cref="BinaryTokenStreamWriter"/></param>
        /// <param name="expectedType">The type the deserializer should expect</param>
        public void Serialize(object item, BinaryTokenStreamWriter writer, Type expectedType)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (item == null)
            {
                writer.WriteNull();
                return;
            }

            var str = JsonConvert.SerializeObject(item, expectedType, defaultSettings);
            writer.Write(str);
        }
예제 #59
0
        internal static OutputStream Create(BinaryTokenStreamWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            return new OutputStream(writer);
        }
 public static void Serialize(object obj, BinaryTokenStreamWriter stream, Type expected)
 {
     var str = JsonConvert.SerializeObject(obj, Settings);
     SerializationManager.Serialize(str, stream);
 }