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 void ExceptionSerializer_SimpleException()
        {
            // Throw an exception so that is has a stack trace.
            var expected = GetNewException();

            var writer = new SerializationContext
            {
                StreamWriter = new BinaryTokenStreamWriter()
            };

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

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

            var actual = (ILExceptionSerializerTestException)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);
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a deep copy of an object
        /// </summary>
        /// <param name="original">The object to create a copy of</param>
        /// <param name="context">The copy context.</param>
        /// <returns>The copy.</returns>
        public static object DeepCopy(object original, ICopyContext context)
        {
            var source = original as AzureQueueBatchContainerV2;

            if (source == null)
            {
                throw new ArgumentNullException(nameof(original));
            }

            var copy = new AzureQueueBatchContainerV2();

            context.RecordCopy(original, copy);
            var           token  = source.sequenceToken == null ? null : new EventSequenceTokenV2(source.sequenceToken.SequenceNumber, source.sequenceToken.EventIndex);
            List <object> events = null;

            if (source.events != null)
            {
                events = new List <object>(source.events.Count);
                foreach (var item in source.events)
                {
                    events.Add(SerializationManager.DeepCopyInner(item, context));
                }
            }

            var ctx = source.requestContext?.ToDictionary(kv => kv.Key, kv => SerializationManager.DeepCopyInner(kv.Value, context));

            copy.SetValues(source.StreamGuid, source.StreamNamespace, events, ctx, token);
            return(copy);
        }
Esempio n. 4
0
            public ExpressionSyntax GetGetter(ExpressionSyntax instance, bool forceAvoidCopy = false)
            {
                Expression <Action> fieldGetter = () => this.FieldInfo.GetValue(default(object));
                var getFieldExpression          =
                    fieldGetter.Invoke(this.FieldInfoExpression).AddArgumentListArguments(SF.Argument(instance));

                // If the field is the backing field for an auto-property, try to use the property directly.
                var propertyName = Regex.Match(this.FieldInfo.Name, "^<([^>]+)>.*$");

                if (propertyName.Success && this.FieldInfo.DeclaringType != null)
                {
                    var name     = propertyName.Groups[1].Value;
                    var property = this.FieldInfo.DeclaringType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public);
                    if (property != null && property.GetGetMethod() != null)
                    {
                        return(instance.Member(property.Name));
                    }
                }

                if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable())
                {
                    // Shallow-copy the field.
                    return(getFieldExpression);
                }

                // Deep-copy the field.
                Expression <Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object));

                return(SF.CastExpression(
                           this.FieldInfo.FieldType.GetTypeSyntax(),
                           deepCopyInner.Invoke().AddArgumentListArguments(SF.Argument(getFieldExpression))));
            }
Esempio n. 5
0
            /// <summary>
            /// Returns syntax for retrieving the value of this field.
            /// </summary>
            /// <param name="instance">The instance of the containing type.</param>
            /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param>
            /// <returns>Syntax for retrieving the value of this field.</returns>
            public ExpressionSyntax GetGetter(ExpressionSyntax instance, bool forceAvoidCopy = false)
            {
                Type             type;
                ExpressionSyntax getExpression;

                // If the field is the backing field for an auto-property, try to use the property directly.
                if (this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null)
                {
                    type          = this.PropertyInfo.PropertyType;
                    getExpression = instance.Member(this.PropertyInfo.Name);
                }
                // otherwise, construct a field access expression
                else
                {
                    type          = this.FieldInfo.FieldType;
                    getExpression = SF.InvocationExpression(SF.IdentifierName(this.GetterFieldName))
                                    .AddArgumentListArguments(SF.Argument(instance));
                }

                if (forceAvoidCopy || type.IsOrleansShallowCopyable())
                {
                    // Shallow-copy the field.
                    return(getExpression);
                }

                // Deep-copy the field.
                Expression <Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object));

                return(SF.CastExpression(
                           type.GetTypeSyntax(),
                           deepCopyInner.Invoke().AddArgumentListArguments(SF.Argument(getExpression))));
            }
