public bool runTest()
    {
        Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer);
        int                iCountErrors    = 0;
        int                iCountTestcases = 0;
        String             strLoc          = "Loc_000oo";
        ObjectManager      objmgr1         = null;
        ISurrogateSelector isur            = null;
        StreamingContext   sc1             = new StreamingContext(StreamingContextStates.All);
        ObjectIDGenerator  objid1          = null;
        TestFixup          tstfxp1;
        Int64              iRootID;
        Int64              iChildID;
        String             strValue;
        bool               fFirstTime;

        MemberInfo[]  members = null;
        TestReference tst1;
        ThisImplementsIObjectReference tst2;

        try {
            do
            {
                strLoc   = "Loc_174cds";
                tstfxp1  = new TestFixup();
                objid1   = new ObjectIDGenerator();
                iRootID  = objid1.GetId(tstfxp1, out fFirstTime);
                strValue = "Hello World";
                iChildID = objid1.GetId(strValue, out fFirstTime);
                members  = FormatterServices.GetSerializableMembers(tstfxp1.GetType());
                objmgr1  = new ObjectManager(isur, sc1);
                objmgr1.RecordFixup(iRootID, members[0], iChildID);
                objmgr1.RegisterObject(tstfxp1, iRootID);
                objmgr1.RegisterObject(strValue, iChildID);
                iCountTestcases++;
                if (!tstfxp1.strFixupValue.Equals(strValue))
                {
                    iCountErrors++;
                    Console.WriteLine("Err_753cd! Expected value not returned, " + tstfxp1.strFixupValue + ", expected, " + strValue);
                }
                objmgr1.DoFixups();
                iCountTestcases++;
                if (!tstfxp1.strFixupValue.Equals(strValue))
                {
                    iCountErrors++;
                    Console.WriteLine("Err_90342ddvs! Expected value not returned, " + tstfxp1.strFixupValue + ", expected, " + strValue);
                }
                strLoc   = "Loc_5720xs";
                tst1     = new TestReference();
                tst2     = new ThisImplementsIObjectReference();
                objid1   = new ObjectIDGenerator();
                iRootID  = objid1.GetId(tst1, out fFirstTime);
                iChildID = objid1.GetId(tst2, out fFirstTime);
                members  = FormatterServices.GetSerializableMembers(typeof(TestReference));
                Console.WriteLine("<<" + members[0].Name + ">>");
                objmgr1 = new ObjectManager(isur, sc1);
                objmgr1.RecordFixup(iRootID, members[0], iChildID);
                objmgr1.RegisterObject(tst1, iRootID);
                objmgr1.RegisterObject(tst2, iChildID);
                try{
                    iCountTestcases++;
                    objmgr1.DoFixups();
                    iCountErrors++;
                    Console.WriteLine("Err_753fvdf! exception not thrown!!");
                }catch (SerializationException) {
                }catch (Exception ex) {
                    iCountErrors++;
                    Console.WriteLine("Err_04523cd! Unexpected exception, " + ex.ToString());
                }
            } while (false);
        } catch (Exception exc_general) {
            ++iCountErrors;
            Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy!  strLoc==" + strLoc + ", exc_general==\n" + exc_general.StackTrace);
        }
        if (iCountErrors == 0)
        {
            Console.WriteLine("paSs.   " + s_strTFPath + " " + s_strTFName + " ,iCountTestcases==" + iCountTestcases);
            return(true);
        }
        else
        {
            Console.WriteLine("FAiL!   " + s_strTFPath + " " + s_strTFName + " ,iCountErrors==" + iCountErrors + " , BugNums?: " + s_strActiveBugNums);
            return(false);
        }
    }
