Example #1
0
        /// <summary>
        /// Copies the base objects data to the specified target object.
        /// </summary>
        /// <param name="baseObj"></param>
        /// <param name="targetObj"></param>
        /// <param name="fields"></param>
        public void CopyObjectTo <T>(T baseObj, T targetObj, IEnumerable <FieldInfo> fields = null)
        {
            if (fields == null)
            {
                Type objType = baseObj.GetType();
                if (!this.DoesUnwrapType(objType))
                {
                    return;
                }

                // IClonables
                if (baseObj is ICloneable)
                {
                    (baseObj as ICloneable).CopyDataTo(targetObj, this);
                    return;
                }

                // ISurrogate
                ISurrogate surrogate = this.GetSurrogateFor(objType);
                if (surrogate != null)
                {
                    surrogate.RealObject = baseObj;
                    surrogate.CopyDataTo(targetObj, this);
                    return;
                }

                fields = objType.GetAllFields(ReflectionHelper.BindInstanceAll);
            }
            foreach (FieldInfo f in fields)
            {
                f.SetValue(targetObj, this.RequestObjectClone(f.GetValue(baseObj)));
            }
        }
Example #2
0
 /// <summary>
 /// Adds a surrogate object that can support objects of type Type.
 /// </summary>
 /// <param name="type">Type of object this surrogate can support.</param>
 /// <param name="surrogate">The serialization surrogate object.</param>
 public void AddSurrogate(Type type, ISurrogate surrogate)
 {
     if (!_surrogates.ContainsKey(type))
     {
         _surrogates.Add(type, surrogate);
     }
 }
        /// <summary>
        /// Reads data from an STDF data stream and deserializes it into the corresponding STDF record type.
        /// </summary>
        /// <param name="stream">Stream object to read the record data from.</param>
        /// <returns></returns>
        public override object Deserialize(Stream stream)
        {
            SerializeStream = stream;
            EndOfStream     = SerializeStream.Position >= SerializeStream.Length;
            if (EndOfStream)
            {
                return(null);
            }
            ReadHeader(out ushort recordLength, out ushort recordTypeCode);
            if (SerializeStream.Position + recordLength > SerializeStream.Length)
            {
                throw new EndOfStreamException("Unexpected end of record during serialization.");
            }
            Type       recordType          = STDFFormatterServices.ConvertTypeCode(recordTypeCode);
            ISurrogate serializerSurrogate = TypeSurrogateSelector.GetSurrogate(recordType);

            if (serializerSurrogate == null)
            {
                // no surrogate to deserialize this type.  Skip to next record and return
                SerializeStream.Seek(recordLength, SeekOrigin.Current);
                //Console.WriteLine("Skipping record type " + recordType.Name);
                return(null);
            }
            ISTDFRecord record = (ISTDFRecord)STDFFormatterServices.GetUninitializedObject(recordType);

            record.RecordLength = recordLength;
            SerializationInfo info = SerializationInfo.Create(recordType, Converter);
            long startPosition     = SerializeStream.Position;

            foreach (SerializationInfoEntry field in info)
            {
                EndOfRecord = (SerializeStream.Position - startPosition) >= recordLength;
                if (EndOfRecord)
                {
                    // If end of record reached yet we still have more fields to serialize, then we can skip the rest of the record.
                    break;
                }
                if (field.ItemCountIndex >= 0)
                {
                    // Field has an item count property, so we are deserializing an array.
                    // Get the number of items to deserialize from the value that was deserialized earlier.
                    int itemCount = info.GetValue <int>((int)field.ItemCountIndex);
                    if (itemCount > 0)
                    {
                        info.SetValue(field.Index, ReadArray(field.Type.GetElementType(), itemCount));
                    }
                }
                else
                {
                    info.SetValue(field.Index, Read(field.Type));
                }
            }
            EndOfStream = SerializeStream.Position >= SerializeStream.Length;
            // Set the fields on the record
            serializerSurrogate.SetObjectData(record, info);
            return(record);
        }