Esempio n. 6
0
            /// <summary>
            /// Returns syntax for retrieving the value of this field, deep copying it if necessary.
            /// </summary>
            /// <param name="instance">The instance of the containing type.</param>
            /// <param name="serializationContextExpression">The expression used to retrieve the serialization context.</param>
            /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param>
            /// <returns>Syntax for retrieving the value of this field.</returns>
            public ExpressionSyntax GetGetter(ExpressionSyntax instance, ExpressionSyntax serializationContextExpression = null, bool forceAvoidCopy = false)
            {
                // Retrieve the value of the field.
                var getValueExpression = this.GetValueExpression(instance);

                // Avoid deep-copying the field if possible.
                if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable())
                {
                    // Return the value without deep-copying it.
                    return(getValueExpression);
                }

                // Addressable arguments must be converted to references before passing.
                // IGrainObserver instances cannot be directly converted to references, therefore they are not included.
                ExpressionSyntax deepCopyValueExpression;

                if (typeof(IAddressable).IsAssignableFrom(this.FieldInfo.FieldType) &&
                    this.FieldInfo.FieldType.GetTypeInfo().IsInterface &&
                    !typeof(IGrainObserver).IsAssignableFrom(this.FieldInfo.FieldType))
                {
                    var getAsReference = getValueExpression.Member(
                        (IAddressable grain) => grain.AsReference <IGrain>(),
                        this.FieldInfo.FieldType);

                    // If the value is not a GrainReference, convert it to a strongly-typed GrainReference.
                    // C#: (value == null || value is GrainReference) ? value : value.AsReference<TInterface>()
                    deepCopyValueExpression =
                        SF.ConditionalExpression(
                            SF.ParenthesizedExpression(
                                SF.BinaryExpression(
                                    SyntaxKind.LogicalOrExpression,
                                    SF.BinaryExpression(
                                        SyntaxKind.EqualsExpression,
                                        getValueExpression,
                                        SF.LiteralExpression(SyntaxKind.NullLiteralExpression)),
                                    SF.BinaryExpression(
                                        SyntaxKind.IsExpression,
                                        getValueExpression,
                                        typeof(GrainReference).GetTypeSyntax()))),
                            getValueExpression,
                            SF.InvocationExpression(getAsReference));
                }
                else
                {
                    deepCopyValueExpression = getValueExpression;
                }

                // Deep-copy the value.
                Expression <Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object), default(ICopyContext));
                var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax();

                return(SF.CastExpression(
                           typeSyntax,
                           deepCopyInner.Invoke()
                           .AddArgumentListArguments(
                               SF.Argument(deepCopyValueExpression),
                               SF.Argument(serializationContextExpression))));
            }
Esempio n. 7
0
 /// <summary>
 /// Called from generated code.
 /// </summary>
 /// <returns>Deep copy of this grain state object.</returns>
 public GrainState DeepCopy()
 {
     // NOTE: Cannot use SerializationManager.DeepCopy[Inner] functionality here without StackOverflowException!
     var values = this.AsDictionaryInternal();
     var copiedData = SerializationManager.DeepCopyInner(values) as IDictionary<string, object>;
     var copy = (GrainState)this.MemberwiseClone();
     copy.SetAllInternal(copiedData);
     return copy;
 }
            public static object DeepCopier(object original, ICopyContext context)
            {
                TestTypeA input  = (TestTypeA)original;
                TestTypeA result = new TestTypeA();

                context.RecordCopy(original, result);
                result.Collection = (ICollection <TestTypeA>)SerializationManager.DeepCopyInner(input.Collection, context);
                return(result);
            }