Exemplo n.º 2
0
 public object MapFrom1C(object source, Type type)
 {
     if (source == null || source == DBNull.Value)
     {
         return(null);
     }
     if (type == typeof(object))
     {
         if (source is MarshalByRefObject)
         {
             var typeName = GetFullName(source);
             type = mappingSource.TypeRegistry.GetType(typeName);
         }
         else
         {
             type = source.GetType();
         }
     }
     type = Nullable.GetUnderlyingType(type) ?? type;
     if (type == typeof(DateTime))
     {
         var dateTime = (DateTime)source;
         return(dateTime == nullDateTime ? null : source);
     }
     if (type == typeof(Guid))
     {
         var guid = Guid.Parse(globalContext.String(source));
         return(guid == Guid.Empty ? (object)null : guid);
     }
     if (type.IsEnum)
     {
         return(Call.IsEmpty(source) ? null : MapEnumFrom1C(type, source));
     }
     if (type == typeof(Type))
     {
         return(ConvertType(source));
     }
     if (type == typeof(Type[]))
     {
         var typesObject = ComHelpers.Invoke(source, "Типы");
         var typesCount  = Call.Количество(typesObject);
         var result      = new Type[typesCount];
         for (var i = 0; i < result.Length; i++)
         {
             var typeObject = Call.Получить(typesObject, i);
             result[i] = ConvertType(typeObject);
         }
         return(result);
     }
     if (typeof(Abstract1CEntity).IsAssignableFrom(type))
     {
         var configurationName = ConfigurationName.GetOrNull(type);
         var isEmpty           = configurationName.HasValue &&
                                 configurationName.Value.HasReference &&
                                 Call.IsEmpty(source);
         if (isEmpty)
         {
             return(null);
         }
         var result = (Abstract1CEntity)FormatterServices.GetUninitializedObject(type);
         result.Controller = new EntityController(new ComValueSource(source, this, false));
         return(result);
     }
     if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
     {
         var itemType = type.GetGenericArguments()[0];
         if (!typeof(Abstract1CEntity).IsAssignableFrom(itemType))
         {
             throw new InvalidOperationException("assertion failure");
         }
         var itemsCount = Call.Количество(source);
         var list       = ListFactory.Create(itemType, null, itemsCount);
         for (var i = 0; i < itemsCount; ++i)
         {
             list.Add(MapFrom1C(Call.Получить(source, i), itemType));
         }
         return(list);
     }
     return(source is IConvertible?Convert.ChangeType(source, type) : source);
 }
Exemplo n.º 3
0
 public void CheckTypeSecurity_Nop()
 {
     FormatterServices.CheckTypeSecurity(typeof(int), TypeFilterLevel.Full);
     FormatterServices.CheckTypeSecurity(typeof(int), TypeFilterLevel.Low);
 }
Exemplo n.º 4
0
 public static object GetEmptyObject(this Type type)
 {
     return(FormatterServices.GetUninitializedObject(type));
 }
Exemplo n.º 5
0
 public object CreateUninitialized(Type type)
 {
     return(FormatterServices.GetUninitializedObject(type));
 }
Exemplo n.º 6
0
 public object Invoke(params object[] arguments)
 {
     return(FormatterServices.GetSafeUninitializedObject(type));
 }
Exemplo n.º 7
0
        // Write constructor
        // [System.Security.SecurityCritical]  // auto-generated
        internal void InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
        {
            SerTrace.Log(this, objectInfoId, " Constructor 1 ", obj);
            this.context           = context;
            this.obj               = obj;
            this.serObjectInfoInit = serObjectInfoInit;
            ISurrogateSelector surrogateSelectorTemp;

#if  FEATURE_REMOTING
            if (RemotingServices.IsTransparentProxy(obj))
            {
                objectType = Converter.typeofMarshalByRefObject;
            }
            else
#endif
            objectType = obj.GetType();

            if (objectType.IsArray)
            {
                isArray = true;
                InitNoMembers();
                return;
            }

            InvokeSerializationBinder(binder);

            SerTrace.Log(this, objectInfoId, " Constructor 1 trace 2");

            objectWriter.ObjectManager.RegisterObject(obj);
            if (surrogateSelector != null && (serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp)) != null)
            {
                SerTrace.Log(this, objectInfoId, " Constructor 1 trace 3");
                si = new SerializationInfo(objectType, converter);
                if (!objectType.IsPrimitive)
                {
                    serializationSurrogate.GetObjectData(obj, si, context);
                }
                InitSiWrite();
            }
            else if (obj is ISerializable)
            {
                if (!objectType.IsSerializable)
                {
                    throw new SerializationException(Ssz.Runtime.Serialization.Environment.GetResourceString("Serialization_NonSerType",
                                                                                                             objectType.FullName, objectType.Assembly.FullName));
                }
                si = new SerializationInfo(objectType, converter, !FormatterServices.UnsafeTypeForwardersIsEnabled());
#if FEATURE_SERIALIZATION
                ((ISerializable)obj).GetObjectData(si, context);
#endif
                SerTrace.Log(this, objectInfoId, " Constructor 1 trace 4 ISerializable " + objectType);
                InitSiWrite();
                CheckTypeForwardedFrom(cache, objectType, binderAssemblyString);
            }
            else
            {
                SerTrace.Log(this, objectInfoId, " Constructor 1 trace 5");
                InitMemberInfo();
                CheckTypeForwardedFrom(cache, objectType, binderAssemblyString);
            }
        }
Exemplo n.º 8
0
 public static object CreateInstance(this Type type, bool uninitializedObject = true)
 {
     return(uninitializedObject ? FormatterServices.GetUninitializedObject(type) : Activator.CreateInstance(type));
 }