Example #4
0
 /// <summary>
 /// Registers a new <see cref="Duality.Serialization.ISurrogate">Surrogate</see>.
 /// </summary>
 /// <param name="surrogate"></param>
 public void AddSurrogate(ISurrogate surrogate)
 {
     if (this.surrogates.Contains(surrogate))
     {
         return;
     }
     this.surrogates.Add(surrogate);
     this.surrogates.StableSort((s1, s2) => s1.Priority - s2.Priority);
 }
Example #5
0
        public void updateSurrogateByFunctionId(HiddenFunctionId functionId, ISurrogate surrogate)
        {
            // if there is already an surrogate we invalidate it
            if (surrogateByFunctionId.ContainsKey(functionId))
            {
                surrogateByFunctionId[functionId].invalidateByFunctionId(functionId);
            }

            surrogateByFunctionId[functionId] = surrogate;
        }
 public static SurrogateForISurrogate Convert(ISurrogate value)
 {
     if (value == null)
     {
         return(null);
     }
     return(new SurrogateForISurrogate {
         Target = ((SurrogateRef)value).Target
     });
 }
Example #7
0
        /// <summary>
        /// Writes the specified structural object, including references objects.
        /// </summary>
        /// <param name="obj">The object to write.</param>
        /// <param name="objSerializeType">The <see cref="Duality.Serialization.SerializeType"/> describing the object.</param>
        /// <param name="id">The objects id.</param>
        protected void WriteStruct(object obj, SerializeType objSerializeType, uint id = 0)
        {
            ISerializable objAsCustom  = obj as ISerializable;
            ISurrogate    objSurrogate = this.GetSurrogateFor(objSerializeType.Type);

            // Write the structs data type
            this.writer.Write(objSerializeType.TypeString);
            this.writer.Write(id);
            this.writer.Write(objAsCustom != null);
            this.writer.Write(objSurrogate != null);

            if (objSurrogate != null)
            {
                objSurrogate.RealObject = obj;
                objAsCustom             = objSurrogate.SurrogateObject;

                CustomSerialIO customIO = new CustomSerialIO();
                try { objSurrogate.WriteConstructorData(customIO); }
                catch (Exception e) { this.LogCustomSerializationError(id, objSerializeType.Type, e); }
                customIO.Serialize(this);
            }

            if (objAsCustom != null)
            {
                CustomSerialIO customIO = new CustomSerialIO();
                try { objAsCustom.WriteData(customIO); }
                catch (Exception e) { this.LogCustomSerializationError(id, objSerializeType.Type, e); }
                customIO.Serialize(this);
            }
            else
            {
                // Assure the type data layout has bee written (only once per file)
                this.WriteTypeDataLayout(objSerializeType);

                // Write omitted field bitmask
                bool[] fieldOmitted = new bool[objSerializeType.Fields.Length];
                for (int i = 0; i < fieldOmitted.Length; i++)
                {
                    fieldOmitted[i] = this.IsFieldBlocked(objSerializeType.Fields[i], obj);
                }
                this.WriteArrayData(fieldOmitted);

                // Write the structs fields
                for (int i = 0; i < objSerializeType.Fields.Length; i++)
                {
                    if (fieldOmitted[i])
                    {
                        continue;
                    }
                    this.WriteObjectData(objSerializeType.Fields[i].GetValue(obj));
                }
            }
        }