Esempio n. 9
0
        internal static object DeepCopier(object original, ICopyContext context)
        {
            GrainStateWithMetaDataAndETag <TView> instance = (GrainStateWithMetaDataAndETag <TView>)original;

            string etag          = (string)SerializationManager.DeepCopyInner(instance.ETag, context);
            TView  state         = (TView)SerializationManager.DeepCopyInner(instance.State, context);
            int    globalVersion = (int)SerializationManager.DeepCopyInner(instance.GlobalVersion, context);
            string writeVector   = (string)SerializationManager.DeepCopyInner(instance.WriteVector, context);

            return(new GrainStateWithMetaDataAndETag <TView>(etag, state, globalVersion, writeVector));
        }
Esempio n. 10
0
            public static object DeepCopier(object original, ICopyContext context)
            {
                AdvancedPOCO instance = (AdvancedPOCO)original;

                int a = (int)SerializationManager.DeepCopyInner(instance.A, context);
                int b = (int)SerializationManager.DeepCopyInner(instance.B, context);

                return(new AdvancedPOCO {
                    A = a, B = b
                });
            }
Esempio n. 11
0
        static private object Copy(object input, ICopyContext context)
        {
            var inputCopy = context.CheckObjectWhileCopying(input);

            if (inputCopy == null)
            {
                context.RecordCopy(input, inputCopy);
            }
            var copy = SerializationManager.DeepCopyInner(input, context);

            return(copy);
        }
Esempio n. 12
0
            public static object DeepCopier(object original, ICopyContext context)
            {
                ReportingPOCO instance = (ReportingPOCO)original;

                int a                = (int)SerializationManager.DeepCopyInner(instance.A, context);
                int b                = (int)SerializationManager.DeepCopyInner(instance.B, context);
                int copyCount        = (int)SerializationManager.DeepCopyInner(instance.CopyCount, context);
                int serializeCount   = (int)SerializationManager.DeepCopyInner(instance.SerializeCount, context);
                int deserializeCount = (int)SerializationManager.DeepCopyInner(instance.DeserializeCount, context);

                return(new ReportingPOCO {
                    A = a, B = b, CopyCount = copyCount + 1, SerializeCount = serializeCount, DeserializeCount = deserializeCount
                });
            }
Esempio n. 13
0
            /// <summary>
            /// Returns syntax for retrieving the value of this field, deep copying it if neccessary.
            /// </summary>
            /// <param name="instance">The instance of the containing type.</param>
            /// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param>
            /// <returns>Syntax for retrieving the value of this field.</returns>
            public ExpressionSyntax GetGetter(ExpressionSyntax instance, bool forceAvoidCopy = false)
            {
                // Retrieve the value of the field.
                var getValueExpression = this.GetValueExpression(instance);

                // Avoid deep-copying the field if possible.
                if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable())
                {
                    // Return the value without deep-copying it.
                    return getValueExpression;
                }

                // Deep-copy the value.
                Expression<Action> deepCopyInner = () => SerializationManager.DeepCopyInner(default(object));
                var typeSyntax = this.FieldInfo.FieldType.GetTypeSyntax();
                return SF.CastExpression(
                    typeSyntax,
                    deepCopyInner.Invoke().AddArgumentListArguments(SF.Argument(getValueExpression)));
            }
Esempio n. 14
0
        public static object DeepCopier(object original, ICopyContext context)
        {
            var input  = (User)original;
            var result = new User();

            // Record 'result' as a copy of 'input'. Doing this immediately after construction allows for
            // data structures which have cyclic references or duplicate references.
            // For example, imagine that 'input.BestFriend' is set to 'input'. In that case, failing to record
            // the copy before trying to copy the 'BestFriend' field would result in infinite recursion.
            context.RecordCopy(original, result);

            // Deep-copy each of the fields.
            result.BestFriend     = (User)SerializationManager.DeepCopyInner(input.BestFriend, context);
            result.NickName       = input.NickName;       // strings in .NET are immutable, so they can be shallow-copied.
            result.FavoriteNumber = input.FavoriteNumber; // ints are primitive value types, so they can be shallow-copied.
            result.BirthDate      = (DateTimeOffset)SerializationManager.DeepCopyInner(input.BirthDate, context);

            return(result);
        }