Exemplo n.º 9
0
 void Call_FS_1()
 {
     MemberInfo[] members = FormatterServices.GetSerializableMembers(typeof(Test));
 }
Exemplo n.º 10
0
        private T ReadFullObject <T>(int pos)
        {
            var hdr = BinaryObjectHeader.Read(Stream, pos);

            // Validate protocol version.
            BinaryUtils.ValidateProtocolVersion(hdr.Version);

            try
            {
                // Already read this object?
                object hndObj;

                if (_hnds != null && _hnds.TryGetValue(pos, out hndObj))
                {
                    return((T)hndObj);
                }

                if (hdr.IsUserType && _mode == BinaryMode.ForceBinary)
                {
                    BinaryObject portObj;

                    if (_detach)
                    {
                        Stream.Seek(pos, SeekOrigin.Begin);

                        portObj = new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
                    }
                    else
                    {
                        portObj = new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
                    }

                    T obj = _builder == null ? TypeCaster <T> .Cast(portObj) : TypeCaster <T> .Cast(_builder.Child(portObj));

                    AddHandle(pos, obj);

                    return(obj);
                }
                else
                {
                    // Find descriptor.
                    IBinaryTypeDescriptor desc;

                    if (!_descs.TryGetValue(BinaryUtils.TypeKey(hdr.IsUserType, hdr.TypeId), out desc))
                    {
                        throw new BinaryObjectException("Unknown type ID: " + hdr.TypeId);
                    }

                    // Instantiate object.
                    if (desc.Type == null)
                    {
                        throw new BinaryObjectException("No matching type found for object [typeId=" +
                                                        desc.TypeId + ", typeName=" + desc.TypeName + ']');
                    }

                    // Preserve old frame.
                    var  oldHdr       = _curHdr;
                    int  oldPos       = _curPos;
                    var  oldStruct    = _curStruct;
                    bool oldRaw       = _curRaw;
                    var  oldSchema    = _curSchema;
                    var  oldSchemaMap = _curSchemaMap;

                    // Set new frame.
                    _curHdr = hdr;
                    _curPos = pos;
                    SetCurSchema(desc);
                    _curStruct = new BinaryStructureTracker(desc, desc.ReaderTypeStructure);
                    _curRaw    = false;

                    // Read object.
                    Stream.Seek(pos + BinaryObjectHeader.Size, SeekOrigin.Begin);

                    object obj;

                    var sysSerializer = desc.Serializer as IBinarySystemTypeSerializer;

                    if (sysSerializer != null)
                    {
                        obj = sysSerializer.ReadInstance(this);
                    }
                    else
                    {
                        try
                        {
                            obj = FormatterServices.GetUninitializedObject(desc.Type);

                            // Save handle.
                            AddHandle(pos, obj);
                        }
                        catch (Exception e)
                        {
                            throw new BinaryObjectException("Failed to create type instance: " +
                                                            desc.Type.AssemblyQualifiedName, e);
                        }

                        desc.Serializer.ReadBinary(obj, this);
                    }

                    _curStruct.UpdateReaderStructure();

                    // Restore old frame.
                    _curHdr       = oldHdr;
                    _curPos       = oldPos;
                    _curStruct    = oldStruct;
                    _curRaw       = oldRaw;
                    _curSchema    = oldSchema;
                    _curSchemaMap = oldSchemaMap;

                    // Process wrappers. We could introduce a common interface, but for only 2 if-else is faster.
                    var wrappedSerializable = obj as SerializableObjectHolder;

                    if (wrappedSerializable != null)
                    {
                        return((T)wrappedSerializable.Item);
                    }

                    var wrappedDateTime = obj as DateTimeHolder;

                    if (wrappedDateTime != null)
                    {
                        return(TypeCaster <T> .Cast(wrappedDateTime.Item));
                    }

                    return((T)obj);
                }
            }
            finally
            {
                // Advance stream pointer.
                Stream.Seek(pos + hdr.Length, SeekOrigin.Begin);
            }
        }
