示例#1
0
        object ReadISerializable(ReflectType ts, ulong oid, object possibleValue)
        {
#if __PCL__
            throw new PlatformNotSupportedException("PCL");
#elif __NETCORE__
            var missing = new Missing(ts);
            var list    = new List <Tuple <object, object> >();
            missing.Collection = list;
            var N = Reader.ReadVInt();
            for (int i = 0; i < N; i++)
            {
                var s = (string)Read(ReflectType.RString, null);
                var o = Read(ReflectType.RObject, null);
                list.Add(Tuple.Create <object, object>(s, o));
            }
            if (ts.Type != null)
            {
                return(possibleValue);
            }
            return(missing);
#else
            var info = new SRS.SerializationInfo(typeof(object), new SRS.FormatterConverter());
            var ctx  = new SRS.StreamingContext(SRS.StreamingContextStates.Persistence);
            var N    = (int)Reader.ReadVInt();
            for (int i = 0; i < N; i++)
            {
                var s = (string)Read(ReflectType.RString, null);
                var o = Read(ReflectType.RObject, null);
                info.AddValue(s, o);
            }
            if (ts.Type != null)
            {
                if (possibleValue != null && ts.Type.IsInstanceOf(possibleValue))
                {
                    var ctor = ts.Type.TryGetConstructors(info.GetType(), ctx.GetType()).FirstOrDefault();
                    // No FastMethod(): couldn't manage to call constructor on existing instance
                    if (ctor != null)
                    {
                        ctor.Invoke(possibleValue, new object[] { info, ctx }); // Dare to do it! Call constructor on existing instance!!
                    }
                    if (oid > 0)
                    {
                        Context.Register(oid, possibleValue);
                    }
                    return(possibleValue);
                }
                var o = ts.Type.TryConstruct(info, ctx) ?? ts.FastType.TryConstruct();
                if (oid > 0)
                {
                    Context.Register(oid, o);
                }
                return(o);
            }
            var missing = new Missing(ts);
            if (oid > 0)
            {
                Context.Register(oid, missing);
            }
            var list = new List <Tuple <object, object> >();
            missing.Collection = list;
            foreach (var kv in info)
            {
                list.Add(Tuple.Create <object, object>(kv.Name, kv.Value));
            }
            return(missing);
#endif
        }
示例#2
0
        /// <summary>
        /// Deserialize to a specific type.
        /// This call bypasses the call to ObjectType(data)
        /// and uses the object type "t".
        /// </summary>
        /// <param name="s">Stream to deserialize</param>
        /// <param name="t">Object type to be created</param>
        /// <returns></returns>
        public Object Deserialize(Stream s, Type t)
        {
            Object ret = null;
            // read one line from the stream that defines our object
            m_FirstLine = false;
            if (s.CanRead && s.Position == 0)
            {
                m_FirstLine = true;
            }
            String str = ReadLine(s);

            // local storage of the elements read from the line
            Dictionary<String, String> data
                = new Dictionary<string, string>();

            DeserializeFromString(str, m_EscapeChar
                , m_NameDelimiter, m_ValueDelimiter, ref data);
            try
            {
                if (m_StorageType == StorageType.CSV
                    && UseFirstLineAsColumnNames && m_FirstLine)
                { // create name map for this stream
                    foreach (KeyValuePair<String, String> value in data)
                    {
                        m_FirstLineColumnNames.Add(value.Value);
                    }
                    // return a copy of the name list
                    t = m_FirstLineColumnNames.GetType();
                    Type[] types = { };
                    Object[] objs = { };
                    ret = t.GetConstructor(types).Invoke(objs);
                }
                else if (t != typeof(Object))
                {
                    // create a different SerializationInfo for each object
                    SerializationInfo info
                        = new SerializationInfo(t, m_Converter);
                    // add the name/value pairs to the SerializationInfo object
                    if (m_StorageType == StorageType.NameValue)
                    {
                        foreach (KeyValuePair<String, String> value in data)
                        {
                            info.AddValue(value.Key, value.Value);
                        }
                    }
                    else if (m_StorageType == StorageType.ValueOnly
                        || m_StorageType == StorageType.CSV)
                    {
                        List<String> nameMap = ObjectNameMap(t);
                        IEnumerator<String> nameItr = null;
                        if (nameMap != null)
                        {
                            // starts before first item - MoveNext() to set at first item
                            nameItr = nameMap.GetEnumerator();
                        }
                        foreach (KeyValuePair<String, String> value in data)
                        {
                            if (nameMap != null)
                            {
                                String key = String.Empty;
                                if (nameItr.MoveNext())
                                {
                                    if (nameItr.Current != null)
                                    {
                                        key = nameItr.Current;
                                    }
                                }
                                // an empty key from the name map
                                // indicates to use the auto-generated key
                                if (key.Length > 0)
                                {
                                    info.AddValue(key, value.Value);
                                }
                                else
                                {
                                    info.AddValue(value.Key, value.Value);
                                }
                            }
                            else
                            { // use the auto-generated key
                                info.AddValue(value.Key, value.Value);
                            }
                        }
                    }

                    // call private constructor for ISerializable objects
                    Type[] types = { info.GetType(), m_Context.GetType() };
                    Object[] objs = { info, m_Context };
                    ret = t.GetConstructor(types).Invoke(objs);
                }
                else
                {
                    // no type defined by the deserialized string
                }
            }
            catch (SerializationException e)
            {
                throw e;
            }
            // return instance of new object
            return ret;
        }