Example #8
0
        /// <summary>
        /// Writes the specified structural object, including references objects.
        /// </summary>
        /// <param name="obj">The object to write.</param>
        /// <param name="objSerializeType">The <see cref="Duality.Serialization.SerializeType"/> describing the object.</param>
        /// <param name="id">The objects id.</param>
        protected void WriteStruct(object obj, SerializeType objSerializeType, uint id = 0)
        {
            ISerializable objAsCustom  = obj as ISerializable;
            ISurrogate    objSurrogate = this.GetSurrogateFor(objSerializeType.Type);

            // Write the structs data type
            this.writer.WriteAttributeString("type", objSerializeType.TypeString);
            if (id != 0)
            {
                this.writer.WriteAttributeString("id", XmlConvert.ToString(id));
            }
            if (objAsCustom != null)
            {
                this.writer.WriteAttributeString("custom", XmlConvert.ToString(true));
            }
            if (objSurrogate != null)
            {
                this.writer.WriteAttributeString("surrogate", XmlConvert.ToString(true));
            }

            if (objSurrogate != null)
            {
                objSurrogate.RealObject = obj;
                objAsCustom             = objSurrogate.SurrogateObject;

                CustomSerialIO customIO = new CustomSerialIO(CustomSerialIO.HeaderElement);
                try { objSurrogate.WriteConstructorData(customIO); }
                catch (Exception e) { this.LogCustomSerializationError(id, objSerializeType.Type, e); }
                customIO.Serialize(this);
            }

            if (objAsCustom != null)
            {
                CustomSerialIO customIO = new CustomSerialIO(CustomSerialIO.BodyElement);
                try { objAsCustom.WriteData(customIO); }
                catch (Exception e) { this.LogCustomSerializationError(id, objSerializeType.Type, e); }
                customIO.Serialize(this);
            }
            else
            {
                // Write the structs fields
                foreach (FieldInfo field in objSerializeType.Fields)
                {
                    if (this.IsFieldBlocked(field, obj))
                    {
                        continue;
                    }
                    this.WriteObjectData(field.GetValue(obj), field.Name);
                }
            }
        }
Example #9
0
        public static ISurrogated Convert(ISurrogate surrogate, ISurrogated surrogated)
        {
            var system = BondSerializer.LocalSystem.Value;

            return(surrogate.FromSurrogate(system));
        }
Example #10
0
 public TypedActorReferenceSurrogate(ISurrogate refSurrogate) : this()
 {
     RefSurrogate = refSurrogate;
 }
Example #11
0
        private object CloneObject(object baseObj)
        {
            Type objType = baseObj.GetType();

            if (!this.DoesUnwrapType(objType))
            {
                return(baseObj);
            }

            // IClonables
            if (baseObj is ICloneable)
            {
                object copy = objType.CreateInstanceOf() ?? objType.CreateInstanceOf(true);
                if (objType.IsClass)
                {
                    this.RegisterObjectClone(baseObj, copy);
                }
                (baseObj as ICloneable).CopyDataTo(copy, this);
                return(copy);
            }

            // ISurrogate
            ISurrogate surrogate = this.GetSurrogateFor(objType);

            if (surrogate != null)
            {
                surrogate.RealObject = baseObj;
                object copy = surrogate.CreateTargetObject(this);
                if (objType.IsClass)
                {
                    this.RegisterObjectClone(baseObj, copy);
                }
                surrogate.CopyDataTo(copy, this);
                return(copy);
            }

            // Shallow types, cloned by assignment
            if (objType.IsDeepByValueType())
            {
                return(baseObj);
            }
            // Arrays
            else if (objType.IsArray)
            {
                Array baseArray = (Array)baseObj;
                Type  elemType  = objType.GetElementType();
                int   length    = baseArray.Length;
                Array copy      = Array.CreateInstance(elemType, length);
                this.RegisterObjectClone(baseObj, copy);

                bool unwrap = this.DoesUnwrapType(elemType);
                if (unwrap)
                {
                    for (int i = 0; i < length; ++i)
                    {
                        copy.SetValue(this.RequestObjectClone(baseArray.GetValue(i)), i);
                    }
                }
                else if (!elemType.IsValueType)
                {
                    for (int i = 0; i < length; ++i)
                    {
                        object obj = baseArray.GetValue(i);
                        copy.SetValue(this.GetRegisteredObjectClone(obj) ?? obj, i);
                    }
                }
                else
                {
                    baseArray.CopyTo(copy, 0);
                }

                return(copy);
            }
            // Reference types / complex objects
            else
            {
                object copy = objType.CreateInstanceOf() ?? objType.CreateInstanceOf(true);
                if (objType.IsClass)
                {
                    this.RegisterObjectClone(baseObj, copy);
                }

                this.CopyObjectTo(baseObj, copy, objType.GetAllFields(ReflectionHelper.BindInstanceAll));

                return(copy);
            }
        }