Exemplo n.º 11
0
 public static Attribute GetAttributeType <T>() where T : Attribute
 {
     return((T)FormatterServices.GetUninitializedObject(typeof(T)));
 }
        object Unpack(MsgPackReader reader, Type t)
        {
            if (t.IsPrimitive)
            {
                if (!reader.Read())
                {
                    throw new FormatException();
                }
                if (t.Equals(typeof(int)) && reader.IsSigned())
                {
                    return(reader.ValueSigned);
                }
                else if (t.Equals(typeof(int)) && reader.IsUnsigned())
                {
                    return((int)reader.ValueUnsigned);
                }
                else if (t.Equals(typeof(uint)) && reader.IsUnsigned())
                {
                    return(reader.ValueUnsigned);
                }
                else if (t.Equals(typeof(float)) && reader.Type == TypePrefixes.Float)
                {
                    return(reader.ValueFloat);
                }
                else if (t.Equals(typeof(double)) && reader.Type == TypePrefixes.Double)
                {
                    return(reader.ValueDouble);
                }
                else if (t.Equals(typeof(long)))
                {
                    if (reader.IsSigned64())
                    {
                        return(reader.ValueSigned64);
                    }
                    if (reader.IsSigned())
                    {
                        return((long)reader.ValueSigned);
                    }
                    if (reader.IsUnsigned64())
                    {
                        return((long)reader.ValueUnsigned64);
                    }
                    if (reader.IsUnsigned())
                    {
                        return((long)reader.ValueUnsigned);
                    }
                }
                else if (t.Equals(typeof(ulong)))
                {
                    if (reader.IsUnsigned64())
                    {
                        return(reader.ValueUnsigned64);
                    }
                    if (reader.IsUnsigned())
                    {
                        return((ulong)reader.ValueUnsigned);
                    }
                }
                else if (t.Equals(typeof(bool)) && reader.IsBoolean())
                {
                    return(reader.Type == TypePrefixes.True);
                }
                else if (t.Equals(typeof(byte)) && reader.IsUnsigned())
                {
                    return((byte)reader.ValueUnsigned);
                }
                else if (t.Equals(typeof(sbyte)) && reader.IsSigned())
                {
                    return((sbyte)reader.ValueSigned);
                }
                else if (t.Equals(typeof(short)) && reader.IsSigned())
                {
                    return((short)reader.ValueSigned);
                }
                else if (t.Equals(typeof(ushort)) && reader.IsUnsigned())
                {
                    return((ushort)reader.ValueUnsigned);
                }
                else if (t.Equals(typeof(char)) && reader.IsUnsigned())
                {
                    return((char)reader.ValueUnsigned);
                }
                else
                {
                    throw new NotSupportedException();
                }
            }

            UnpackDelegate unpacker;

            if (UnpackerMapping.TryGetValue(t, out unpacker))
            {
                return(unpacker(this, reader));
            }

            if (t.IsArray)
            {
                if (!reader.Read() || (!reader.IsArray() && reader.Type != TypePrefixes.Nil))
                {
                    throw new FormatException();
                }
                if (reader.Type == TypePrefixes.Nil)
                {
                    return(null);
                }
                Type  et  = t.GetElementType();
                Array ary = Array.CreateInstance(et, (int)reader.Length);
                for (int i = 0; i < ary.Length; i++)
                {
                    ary.SetValue(Unpack(reader, et), i);
                }
                return(ary);
            }

            if (!reader.Read())
            {
                throw new FormatException();
            }
            if (reader.Type == TypePrefixes.Nil)
            {
                return(null);
            }
            if (t.IsInterface)
            {
                if (reader.Type != TypePrefixes.FixArray && reader.Length != 2)
                {
                    throw new FormatException();
                }
                if (!reader.Read() || !reader.IsRaw())
                {
                    throw new FormatException();
                }
                CheckBufferSize((int)reader.Length);
                reader.ReadValueRaw(_buf, 0, (int)reader.Length);
                t = Type.GetType(Encoding.UTF8.GetString(_buf, 0, (int)reader.Length));
                if (!reader.Read() || reader.Type == TypePrefixes.Nil)
                {
                    throw new FormatException();
                }
            }
            if (!reader.IsMap())
            {
                throw new FormatException();
            }

            object o;

            if (t.IsSubclassOf(typeof(ScriptableObject)))
            {
                o = ScriptableObject.CreateInstance(t);
            }
            else
            {
                o = FormatterServices.GetUninitializedObject(t);
            }
            ReflectionCacheEntry entry = ReflectionCache.Lookup(t);
            int members = (int)reader.Length;

            for (int i = 0; i < members; i++)
            {
                if (!reader.Read() || !reader.IsRaw())
                {
                    throw new FormatException();
                }
                CheckBufferSize((int)reader.Length);
                reader.ReadValueRaw(_buf, 0, (int)reader.Length);
                string    name = Encoding.UTF8.GetString(_buf, 0, (int)reader.Length);
                FieldInfo f;
                if (!entry.FieldMap.TryGetValue(name, out f))
                {
                    // 正体不明なものは読み飛ばす
                    new BoxingPacker().Unpack(reader);
                    continue;
                    //throw new FormatException ();
                }
                f.SetValue(o, Unpack(reader, f.FieldType));
            }

            IDeserializationCallback callback = o as IDeserializationCallback;

            if (callback != null)
            {
                callback.OnDeserialization(this);
            }
            return(o);
        }
 static partial void RealInstanceFactory(ref IdentityDescriptor real, string callerName)
 {
     real = (IdentityDescriptor)FormatterServices.GetUninitializedObject(typeof(IdentityDescriptor));
 }