示例#3
0
        /// <summary>
        /// Deserialize to a specific type.
        /// This call bypasses the call to ObjectType(data)
        /// and uses the object type "t".
        /// </summary>
        /// <param name="s">Stream to deserialize</param>
        /// <param name="t">Object type to be created</param>
        /// <returns></returns>
        public object Deserialize(Stream s, Type t)
        {
            object ret = null;
            // read one line from the stream that defines our object
            _mFirstLine = s.CanRead && s.Position == 0;
            string str = ReadLine(s);

            // local storage of the elements read from the line
            Dictionary<string, string> data
                = new Dictionary<string, string>();

            DeserializeFromString(str, Escape
                , NameDelimiter, ValueDelimiter, ref data);
            try
            {
                if (TextStorage == TextStorageType.Csv
                    && UseFirstLineAsColumnNames && _mFirstLine)
                { // create name map for this stream
                    foreach (KeyValuePair<string, string> value in data)
                    {
                        _mFirstLineColumnNames.Add(value.Value);
                    }
                    // return a copy of the name list
                    t = _mFirstLineColumnNames.GetType();
                    Type[] types = { };
                    object[] objs = { };
                    var constructorInfo = t.GetConstructor(types);
                    if (constructorInfo != null) ret = constructorInfo.Invoke(objs);
                }
                else if (t != typeof(object))
                {
                    // create a different SerializationInfo for each object
                    SerializationInfo info
                        = new SerializationInfo(t, _mConverter);
                    // add the name/value pairs to the SerializationInfo object
                    if (TextStorage == TextStorageType.NameValue)
                    {
                        foreach (KeyValuePair<string, string> value in data)
                        {
                            info.AddValue(value.Key, value.Value);
                        }
                    }
                    else if (TextStorage == TextStorageType.ValueOnly
                        || TextStorage == TextStorageType.Csv)
                    {
                        List<string> nameMap = ObjectNameMap(t);
                        IEnumerator<string> nameItr = null;
                        if (nameMap != null)
                        {
                            // starts before first item - MoveNext() to set at first item
                            nameItr = nameMap.GetEnumerator();
                        }
                        foreach (KeyValuePair<string, string> value in data)
                        {
                            if (nameMap != null)
                            {
                                string key = string.Empty;
                                if (nameItr.MoveNext())
                                {
                                    if (nameItr.Current != null)
                                    {
                                        key = nameItr.Current;
                                    }
                                }
                                // an empty key from the name map
                                // indicates to use the auto-generated key
                                info.AddValue(key.Length > 0 ? key : value.Key, value.Value);
                            }
                            else
                            { // use the auto-generated key
                                info.AddValue(value.Key, value.Value);
                            }
                        }
                    }

                    // call private constructor for ISerializable objects
                    Type[] types = { info.GetType(), _mContext.GetType() };
                    object[] objs = { info, _mContext };
                    var constructorInfo = t.GetConstructor(types);
                    if (constructorInfo != null) ret = constructorInfo.Invoke(objs);
                }
                else
                {
                    // no type defined by the deserialized string
                }
            }
            catch (SerializationException e)
            {
                throw new SerializationException(nameof(Deserialize) + "(Stream, Type)", e);
            }
            // return instance of new object
            return ret;
        }