Esempio n. 15
0
            public Expression GetGetExpression(Expression instance, bool forceAvoidCopy = false)
            {
                // If the field is the backing field for an auto-property, try to use the property directly.
                if (this.PropertyInfo != null && this.PropertyInfo.GetGetMethod() != null)
                {
                    return(Expression.Property(instance, this.PropertyInfo));
                }

                if (forceAvoidCopy || this.FieldInfo.FieldType.IsOrleansShallowCopyable())
                {
                    // Shallow-copy the field.
                    return(Expression.Field(instance, this.FieldInfo));
                }

                // Deep-copy the field.
                Expression <Func <object, object> > deepCopyInner = input => SerializationManager.DeepCopyInner(input);

                return(Expression.Invoke(deepCopyInner, instance));
            }
        public ReflectedSerializationMethodInfo()
        {
            this.GetUninitializedObject = TypeUtils.Method(() => FormatterServices.GetUninitializedObject(typeof(int)));
            this.GetTypeFromHandle      = TypeUtils.Method(() => Type.GetTypeFromHandle(typeof(Type).TypeHandle));
            this.DeepCopyInner          = TypeUtils.Method(() => SerializationManager.DeepCopyInner(default(Type), default(ICopyContext)));
            this.SerializeInner         = TypeUtils.Method(() => SerializationManager.SerializeInner(default(object), default(ISerializationContext), default(Type)));
            this.DeserializeInner       = TypeUtils.Method(() => SerializationManager.DeserializeInner(default(Type), default(IDeserializationContext)));

            this.RecordObjectWhileCopying = TypeUtils.Method((ICopyContext ctx) => ctx.RecordCopy(default(object), default(object)));

            this.GetStreamFromDeserializationContext = TypeUtils.Property((IDeserializationContext ctx) => ctx.StreamReader).GetMethod;
            this.GetStreamFromSerializationContext   = TypeUtils.Property((ISerializationContext ctx) => ctx.StreamWriter).GetMethod;

            this.RecordObjectWhileDeserializing = TypeUtils.Method((IDeserializationContext ctx) => ctx.RecordObject(default(object)));
            this.SerializerDelegate             =
                TypeUtils.Method((Serializer del) => del.Invoke(default(object), default(ISerializationContext), default(Type)));
            this.DeserializerDelegate = TypeUtils.Method((Deserializer del) => del.Invoke(default(Type), default(IDeserializationContext)));
            this.DeepCopierDelegate   = TypeUtils.Method((DeepCopier del) => del.Invoke(default(object), default(ICopyContext)));
        }
Esempio n. 17
0
        /// <summary>
        /// Creates a deep copy of an object
        /// </summary>
        /// <param name="original">The object to create a copy of</param>
        /// <returns>The copy.</returns>
        public static object DeepCopy(object original)
        {
            var source = original as AzureQueueBatchContainerV2;

            if (source == null)
            {
                throw new ArgumentNullException(nameof(original));
            }

            var copy = new AzureQueueBatchContainerV2();

            SerializationContext.Current.RecordObject(original, copy);
            var token   = source.sequenceToken == null ? null : new EventSequenceTokenV2(source.sequenceToken.SequenceNumber, source.sequenceToken.EventIndex);
            var events  = source.events?.Select(SerializationManager.DeepCopyInner).ToList();
            var context = source.requestContext?.ToDictionary(kv => kv.Key, kv => SerializationManager.DeepCopyInner(kv.Value));

            copy.SetValues(source.StreamGuid, source.StreamNamespace, events, context, token);
            return(copy);
        }