Exemplo n.º 14
0
        /// <summary>
        /// Creates an <see cref="IContract"/> that represents a smart contract in an uninitialized state.
        /// </summary>
        public static IContract CreateUninitialized(Type type, ISmartContractState state, uint160 address)
        {
            var contract = (SmartContract)FormatterServices.GetSafeUninitializedObject(type);

            return(new Contract(contract, type, state, address));
        }
Exemplo n.º 15
0
        [System.Security.SecurityCritical]  // auto-generated
        private Object GetCustomMarshaledCOMObject(Object ret)
        {
            // Some special work we need to do for __COMObject
            // (Note that we use typeInfo to detect this case instead of
            // calling GetType on 'ret' so as to not refine the proxy)
            DynamicTypeInfo dt = this.TypeInfo as DynamicTypeInfo;

            if (dt != null)
            {
                // This is a COMObject type ... we do the special work
                // only if it is from the same process but another appDomain
                // We rely on the x-appDomain channel data in the objRef
                // to provide us with the answers.
                Object ret1 = null;
                IntPtr pUnk = IntPtr.Zero;
                if (IsFromThisProcess() && !IsFromThisAppDomain())
                {
                    try
                    {
                        bool fIsURTAggregated;
                        pUnk = ((__ComObject)ret).GetIUnknown(out fIsURTAggregated);
                        if (pUnk != IntPtr.Zero && !fIsURTAggregated)
                        {
                            // The RCW for an IUnk is per-domain. This call
                            // gets (or creates) the RCW for this pUnk for
                            // the current domain.
                            String srvTypeName = TypeInfo.TypeName;
                            String typeName    = null;
                            String assemName   = null;

                            System.Runtime.Remoting.TypeInfo.ParseTypeAndAssembly(srvTypeName, out typeName, out assemName);
                            BCLDebug.Assert((null != typeName) && (null != assemName), "non-null values expected");

                            Assembly asm = FormatterServices.LoadAssemblyFromStringNoThrow(assemName);
                            if (asm == null)
                            {
                                BCLDebug.Trace("REMOTE", "ObjRef.GetCustomMarshaledCOMObject. AssemblyName is: ", assemName, " but we can't load it.");
                                throw new RemotingException(Environment.GetResourceString("Serialization_AssemblyNotFound", assemName));
                            }

                            Type serverType = asm.GetType(typeName, false, false);
                            if (serverType != null && !serverType.IsVisible)
                            {
                                serverType = null;
                            }
                            BCLDebug.Assert(serverType != null, "bad objRef!");

                            ret1 = InteropServices.Marshal.GetTypedObjectForIUnknown(pUnk, serverType);
                            if (ret1 != null)
                            {
                                ret = ret1;
                            }
                        }
                    }
                    finally
                    {
                        if (pUnk != IntPtr.Zero)
                        {
                            InteropServices.Marshal.Release(pUnk);
                        }
                    }
                }
            }
            return(ret);
        }
Exemplo n.º 16
0
 void Call_FS_2()
 {
     MemberInfo[] members = FormatterServices.GetSerializableMembers(typeof(Test), new StreamingContext(StreamingContextStates.All));
 }
Exemplo n.º 17
0
 private static SqlException GetSqlException() =>
 (SqlException)FormatterServices.GetUninitializedObject(typeof(SqlException));
Exemplo n.º 18
0
 void Call_FS_3()
 {
     Object[] os = FormatterServices.GetObjectData(t, members);
 }
Exemplo n.º 19
0
 internal static object CreateInstance(this Type type, bool hasDefaultCtor)
 {
     return(hasDefaultCtor ?
            Activator.CreateInstance(type) :
            FormatterServices.GetUninitializedObject(type));
 }
Exemplo n.º 20
0
 void Call_FS_4()
 {
     Type tp = FormatterServices.GetTypeFromAssembly(typeof(string).Assembly, "System.Int32");
 }