示例#4
0
        protected Map(SerializationInfo info, StreamingContext context)
        {
            source = info.GetString("source");
              sourceType = (MapSourceType)(info.GetValue("sourceType", typeof(MapSourceType)));
              storageType = (MapStorageType)(info.GetValue("storageType", typeof(MapStorageType)));
              switch (storageType)
              {
            case MapStorageType.Inline:
              //rawData = (byte[])(info.GetValueNo("rawData", typeof(byte[])));
              var getValueNoThrowMethod = info.GetType().GetMethod("GetValueNoThrow", BindingFlags.Instance | BindingFlags.NonPublic);
              rawData = (byte[])getValueNoThrowMethod.Invoke(info, new object[] { "rawData", typeof(byte[]) });

              if (rawData != null)
              {
            // version 2.3 file format contains rawData field, create image from it
            using (var ms = new MemoryStream(rawData))
            {
              image = (Bitmap)System.Drawing.Image.FromStream(ms);
            }
              }
              else
              {
            // version 2.2 file format
            image = (Bitmap)(info.GetValue("image", typeof(Bitmap)));
              }
              break;

            case MapStorageType.Reference:
              switch (sourceType)
              {
            case MapSourceType.FileSystem:
              image = (Bitmap)System.Drawing.Image.FromFile(source);
              break;
            case MapSourceType.Url:
              image = GetImageFromUrl(source);
              break;
              }
              break;
              }
        }