Example #12
0
 public TypedPropsSurrogate(ISurrogate propsSurrogate) : this()
 {
     PropsSurrogate = propsSurrogate;
 }
Example #13
0
 /// <summary>
 /// Creates a new instance of a query container for use in checkpointable queries.
 /// </summary>
 /// <param name="surrogate">An object that offers serialization surrogacy.</param>
 public QueryContainer(ISurrogate surrogate) => this.Surrogate = surrogate;
Example #14
0
        /// <summary>
        /// Reads a structural object, including referenced objects.
        /// </summary>
        /// <returns>The object that has been read.</returns>
        protected object ReadStruct()
        {
            // Read struct type
            string objTypeString   = this.reader.GetAttribute("type");
            string objIdString     = this.reader.GetAttribute("id");
            string customString    = this.reader.GetAttribute("custom");
            string surrogateString = this.reader.GetAttribute("surrogate");
            uint   objId           = objIdString == null ? 0 : XmlConvert.ToUInt32(objIdString);
            bool   custom          = customString != null && XmlConvert.ToBoolean(customString);
            bool   surrogate       = surrogateString != null && XmlConvert.ToBoolean(surrogateString);
            Type   objType         = this.ResolveType(objTypeString, objId);

            SerializeType objSerializeType = null;

            if (objType != null)
            {
                objSerializeType = objType.GetSerializeType();
            }

            // Retrieve surrogate if requested
            ISurrogate objSurrogate = null;

            if (surrogate && objType != null)
            {
                objSurrogate = this.GetSurrogateFor(objType);
            }

            // Construct object
            object obj = null;

            if (objType != null)
            {
                if (objSurrogate != null)
                {
                    custom = true;

                    // Set fake object reference for surrogate constructor: No self-references allowed here.
                    this.idManager.Inject(null, objId);

                    CustomSerialIO customIO = new CustomSerialIO(CustomSerialIO.HeaderElement);
                    customIO.Deserialize(this);
                    try { obj = objSurrogate.ConstructObject(customIO, objType); }
                    catch (Exception e) { this.LogCustomDeserializationError(objId, objType, e); }
                }
                if (obj == null)
                {
                    obj = objType.CreateInstanceOf();
                }
                if (obj == null)
                {
                    obj = objType.CreateInstanceOf(true);
                }
            }

            // Prepare object reference
            this.idManager.Inject(obj, objId);

            // Read custom object data
            if (custom)
            {
                CustomSerialIO customIO = new CustomSerialIO(CustomSerialIO.BodyElement);
                customIO.Deserialize(this);

                ISerializable objAsCustom;
                if (objSurrogate != null)
                {
                    objSurrogate.RealObject = obj;
                    objAsCustom             = objSurrogate.SurrogateObject;
                }
                else
                {
                    objAsCustom = obj as ISerializable;
                }

                if (objAsCustom != null)
                {
                    try { objAsCustom.ReadData(customIO); }
                    catch (Exception e) { this.LogCustomDeserializationError(objId, objType, e); }
                }
                else if (obj != null && objType != null)
                {
                    this.SerializationLog.WriteWarning(
                        "Object data (Id {0}) is flagged for custom deserialization, yet the objects Type ('{1}') does not support it. Guessing associated fields...",
                        objId,
                        Log.Type(objType));
                    this.SerializationLog.PushIndent();
                    foreach (var pair in customIO.Data)
                    {
                        this.AssignValueToField(objSerializeType, obj, pair.Key, pair.Value);
                    }
                    this.SerializationLog.PopIndent();
                }
            }
            // Red non-custom object data
            else if (!this.reader.IsEmptyElement)
            {
                // Read fields
                bool   scopeChanged;
                string fieldName;
                object fieldValue;
                while (true)
                {
                    fieldValue = this.ReadObjectData(out fieldName, out scopeChanged);
                    if (scopeChanged)
                    {
                        break;
                    }
                    this.AssignValueToField(objSerializeType, obj, fieldName, fieldValue);
                }
            }

            return(obj);
        }
 public AlienPropertyBuilder(IMember owner, IMemberBuilder parentBuilder, IProperty alienProperty)
     : base(parentBuilder, alienProperty)
 {
     _parentBuilder         = (IKeepSurrogateInstances)parentBuilder;
     _surrogatedTypeBuilder = _parentBuilder.Surrogates[owner];
 }