Exemplo n.º 21
0
        /// <summary>
        /// 解释 json 字符串,并填充到obj对象中,如果obj为null则新建对象
        /// </summary>
        private void FillObject(ref object obj, Type type, UnsafeJsonReader reader)
        {
            reader.CheckEnd();
            JsonType jsonType;

            if (type == null || type == typeof(object))
            {
                switch (reader.Current)
                {
                case '{':
                    jsonType = _keyValueType;
                    break;

                case '[':     // 中括号的json仅支持反序列化成IList的对象
                    jsonType = _arrayType;
                    break;

                default:
                    jsonType = _JsonTypeObject;
                    break;
                }
            }
            else
            {
                jsonType = JsonType.Get(type);
            }


            //如果obj == null创建新对象
            if (obj == null)
            {
                if (jsonType.IsAnonymous)
                {
                    obj = FormatterServices.GetUninitializedObject(jsonType.Type);
                }
                else if (jsonType.IsMataType == false)
                {
                    obj = Activator.CreateInstance(jsonType.Type);
                }
            }


            //判断起始字符
            switch (reader.Current)
            {
            case '{':
                reader.MoveNext();
                if (jsonType.IsDictionary)
                {
                    FillDictionary(ref obj, jsonType, reader);
                }
                else
                {
                    FillProperty(obj, jsonType, reader);
                }
                reader.SkipChar('}', true);
                break;

            case '[':     // 中括号的json仅支持反序列化成IList的对象
                reader.MoveNext();
                if (jsonType.Type.IsArray)
                {
                    if (obj is ArrayList)
                    {
                        FillList(obj, jsonType, reader);
                    }
                    else
                    {
                        var arr = obj as Array;
                        if (arr == null)
                        {
                            throw new JsonParseException(jsonType.DisplayText + " 无法从集合型的Json反序列化", reader.RawJson);
                        }
                        FillArray(arr, jsonType, reader);
                    }
                }
                else if (jsonType.IsList)
                {
                    FillList(obj, jsonType, reader);
                }
                else
                {
                    throw new JsonParseException(jsonType.DisplayText + " 无法从集合型的Json反序列化", reader.RawJson);
                }
                reader.SkipChar(']', true);
                break;

            default:
                obj = ReadValue(reader, jsonType);
                break;
            }
        }
Exemplo n.º 22
0
 void Call_FS_5()
 {
     Object o = FormatterServices.GetUninitializedObject(typeof(Test));
 }
 private static IDiscoverableMapping Construct(Type type)
 => (IDiscoverableMapping)FormatterServices
 .GetUninitializedObject(type);
Exemplo n.º 24
0
 void Call_FS_6()
 {
     Object o = FormatterServices.PopulateObjectMembers(t, members, new Object[] { 1, "hello" });
 }