示例#5
0
            private STypeInstanceProxy GetTypeInstanceProxy(object o, Type nullableType)
            {
                STypeInstanceProxy result = null;

                if (o != null)
                {
                    Type objectType = nullableType == null ? o.GetType() : nullableType;
                    if (!objectType.IsSerializable && !objectType.IsNested && !objectType.IsEnum)
                    {
                        throw new SerializationException("Type has not been marked as serializable.");
                    }

                    STypeInfo ti = GetTypeInfo(objectType);

                    bool firstTime = false;
                    long instanceId = mGenerator.GetId(o, out firstTime);
                    if (!firstTime)
                    {
                        result = mReferenceVsTypeInstances[instanceId];
                    }

                    if (result == null)
                    {
                        result = (STypeInstanceProxy)ti.Clone();

                        result.InstanceId = instanceId; //mProxyIdGenerator;
                        result.InstanceValue = o;
                        mReferenceVsTypeInstances.Add(result.InstanceId, result);

                        if (mSystemTypes.Contains(objectType))
                        {
                        }
                        else if (objectType.IsEnum)
                        {
                        }
                        else if (o is ISerializable)
                        {
                            // serializable type
                            ISurrogateSelector selector = null;
                            ISerializationSurrogate surrogate = (Selector == null ? null : Selector.GetSurrogate(objectType, this.Context, out selector));

                            SerializationInfo info = new SerializationInfo(ti.Type, new FormatterConverter());
                            if (surrogate == null)
                            {
                                ISerializable serializable = (ISerializable)o;
                                serializable.GetObjectData(info, this.Context);
                            }
                            else
                            {
                                surrogate.GetObjectData(o, info, this.Context);
                            }

                            result.SerializationInfo = info;
                            if (info.MemberCount > 0)
                            {
                                result.ArrayKeys = new List<STypeInstanceProxy>();
                                result.ArrayItems = new List<STypeInstanceProxy>();
                                string[] memberNames = (string[])info.GetType().GetProperty("MemberNames", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).GetGetMethod(true).Invoke(info, null);
                                object[] memberValues = (object[])info.GetType().GetProperty("MemberValues", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).GetGetMethod(true).Invoke(info, null);

                                for (int i = 0; i < memberNames.Length; i++)
                                {
                                    string memberName = memberNames[i];
                                    if (memberName != null)
                                    {
                                        object memberValue = memberValues[i];
                                        result.ArrayKeys.Add(GetTypeInstanceProxy(memberName, null));
                                        result.ArrayItems.Add(GetTypeInstanceProxy(memberValue, null));
                                    }
                                }
                            }
                        }
                        else if (objectType.IsGenericType && objectType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                        {
                            // a reflector nem viszi a Nullable típust
                            dynamic dn = o;
                            result.FieldVsProxy.Add("value", GetTypeInstanceProxy(dn, dn.GetType()));
                        }
                        else if (objectType.IsArray && objectType.GetArrayRank() == 1 && objectType.Equals(typeof(byte[])))
                        {
                            // a byte tömböt máshogy serializálom
                        }
                        else if (objectType.IsArray && objectType.GetArrayRank() == 1)
                        {
                            Array array = o as Array;
                            List<STypeInstanceProxy> items = new List<STypeInstanceProxy>();
                            result.ArrayItems = items;
                            CollectArrayItems(items, array, new long[objectType.GetArrayRank()]);
                        }
                        else if (objectType.IsArray && objectType.GetArrayRank() > 1)
                        {
                            // multidim array
                            Array array = o as Array;
                            List<STypeInstanceProxy> items = new List<STypeInstanceProxy>();
                            result.ArrayItems = items;
                            CollectMultiArrayItems(items, array, 0, new long[objectType.GetArrayRank()]);
                        }
                        else
                        {
                            while (objectType != typeof(object) && objectType != typeof(ValueType) &&
                                objectType != typeof(MarshalByRefObject) && objectType != typeof(MBRBase))
                            {
                                foreach (FieldInfo fi in objectType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
                                {
                                    if (!fi.IsNotSerialized)
                                    {
                                        if (objectType.IsValueType && objectType.IsAssignableFrom(fi.FieldType))
                                        {
                                            // ez a Boolean struktúránál tapasztalt végtelen ciklus kivédésére szolgál
                                            // a Boolean-ban van egy bool mező, amiben ismét van egy és ismét. Örökös körforgást el kell kerülni.
                                        }
                                        else if (fi.FieldType.IsGenericType && fi.FieldType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                                        {
                                            string name = string.Format("{0}.{1}", GetTypeInfo(objectType).TypeId.ToString(), fi.Name);
                                            result.FieldVsProxy.Add(name, GetTypeInstanceProxy(fi.GetValue(o), fi.FieldType));
                                        }
                                        else
                                        {
                                            string name = string.Format("{0}.{1}", GetTypeInfo(objectType).TypeId.ToString(), fi.Name);
                                            result.FieldVsProxy.Add(name, GetTypeInstanceProxy(fi.GetValue(o), null));
                                        }
                                    }
                                }
                                objectType = objectType.BaseType;
                            }
                            ti.SerializableFieldCounter = result.FieldVsProxy.Count;
                        }
                    }
                }
                else
                {
                    // null érték
                    if (mNullProxy == null)
                    {
                        STypeInfo ti = GetTypeInfo(typeof(Object));
                        result = (STypeInstanceProxy)ti.Clone();

                        bool firstTime = false;
                        result.InstanceId = mGenerator.GetId(result, out firstTime);
                        mReferenceVsTypeInstances.Add(result.InstanceId, result);
                        mNullProxy = result;
                    }
                    else
                    {
                        result = mNullProxy;
                    }
                }

                return result;
            }