Example #16
0
        /// <summary>
        /// Reads a structural object, including referenced objects.
        /// </summary>
        /// <returns>The object that has been read.</returns>
        protected object ReadStruct()
        {
            // Read struct type
            string objTypeString = this.reader.ReadString();
            uint   objId         = this.reader.ReadUInt32();
            bool   custom        = this.reader.ReadBoolean();
            bool   surrogate     = this.reader.ReadBoolean();
            Type   objType       = this.ResolveType(objTypeString, objId);

            SerializeType objSerializeType = null;

            if (objType != null)
            {
                objSerializeType = objType.GetSerializeType();
            }

            // Retrieve surrogate if requested
            ISurrogate objSurrogate = null;

            if (surrogate && objType != null)
            {
                objSurrogate = this.GetSurrogateFor(objType);
            }

            // Construct object
            object obj = null;

            if (objType != null)
            {
                if (objSurrogate != null)
                {
                    custom = true;

                    // Set fake object reference for surrogate constructor: No self-references allowed here.
                    this.idManager.Inject(null, objId);

                    CustomSerialIO customIO = new CustomSerialIO();
                    customIO.Deserialize(this);
                    try { obj = objSurrogate.ConstructObject(customIO, objType); }
                    catch (Exception e) { this.LogCustomDeserializationError(objId, objType, e); }
                }
                if (obj == null)
                {
                    obj = objType.CreateInstanceOf();
                }
                if (obj == null)
                {
                    obj = objType.CreateInstanceOf(true);
                }
            }

            // Prepare object reference
            this.idManager.Inject(obj, objId);

            // Read custom object data
            if (custom)
            {
                CustomSerialIO customIO = new CustomSerialIO();
                customIO.Deserialize(this);

                ISerializable objAsCustom;
                if (objSurrogate != null)
                {
                    objSurrogate.RealObject = obj;
                    objAsCustom             = objSurrogate.SurrogateObject;
                }
                else
                {
                    objAsCustom = obj as ISerializable;
                }

                if (objAsCustom != null)
                {
                    try { objAsCustom.ReadData(customIO); }
                    catch (Exception e) { this.LogCustomDeserializationError(objId, objType, e); }
                }
                else if (obj != null && objType != null)
                {
                    this.SerializationLog.WriteWarning(
                        "Object data (Id {0}) is flagged for custom deserialization, yet the objects Type ('{1}') does not support it. Guessing associated fields...",
                        objId,
                        Log.Type(objType));
                    this.SerializationLog.PushIndent();
                    foreach (var pair in customIO.Data)
                    {
                        this.AssignValueToField(objSerializeType, obj, pair.Key, pair.Value);
                    }
                    this.SerializationLog.PopIndent();
                }
            }
            // Red non-custom object data
            else
            {
                // Determine data layout
                TypeDataLayout layout = this.ReadTypeDataLayout(objTypeString);

                // Read fields
                if (this.dataVersion <= 2)
                {
                    for (int i = 0; i < layout.Fields.Length; i++)
                    {
                        object fieldValue = this.ReadObjectData();
                        this.AssignValueToField(objSerializeType, obj, layout.Fields[i].name, fieldValue);
                    }
                }
                else if (this.dataVersion >= 3)
                {
                    bool[] fieldOmitted = new bool[layout.Fields.Length];
                    this.ReadArrayData(fieldOmitted);
                    for (int i = 0; i < layout.Fields.Length; i++)
                    {
                        if (fieldOmitted[i])
                        {
                            continue;
                        }
                        object fieldValue = this.ReadObjectData();
                        this.AssignValueToField(objSerializeType, obj, layout.Fields[i].name, fieldValue);
                    }
                }
            }

            return(obj);
        }