Exemplo n.º 25
0
        public override object Deserialize(Stream serializationStream)
        {
            object desObject = null;
            Dictionary <long, DesObjectInfo> refObjectInfos = new Dictionary <long, DesObjectInfo>();
            Dictionary <long, object>        desObjects     = new Dictionary <long, object>();

            using (StreamReader reader = new StreamReader(serializationStream))
            {
                while (!reader.EndOfStream)
                {
                    string header = reader.ReadLine().Remove(0, 1);
                    header = header.Remove(header.Length - 1);
                    string[] hvals = header.Split('|');

                    Type objectType = Binder.BindToType(hvals[0], hvals[1]);
                    long id         = long.Parse(hvals[2]);

                    SerializationInfo serializationInfo = new SerializationInfo(objectType, new FormatterConverter());
                    object            obj = FormatterServices.GetUninitializedObject(objectType);

                    desObjects.Add(id, obj);

                    if (desObject == null)
                    {
                        desObject = obj;
                    }

                    string   body  = reader.ReadLine();
                    string[] bvals = body.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string field in bvals)
                    {
                        string[] elements = field.Split('|');
                        string   tType    = elements[0];
                        string   tName    = elements[1];
                        string   tValue   = elements[2];

                        if (tValue.Contains("ref"))
                        {
                            long idref = Convert.ToInt64(tValue.Remove(0, 3));
                            refObjectInfos.Add(id, new DesObjectInfo(Type.GetType(tType), tName, idref, serializationInfo));
                        }
                        else if (tValue.Contains("null"))
                        {
                            Type type = Type.GetType(tType);
                            serializationInfo.AddValue(tName, null, type);
                        }
                        else
                        {
                            Type type = Type.GetType(tType);
                            serializationInfo.AddValue(tName, Convert.ChangeType(tValue, type, CultureInfo.InvariantCulture), type);
                        }
                    }
                }
            }

            foreach (var refInfo in refObjectInfos)
            {
                var refInfoV = refInfo.Value;
                refInfoV.SerializationInfo.AddValue(refInfoV.Name, desObjects[refInfoV.RefId], refInfoV.Type);
            }

            for (long i = 1; i < desObjects.Count + 1; i++)
            {
                var constructor = desObjects[i].GetType().GetConstructor(new Type[] { typeof(SerializationInfo), typeof(StreamingContext) });
                constructor.Invoke(desObjects[i], new object[] { refObjectInfos[i].SerializationInfo, Context });
            }

            return(desObject);
        }
        /// <summary>Sets the property given with the property path on the passed in object.</summary>
        /// <param name="root">The root object.</param>
        /// <param name="propertyPath">The full property path formed by the name of properties from root object to the target property(included), appended by '.'.</param>
        /// <param name="propertyValue">The property value.</param>
        /// <param name="entityPropertyConverterOptions">A <see cref="EntityPropertyConverterOptions"/> object that specifies options for the entity property conversion.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        /// <returns>The updated <see cref="object"/>.</returns>
        private static object SetProperty(
            object root,
            string propertyPath,
            object propertyValue,
            EntityPropertyConverterOptions entityPropertyConverterOptions,
            OperationContext operationContext)
        {
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }

            if (propertyPath == null)
            {
                throw new ArgumentNullException("propertyPath");
            }

            try
            {
                string propertyNameDelimiter = entityPropertyConverterOptions != null ? entityPropertyConverterOptions.PropertyNameDelimiter : DefaultPropertyNameDelimiter;

                Stack <Tuple <object, object, PropertyInfo> > valueTypePropertyHierarchy = new Stack <Tuple <object, object, PropertyInfo> >();
                string[] properties = propertyPath.Split(new[] { propertyNameDelimiter }, StringSplitOptions.RemoveEmptyEntries);

                object parentProperty    = root;
                bool   valueTypeDetected = false;

                for (int i = 0; i < properties.Length - 1; i++)
                {
#if WINDOWS_RT || NETCORE
                    PropertyInfo propertyToGet = parentProperty.GetType().GetRuntimeProperty(properties[i]);
#else
                    PropertyInfo propertyToGet = parentProperty.GetType().GetProperty(properties[i]);
#endif
                    object temp = propertyToGet.GetValue(parentProperty, null);
                    Type   type = propertyToGet.PropertyType;

                    if (temp == null)
                    {
#if WINDOWS_DESKTOP || WINDOWS_RT || NETCORE
                        temp = Activator.CreateInstance(type);
#else
                        temp = FormatterServices.GetUninitializedObject(type);
#endif
                        propertyToGet.SetValue(parentProperty, ChangeType(temp, propertyToGet.PropertyType), index: null);
                    }

#if WINDOWS_RT || NETCORE
                    if (valueTypeDetected || type.GetTypeInfo().IsValueType)
#else
                    if (valueTypeDetected || type.IsValueType)
#endif
                    {
                        valueTypeDetected = true;
                        valueTypePropertyHierarchy.Push(new Tuple <object, object, PropertyInfo>(temp, parentProperty, propertyToGet));
                    }

                    parentProperty = temp;
                }

#if WINDOWS_RT || NETCORE
                PropertyInfo propertyToSet = parentProperty.GetType().GetRuntimeProperty(properties.Last());
#else
                PropertyInfo propertyToSet = parentProperty.GetType().GetProperty(properties.Last());
#endif
                propertyToSet.SetValue(parentProperty, ChangeType(propertyValue, propertyToSet.PropertyType), index: null);

                object termValue = parentProperty;
                while (valueTypePropertyHierarchy.Count != 0)
                {
                    Tuple <object, object, PropertyInfo> propertyTuple = valueTypePropertyHierarchy.Pop();
                    propertyTuple.Item3.SetValue(propertyTuple.Item2, ChangeType(termValue, propertyTuple.Item3.PropertyType), index: null);
                    termValue = propertyTuple.Item2;
                }

                return(root);
            }
            catch (Exception ex)
            {
                Logger.LogError(operationContext, SR.TraceSetPropertyError, propertyPath, propertyValue, ex.Message);
                throw;
            }
        }
        internal static object Creator(this Type type, params object[] parameters)
        {
            try
            {
                var key         = type.FullName + string.Join("", parameters?.Select(x => x.GetType().FullName));
                var constructor = type.GetConstructorInfo(parameters ?? new object[0]);

                if (constructor != null)
                {
                    var constParam = constructor.GetParameters();
                    if (parameters?.Any() ?? false)
                    {
                        for (var i = 0; i < parameters.Length; i++)
                        {
                            if (constParam.Length <= i)
                            {
                                continue;
                            }
                            if (constParam[i].ParameterType != parameters[i].GetType())
                            {
                                try
                                {
                                    parameters[i] = Convert.ChangeType(parameters[i], constParam[i].ParameterType);
                                }
                                catch
                                {
                                    // Ignore
                                }
                            }
                        }
                    }

#if NETSTANDARD2_0 || NETSTANDARD1_3 || NETSTANDARD1_5
                    if (!constParam.Any())
                    {
                        if (CachedConstructor.ContainsKey(key))
                        {
                            return(CachedConstructor[key]());
                        }
                    }
                    else if (CachedConstructorWithParameter.ContainsKey(key))
                    {
                        return(CachedConstructorWithParameter[key](parameters));
                    }

                    if (!(parameters?.Any() ?? false))
                    {
                        return(CachedConstructor.GetOrAdd(key, Expression.Lambda <Func <object> >(Expression.New(type)).Compile())());
                    }
                    else
                    {
                        // Create a single param of type object[].
                        ParameterExpression param = Expression.Parameter(typeof(object[]), "args");

                        // Pick each arg from the params array and create a typed expression of them.
                        Expression[] argsExpressions = new Expression[constParam.Length];

                        for (int i = 0; i < constParam.Length; i++)
                        {
                            Expression index            = Expression.Constant(i);
                            Type       paramType        = constParam[i].ParameterType;
                            Expression paramAccessorExp = Expression.ArrayIndex(param, index);
                            Expression paramCastExp     = Expression.Convert(paramAccessorExp, paramType);
                            argsExpressions[i] = paramCastExp;
                        }


                        return(CachedConstructorWithParameter.GetOrAdd(key, Expression.Lambda <Func <object[], object> >(Expression.New(constructor, argsExpressions), param).Compile())(parameters));
                    }
#else
                    if (!constParam.Any())
                    {
                        if (CachedDynamicMethod.ContainsKey(key))
                        {
                            return(CachedDynamicMethod[key]());
                        }
                    }
                    else if (CachedDynamicMethodWithParameters.ContainsKey(key))
                    {
                        return(CachedDynamicMethodWithParameters[key](parameters));
                    }

                    lock (CachedDynamicMethod)
                    {
                        var dynamicMethod = new System.Reflection.Emit.DynamicMethod("CreateInstance", type, (constParam.Any() ? new Type[] { typeof(object[]) } : Type.EmptyTypes), true);
                        System.Reflection.Emit.ILGenerator ilGenerator = dynamicMethod.GetILGenerator();


                        if (constructor.GetParameters().Any())
                        {
                            for (int i = 0; i < constParam.Length; i++)
                            {
                                Type paramType = constParam[i].ParameterType;
                                ilGenerator.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);    // Push array (method argument)
                                ilGenerator.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);  // Push i
                                ilGenerator.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref); // Pop array and i and push array[i]
                                if (paramType.IsValueType)
                                {
                                    ilGenerator.Emit(System.Reflection.Emit.OpCodes.Unbox_Any, paramType); // Cast to Type t
                                }
                                else
                                {
                                    ilGenerator.Emit(System.Reflection.Emit.OpCodes.Castclass, paramType); //Cast to Type t
                                }
                            }
                        }


                        //ilGenerator.Emit(System.Reflection.Emit.OpCodes.Nop);
                        ilGenerator.Emit(System.Reflection.Emit.OpCodes.Newobj, constructor);
                        //ilGenerator.Emit(System.Reflection.Emit.OpCodes.Stloc_1); // nothing
                        ilGenerator.Emit(System.Reflection.Emit.OpCodes.Ret);

                        if (!constParam.Any())
                        {
                            return(CachedDynamicMethod.GetOrAdd(key, (ObjectActivator)dynamicMethod.CreateDelegate(typeof(ObjectActivator)))());
                        }
                        else
                        {
                            return(CachedDynamicMethodWithParameters.GetOrAdd(key, (ObjectActivatorWithParameters)dynamicMethod.CreateDelegate(typeof(ObjectActivatorWithParameters)))(parameters));
                        }
                    }
#endif
                }
                else
                {
#if !NETSTANDARD1_3
                    return(FormatterServices.GetUninitializedObject(type));
#else
                    try
                    {
                        if (CachedConstructor.ContainsKey(key))
                        {
                            return(CachedConstructor[key]());
                        }
                        return(CachedConstructor.GetOrAdd(key, Expression.Lambda <Func <object> >(Expression.New(type)).Compile())());
                    }
                    catch
                    {
                        throw new Exception("DeepClonerError: Default constructor is require for NETSTANDARD1_3 for type " + type.FullName);
                    }
#endif
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 28
0
 public static T GetUninitializedInstance <T>()
 => (T)FormatterServices.GetUninitializedObject(typeof(T));
Exemplo n.º 29
0
 public void GetUninitializedObject_ByRefLikeType_NonNetfx_ThrowsNotSupportedException(Type type)
 {
     Assert.Throws <NotSupportedException>(() => FormatterServices.GetUninitializedObject(type));
     Assert.Throws <NotSupportedException>(() => FormatterServices.GetSafeUninitializedObject(type));
 }
Exemplo n.º 30
0
 public static T InstanceUninitialised <T>(this Type type) where T : class
 {
     return(FormatterServices.GetUninitializedObject(type) as T);
 }