Esempio n. 18
0
        public ReflectedSerializationMethodInfo()
        {
#if NETSTANDARD
            this.GetUninitializedObject = TypeUtils.Method(() => SerializationManager.GetUninitializedObjectWithFormatterServices(typeof(int)));
#else
            this.GetUninitializedObject = TypeUtils.Method(() => FormatterServices.GetUninitializedObject(typeof(int)));
#endif
            this.GetTypeFromHandle = TypeUtils.Method(() => Type.GetTypeFromHandle(typeof(int).TypeHandle));
            this.DeepCopyInner     = TypeUtils.Method(() => SerializationManager.DeepCopyInner(typeof(int)));
            this.SerializeInner    = TypeUtils.Method(() => SerializationManager.SerializeInner(default(object), default(BinaryTokenStreamWriter), default(Type)));
            this.DeserializeInner  = TypeUtils.Method(() => SerializationManager.DeserializeInner(default(Type), default(BinaryTokenStreamReader)));

            this.GetCurrentSerializationContext = TypeUtils.Property((object _) => SerializationContext.Current).GetMethod;
            this.RecordObjectWhileCopying       = TypeUtils.Method((SerializationContext ctx) => ctx.RecordObject(default(object), default(object)));

            this.GetCurrentDeserializationContext = TypeUtils.Property((object _) => DeserializationContext.Current).GetMethod;
            this.RecordObjectWhileDeserializing   = TypeUtils.Method((DeserializationContext ctx) => ctx.RecordObject(default(object)));
            this.SerializerDelegate =
                TypeUtils.Method((SerializationManager.Serializer del) => del.Invoke(default(object), default(BinaryTokenStreamWriter), default(Type)));
            this.DeserializerDelegate = TypeUtils.Method((SerializationManager.Deserializer del) => del.Invoke(default(Type), default(BinaryTokenStreamReader)));
            this.DeepCopierDelegate   = TypeUtils.Method((SerializationManager.DeepCopier del) => del.Invoke(default(object)));
        }
            /// <inheritdoc />
            public object DeepCopy(object source, ICopyContext context)
            {
                var type         = source.GetType();
                var callbacks    = _serializationCallbacks.GetReferenceTypeCallbacks(type);
                var serializable = (ISerializable)source;
                var result       = FormatterServices.GetUninitializedObject(type);

                context.RecordCopy(source, result);

                // Shallow-copy the object into the serialization info.
                var originalInfo     = new SerializationInfo(type, _formatterConverter);
                var streamingContext = new StreamingContext(StreamingContextStates.All, context);

                callbacks.OnSerializing?.Invoke(source, streamingContext);
                serializable.GetObjectData(originalInfo, streamingContext);

                // Deep-copy the serialization info.
                var copyInfo = new SerializationInfo(type, _formatterConverter);

                foreach (var item in originalInfo)
                {
                    copyInfo.AddValue(item.Name, SerializationManager.DeepCopyInner(item.Value, context));
                }
                callbacks.OnSerialized?.Invoke(source, streamingContext);
                callbacks.OnDeserializing?.Invoke(result, streamingContext);

                // Shallow-copy the serialization info into the result.
                var constructor = _constructorFactory.GetSerializationConstructorDelegate(type);

                constructor(result, copyInfo, streamingContext);
                callbacks.OnDeserialized?.Invoke(result, streamingContext);
                if (result is IDeserializationCallback callback)
                {
                    callback.OnDeserialization(context);
                }

                return(result);
            }
Esempio n. 20
0
        public object DeepCopy(object source, ICopyContext context)
        {
            var fooCopy = SerializationManager.DeepCopyInner(source, context);

            return(fooCopy);
        }
Esempio n. 21
0
 public object DeepCopyInner(object original)
 {
     return(SerializationManager.DeepCopyInner(original, this));
 }
Esempio n. 22
0
        public object DeepCopy(object source, ICopyContext context)
        {
            var fooCopy = SerializationManager.DeepCopyInner(source, context);

            throw new NotImplementedException();
        }