Example #17
0
        public static ISurrogate Convert(ISurrogated surrogated, ISurrogate surrogate)
        {
            var system = BondSerializer.LocalSystem.Value;

            return(surrogated.ToSurrogate(system));
        }
 public AlienPropertyBuilder(IMember owner, IMemberBuilder parentBuilder, IProperty alienProperty)
     : base(parentBuilder, alienProperty)
 {
     _parentBuilder = (IKeepSurrogateInstances)parentBuilder;
     _surrogatedTypeBuilder = _parentBuilder.Surrogates[owner];
 }
 public static SurrogateForISurrogate Convert(ISurrogate value)
 {
     if (value == null) return null;
     return new SurrogateForISurrogate { Target = ((SurrogateRef)value).Target };
 }
Example #20
0
 /// <summary>
 /// Unregisters an existing <see cref="Duality.Serialization.ISurrogate">Surrogate</see>.
 /// </summary>
 /// <param name="surrogate"></param>
 public void RemoveSurrogate(ISurrogate surrogate)
 {
     this.surrogates.Remove(surrogate);
 }
        /// <summary>
        /// Serializes and STDF record object to the output stream.
        /// </summary>
        /// <param name="stream">Stream object to serialized the STDF data to.</param>
        /// <param name="obj">STDF record object to serialize.</param>
        public override void Serialize(Stream stream, object obj)
        {
            Buffer.SetLength(0);
            SerializeStream = Buffer;
            EndOfStream     = false;
            EndOfRecord     = false;
            ushort recordLength = 0;

            if (obj is ISTDFRecord record)
            {
                ISurrogate typeSurrogate = TypeSurrogateSelector.GetSurrogate(record.GetType());
                if (typeSurrogate == null)
                {
                    return;
                }
                //WriteHeader(0, record.RecordType);
                //                long recordStartPosition = SerializeStream.Position;
                Type recordType        = record.GetType();
                SerializationInfo info = SerializationInfo.Create(recordType, Converter);
                typeSurrogate.GetObjectData(record, info);
                foreach (SerializationInfoEntry field in info)
                {
                    if (field.ItemCountIndex >= 0)
                    {
                        // field has an item count property, so we are serializing an array.  Get the number of items
                        // to serialize from the item count field serialized earlier (we always serialize according
                        // to the item count field rather than the array size for the array field.  Normally these are
                        // equal but it is not mandatory that they be equal).
                        int itemCount = field.ItemCountIndex != null?info.GetValue <int>((int)field.ItemCountIndex) : 0;

                        if (itemCount > 0)
                        {
                            WriteArray(field.Value, field.Type.GetElementType(), 0, itemCount);
                        }
                    }
                    else
                    {
                        WriteMember(field.Value, field.Type);
                    }
                    // For optional fields, save the position after the last field written
                    // that does not have a missing value.  Per spec, we can truncate any contiguous missing
                    // value fields from the end of the record.
                    if (!field.IsMissingValue)
                    {
                        recordLength = (ushort)(SerializeStream.Position);
                    }
                }
                //recordLength = (ushort)(lastValidPosition - recordStartPosition);
                if (recordLength != record.RecordLength)
                {
                    throw new Exception("Mismatched record length.");
                }
                record.RecordLength = recordLength;
                //SerializeStream.Seek(-(SerializeStream.Position - recordStartPosition + 4), SeekOrigin.Current);
                SerializeStream.Flush();
                SerializeStream = stream;
                WriteHeader(record.RecordLength, record.RecordType);
                //                SerializeStream.Seek(record.RecordLength, SeekOrigin.Current);
                //                SerializeStream.SetLength(SerializeStream.Position);
                Buffer.SetLength(recordLength);
                Buffer.WriteTo(stream);
                EndOfRecord = true;
            }
        }