System.Type.GetMethod(string)

Here are the examples of the csharp api System.Type.GetMethod(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3899 Examples 7

19 View Source File : ReceivePacket.cs
License : MIT License
Project Creator : 499116344

internal void TlvExecutionProcessing(ICollection<Tlv> tlvs)
        {
            if (_tlvTypes == null)
            {
                var types = replacedembly.GetExecutingreplacedembly().GetTypes();
                _tlvTypes = new Dictionary<int, Type>();
                foreach (var type in types)
                {
                    var attributes = type.GetCustomAttributes();
                    if (!attributes.Any(attr => attr is TlvTagAttribute))
                    {
                        continue;
                    }

                    var attribute = attributes.First(attr => attr is TlvTagAttribute) as TlvTagAttribute;
                    _tlvTypes.Add((int) attribute.Tag, type);
                }
            }
            foreach (var tlv in tlvs)
            {
                if (_tlvTypes.ContainsKey(tlv.Tag))
                {
                    var tlvClreplaced = replacedembly.GetExecutingreplacedembly().CreateInstance(_tlvTypes[tlv.Tag].FullName, true);
                    var methodinfo = _tlvTypes[tlv.Tag].GetMethod("Parser_Tlv");
                    methodinfo.Invoke(tlvClreplaced, new object[] { User, Reader });
                }
            }
        }

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

internal static Func<IDataReader, T> ReaderToObject(IDataReader rdr)
        {
            MethodInfo rdrGetValueMethod = rdr.GetType().GetMethod("get_Item", new Type[] { typeof(int) });

            Type[] args = { typeof(IDataReader) };
            DynamicMethod method = new DynamicMethod("DynamicRead" + Guid.NewGuid().ToString(), typeof(T), args, typeof(Repository<T>).Module, true);
            ILGenerator il = method.GetILGenerator();

            LocalBuilder result = il.DeclareLocal(typeof(T)); //loc_0
            il.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
            il.Emit(OpCodes.Stloc_0, result); //Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index.

            Label tryBlock = il.BeginExceptionBlock();

            LocalBuilder valueCopy = il.DeclareLocal(typeof(object)); //declare local variable to store object value. loc_1

            il.DeclareLocal(typeof(int)); //declare local variable to store index //loc_2
            il.Emit(OpCodes.Ldc_I4_0); //load 0 in index
            il.Emit(OpCodes.Stloc_2); //pop and save to local variable loc 2

            //get FieldInfo of all properties
            TableAttribute tableInfo = EnreplacedyCache.Get(typeof(T));

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                tableInfo.Columns.TryGetValue(rdr.GetName(i), out ColumnAttribute columnInfo);

                if (columnInfo != null && columnInfo.SetMethod != null)
                {
                    Label endIfLabel = il.DefineLabel();

                    il.Emit(OpCodes.Ldarg_0);//load the argument. Loads the argument at index 0 onto the evaluation stack.
                    il.Emit(OpCodes.Ldc_I4, i); //push field index as int32 to the stack. Pushes a supplied value of type int32 onto the evaluation stack as an int32.
                    il.Emit(OpCodes.Dup);//copy value
                    il.Emit(OpCodes.Stloc_2);//pop and save value to loc 2
                    il.Emit(OpCodes.Callvirt, rdrGetValueMethod); //Call rdr[i] method - Calls a late - bound method on an object, pushing the return value onto the evaluation stack.

                    //TODO: dynamic location using valueCopyLocal
                    il.Emit(OpCodes.Stloc_1); //pop the value and push in stack location 1
                    il.Emit(OpCodes.Ldloc_1); //load the variable in location 1

                    il.Emit(OpCodes.Isinst, typeof(DBNull)); //check whether value is null - Tests whether an object reference (type O) is an instance of a particular clreplaced.
                    il.Emit(OpCodes.Brtrue, endIfLabel); //go to end block if value is null

                    il.Emit(OpCodes.Ldloc_0); //load T result
                    il.Emit(OpCodes.Ldloc_1); //TODO: dynamic location using valueCopyLocal

                    //when Enum are without number values
                    if (columnInfo.Property.PropertyType.IsEnum)
                    {
                        Type numericType = Enum.GetUnderlyingType(columnInfo.Property.PropertyType);
                        if (rdr.GetFieldType(i) == typeof(string))
                        {
                            LocalBuilder stringEnumLocal = il.DeclareLocal(typeof(string));

                            il.Emit(OpCodes.Castclreplaced, typeof(string)); // stack is now [...][string]
                            il.Emit(OpCodes.Stloc, stringEnumLocal); // stack is now [...]
                            il.Emit(OpCodes.Ldtoken, columnInfo.Property.PropertyType); // stack is now [...][enum-type-token]
                            il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null);// stack is now [...][enum-type]
                            il.Emit(OpCodes.Ldloc, stringEnumLocal); // stack is now [...][enum-type][string]
                            il.Emit(OpCodes.Ldc_I4_1); // stack is now [...][enum-type][string][true]
                            il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [...][enum-as-object]
                            il.Emit(OpCodes.Unbox_Any, columnInfo.Property.PropertyType); // stack is now [...][typed-value]
                        }
                        else
                        {
                            ConvertValueToEnum(il, rdr.GetFieldType(i), columnInfo.Property.PropertyType, numericType);
                        }
                    }
                    else if (columnInfo.Property.PropertyType.IsValueType)
                        il.Emit(OpCodes.Unbox_Any, rdr.GetFieldType(i)); //type cast

                    // for nullable type fields
                    if (columnInfo.Property.PropertyType.IsGenericType && columnInfo.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        var underlyingType = Nullable.GetUnderlyingType(columnInfo.Property.PropertyType);
                        il.Emit(OpCodes.Newobj, columnInfo.Property.PropertyType.GetConstructor(new Type[] { underlyingType }));
                    }

                    il.Emit(OpCodes.Callvirt, columnInfo.SetMethod);
                    il.Emit(OpCodes.Nop);

                    il.MarkLabel(endIfLabel);
                }
            }

            il.BeginCatchBlock(typeof(Exception)); //begin try block. exception is in stack
            il.Emit(OpCodes.Ldloc_2); //load index
            il.Emit(OpCodes.Ldarg_0); //load argument reader
            il.Emit(OpCodes.Ldloc_1); //load value //TODO: dynamic location using valueCopyLocal
            il.EmitCall(OpCodes.Call, typeof(ReaderCache<T>).GetMethod(nameof(ReaderCache<T>.HandleException)), null); //call exception handler
            il.EndExceptionBlock();

            il.Emit(OpCodes.Ldloc, result);
            il.Emit(OpCodes.Ret);
            

            var funcType = System.Linq.Expressions.Expression.GetFuncType(typeof(IDataReader), typeof(T));
            return (Func<IDataReader, T>)method.CreateDelegate(funcType);
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildICollectionInterfaceType(DynamicFormatterreplacedembly replacedembly, Type type, Type elementType)
        {
            TypeBuilder typeBuilder = replacedembly.DefineCollectionFormatterType(type, elementType);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);

            if (type.IsGenericType == false)
            {
                DEBUG.replacedert(type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection));
                //itemType is Object, Array2
                if (type == typeof(IList))
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
                }
                else
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
                }

                TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(typeof(object)));

                TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                Type genericTypeDefine = type.GetGenericTypeDefinition();
                DEBUG.replacedert(genericTypeDefine == typeof(IEnumerable<>) || genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(ICollection<>) || genericTypeDefine == typeof(ISet<>) || genericTypeDefine == typeof(IReadOnlyList<>) || genericTypeDefine == typeof(IReadOnlyCollection<>));

                if (Array1FormatterHelper.IsArray1Type(elementType))
                {
                    //Array1
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.DeserializeSetPrefix + elementType.Name, BindingFlags.Public | BindingFlags.Static));
                    }
                    else
                    {
                        Type listFormatterType = Array1ResolverGetFormatterHelper.GetListFormatterType(elementType);
                        FieldInfo field = listFormatterType.GetField(nameof(DateTimeListFormatter.Instance), BindingFlags.Static | BindingFlags.Public);
                        MethodInfo method = listFormatterType.GetMethod(nameof(DateTimeListFormatter.Deserialize));
                        TypeBuildHelper.CallOneStaticFieldMethodInDeserialize(deserializeMethod, field, method);
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));
                }
                else
                {
                    if (genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(IReadOnlyList<>))
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeSet), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                }
            }

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : RepositoryDbContext.cs
License : MIT License
Project Creator : 2881099

public override IDbSet Set(Type enreplacedyType) {
			if (_dicSet.ContainsKey(enreplacedyType)) return _dicSet[enreplacedyType];

			var tb = _orm.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
			if (tb == null) return null;

			object repos = _repos;
			if (enreplacedyType != _repos.EnreplacedyType) {
				repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(enreplacedyType, typeof(int)), _repos.Orm);
				(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
				GetRepositoryDbField(enreplacedyType).SetValue(repos, this);

				typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EnreplacedyType)
					.Invoke(null, new object[] { repos, _repos });
			}

			var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(enreplacedyType), repos) as IDbSet;
			if (enreplacedyType != typeof(object)) _dicSet.Add(enreplacedyType, sd);
			return sd;
		}

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type)
        {
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeIDictionary), BindingFlags.Public | BindingFlags.Static));

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            ParameterInfo[] args = constructor.GetParameters();
            Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);

            if (args.Length == 1)
            {
                DEBUG.replacedert(args[0].ParameterType == typeof(IDictionary));

                //return new T(IDictionaryFormatter.Deserialize)
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
                methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
            }
            else
            {
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithIDictionaryEmptyCtor));
                methodinfo.Invoke(null, new object[] { });
            }
            TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeIDictionary), BindingFlags.Public | BindingFlags.Static));

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallDeserializeDelegate(MethodBuilder deserializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = deserializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, typeof(Deserialize<>).MakeGenericType(genericType).GetMethod(nameof(Deserialize<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static T GetMethodAttribute<T>(Type type,string methodName)where T: Attribute
            {
                var mi = type.GetMethod(methodName);
                if (null!=mi)
                {
                    var attributes = mi.GetCustomAttributes(typeof(T),false);
                    if (0<attributes.Length)
                    {
                        return attributes[0] as T;
                    }
                }
                return null;
            }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_FormatterDeserialize(Expression formatter)
        {
            return Expression.Call(formatter, formatter.Type.GetMethod(nameof(IBssomFormatter<int>.Deserialize)), Par_Reader, Par_DeserializeContext);
        }

19 View Source File : PrefixWriter.cs
License : MIT License
Project Creator : Abc-Arbitrage

private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollection<PatternPart> parts, Dictionary<string, (int offset, int length)> stringMap)
        {
            var method = new DynamicMethod("WritePrefix", typeof(void), new[] { typeof(PrefixWriter), typeof(ILogEventHeader) }, typeof(PrefixWriter), false)
            {
                InitLocals = false
            };

            var il = method.GetILGenerator();

            var stringBufferLocal = il.DeclareLocal(typeof(StringBuffer));
            var stringsLocal = il.DeclareLocal(typeof(char).MakeByRefType(), true);
            var dateTimeLocal = default(LocalBuilder);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_stringBuffer), BindingFlags.Instance | BindingFlags.NonPublic)!);
            il.Emit(OpCodes.Stloc, stringBufferLocal);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_strings), BindingFlags.Instance | BindingFlags.NonPublic)!);
            il.Emit(OpCodes.Ldc_I4_0);
            il.Emit(OpCodes.Ldelema, typeof(char));
            il.Emit(OpCodes.Stloc, stringsLocal);

            foreach (var part in parts)
            {
                switch (part.Type)
                {
                    case PatternPartType.String:
                    {
                        // _stringBuffer.Append(&_strings[0] + offset * sizeof(char), length);

                        var (offset, length) = stringMap[part.Value!];

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldloc, stringsLocal);
                        il.Emit(OpCodes.Conv_U);
                        il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
                        il.Emit(OpCodes.Add);

                        il.Emit(OpCodes.Ldc_I4, length);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(char*), typeof(int) })!);
                        break;
                    }

                    case PatternPartType.Date:
                    {
                        // _stringBuffer.Append(logEventHeader.Timestamp, new StringView(&_strings[0] + offset * sizeof(char), length));

                        var (offset, length) = stringMap[_dateFormat];

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);

                        il.Emit(OpCodes.Ldloc, stringsLocal);
                        il.Emit(OpCodes.Conv_U);
                        il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
                        il.Emit(OpCodes.Add);

                        il.Emit(OpCodes.Ldc_I4, length);

                        il.Emit(OpCodes.Newobj, typeof(StringView).GetConstructor(new[] { typeof(char*), typeof(int) })!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(DateTime), typeof(StringView) })!);
                        break;
                    }

                    case PatternPartType.Time:
                    {
                        // _stringBuffer.Append(logEventHeader.Timestamp.TimeOfDay, StringView.Empty);

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
                        il.Emit(OpCodes.Stloc, dateTimeLocal ??= il.DeclareLocal(typeof(DateTime)));
                        il.Emit(OpCodes.Ldloca, dateTimeLocal);
                        il.Emit(OpCodes.Call, typeof(DateTime).GetProperty(nameof(DateTime.TimeOfDay))?.GetGetMethod()!);

                        il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty))!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(TimeSpan), typeof(StringView) })!);
                        break;
                    }

                    case PatternPartType.Thread:
                    {
                        // AppendThread(logEventHeader.Thread);

                        il.Emit(OpCodes.Ldarg_0);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Thread))?.GetGetMethod()!);

                        il.Emit(OpCodes.Call, typeof(PrefixWriter).GetMethod(nameof(AppendThread), BindingFlags.Instance | BindingFlags.NonPublic)!);
                        break;
                    }

                    case PatternPartType.Level:
                    {
                        // _stringBuffer.Append(LevelStringCache.GetLevelString(logEventHeader.Level));

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Level))?.GetGetMethod()!);
                        il.Emit(OpCodes.Call, typeof(LevelStringCache).GetMethod(nameof(LevelStringCache.GetLevelString))!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
                        break;
                    }

                    case PatternPartType.Logger:
                    {
                        // _stringBuffer.Append(logEventHeader.Name);

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Name))?.GetGetMethod()!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            il.Emit(OpCodes.Ret);

            return (Action<PrefixWriter, ILogEventHeader>)method.CreateDelegate(typeof(Action<PrefixWriter, ILogEventHeader>));
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_DeserializeContextOptionResolver_GetFormatterWithVerify_Deserialize(Type type)
        {
            return Expression.Call(Call_GetFormatterWithVerify(DeserializeContextOptionResolver, type), typeof(IBssomFormatter<>).MakeGenericType(type).GetMethod(nameof(IBssomFormatter<int>.Deserialize)), Par_Reader, Par_DeserializeContext);
        }

19 View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099

static Func<Dictionary<string, string>, T> CompileDeserializer()
        {
            var o_t = typeof(T);
            var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) });

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator");

            var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) });

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(Dictionary<string, string>.Enumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_current = Expression.Property(enumerator, "Current");

            var kvp_t = typeof(KeyValuePair<string, string>);
            var kvp_pi_key = kvp_t.GetProperty("Key");
            var kvp_pi_value = kvp_t.GetProperty("Value");

            var exit_loop = Expression.Label("exit_loop");

            var body = Expression.Block(new[] { fc, info, ctx, enumerator },
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.replacedign(enumerator, Expression.Call(d, d_mi_get_enumerator)),

                Expression.Loop(
                    Expression.IfThenElse(
                        Expression.Call(enumerator, enumerator_mi_move_next),
                        Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)),
                        Expression.Break(exit_loop)),
                    exit_loop),

                Expression.MemberInit(Expression.New(o_ctor, info, ctx))
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression AsPointerExpression(Expression instance)
        {
            var asPointerMethodType = typeof(ExpressionTreeAux).GetMethod(nameof(ExpressionTreeAux.AsPointer)).MakeGenericMethod(instance.Type);
            return Expression.Call(null, asPointerMethodType, instance);
        }

19 View Source File : ILRuntimeManager.cs
License : MIT License
Project Creator : 404Lcc

public unsafe void InitializeILRuntime()
        {
#if UNITY_EDITOR
            appdomain.DebugService.StartDebugService(56000);
#endif
#if DEBUG && (UNITY_EDITOR || UNITY_ANDROID || UNITY_IPHONE)
            appdomain.UnityMainThreadID = Thread.CurrentThread.ManagedThreadId;
#endif
            ILRuntimeHelper.RegisterCrossBindingAdaptor(appdomain);
            ILRuntimeHelper.RegisterCLRMethodRedirction(appdomain);
            ILRuntimeHelper.RegisterMethodDelegate(appdomain);
            ILRuntimeHelper.RegisterValueTypeBinderHelper(appdomain);

            JsonMapper.RegisterILRuntimeCLRRedirection(appdomain);
            PType.RegisterILRuntimeCLRRedirection(appdomain);

            Type.GetType("ILRuntime.Runtime.Generated.CLRBindings")?.GetMethod("Initialize")?.Invoke(null, new object[] { appdomain });

            typeList = appdomain.LoadedTypes.Values.Select(x => x.ReflectionType).ToList();
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_Writer_Seek(Expression pos)
        {
            return Expression.Call(Field_WriterBufferWriter, typeof(IBssomBufferWriter).GetMethod(nameof(IBssomBufferWriter.Seek)), pos, Expression.Constant(BssomSeekOrgin.Begin, typeof(BssomSeekOrgin)));
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

internal static Lazy<TDelegate> MakeLazyDelegate<TDelegate>(string name, Action<ILGenerator> ilgen)
            where TDelegate : Delegate
        {
            Debug.replacedert(typeof(TDelegate).GetMethod("Invoke") != null);

            return new Lazy<TDelegate>(() => MakeDelegate<TDelegate>(name, ilgen));
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildICollectionImplementationType(DynamicFormatterreplacedembly replacedembly, Type type, ConstructorInfo constructor,
                     Type itemType,
                     bool isImplGenerIList, bool IsImplIList, bool isImplGenerICollec, bool isImplIReadOnlyList)
        {
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            if (itemType == typeof(object))
            {
                //itemType is Object, Array2
                if (IsImplIList)
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
                }
                else
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
                }

                TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                if (Array1FormatterHelper.IsArray1Type(itemType))
                {
                    //Array1
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(itemType) }));

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(itemType) }));
                }
                else
                {
                    if (isImplGenerIList || isImplIReadOnlyList)
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(itemType));
                }
            }

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            ParameterInfo[] args = constructor.GetParameters();
            if (args.Length == 1 && args[0].ParameterType != typeof(int))
            {
                //new T(IEnumerable t)
                Type dynamicCacheType = typeof(CollectionDynamicDelegateCache<>).MakeGenericType(type);
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateInjectCtor));
                methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
                TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(CollectionDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                if (itemType == typeof(DateTime))//DateTime需要特殊处理,因为要处理Standrand和Native
                {
                    Type dtCollBuilder = typeof(DateTimeCollectionDeserializeBuilder<>).MakeGenericType(type);
                    MethodInfo methodinfo = dtCollBuilder.GetMethod(nameof(DateTimeCollectionDeserializeBuilder<ICollection<DateTime>>.ConstructorInit));
                    methodinfo.Invoke(null, new object[] { constructor });

                    TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, dtCollBuilder.GetMethod(nameof(DateTimeCollectionDeserializeBuilder<ICollection<DateTime>>.Deserialize)));
                }
                else
                {
                    Type dynamicCacheType = typeof(CollectionDynamicDelegateCache<>).MakeGenericType(type);
                    if (args.Length == 0)
                    {
                        MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateDeserializeWithEmptyCtor));
                        methodinfo.Invoke(null, new object[] { constructor, isImplGenerICollec, itemType });
                    }
                    else
                    {
                        DEBUG.replacedert(args.Length == 1 && args[0].ParameterType == typeof(int));

                        MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(CollectionDynamicDelegateCache<int>.GenerateDeserializeWithCapacityCtor));
                        methodinfo.Invoke(null, new object[] { constructor, isImplGenerICollec, itemType });
                    }
                    TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(CollectionDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));
                }
            }
            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin

private static void ReleasePowerPackPersistanceInstance(UnityEngine.Object instance)
		{
			var method = powerPackPersistance.GetMethod("Release");
			method.Invoke(instance, null);
		}

19 View Source File : XnaToFnaUtil.Processor.cs
License : zlib License
Project Creator : 0x0ade

public void PreProcessType(TypeDefinition type) {
            if (HookCompat) {
                foreach (MethodDefinition method in type.Methods) {
                    if (!method.HasPInvokeInfo)
                        continue;
                    // Just check if PInvokeHooks contains the entry point, ignoring the module name, except for its end. What can go wrong?...
                    if (!method.PInvokeInfo.Module.Name.EndsWith("32.dll") && !method.PInvokeInfo.Module.Name.EndsWith("32"))
                        continue;
                    string entryPoint = method.PInvokeInfo.EntryPoint ?? method.Name;
                    if (typeof(PInvokeHooks).GetMethod(entryPoint) != null) {
                        Log($"[PreProcess] [PInvokeHooks] Remapping call to {entryPoint} ({method.GetFindableID()})");
                        Modder.RelinkMap[method.GetFindableID(simple: true)] =
                            new RelinkMapEntry("XnaToFna.PInvokeHooks", entryPoint);
                    } else {
                        Log($"[PreProcess] [PInvokeHooks] Found unhooked call to {entryPoint} ({method.GetFindableID()})");
                    }
                }
            }

            if (FixOldMonoXML) {
                Stack<TypeDefinition> baseTypes = new Stack<TypeDefinition>();
                try {
                    for (TypeDefinition baseType = type.BaseType?.Resolve(); baseType != null; baseType = baseType.BaseType?.Resolve())
                        baseTypes.Push(baseType);
                } catch {
                    // Unresolved replacedembly, f.e. XNA itself
                }

                foreach (FieldDefinition field in type.Fields) {
                    string name = field.Name;

                    if (baseTypes.Any(baseType => baseType.FindField(name) != null || baseType.FindProperty(name) != null)) {
                        // Field name collision found. Mono 4.4+ handles them well, while Xamarin.Android still fails.
                        Log($"[PreProcess] Renaming field name collison {name} in {type.FullName}");
                        field.Name = $"{name}_{type.Name}";
                        Modder.RelinkMap[$"{type.FullName}::{name}"] = field.FullName;
                    }
                }
            }

            foreach (TypeDefinition nested in type.NestedTypes)
                PreProcessType(nested);
        }

19 View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott

private bool ExecuteInnerTask(object innerTask)
        {
            Type innerTaskType = innerTask.GetType();
            Type innerTaskBaseType = innerTaskType;
            while (innerTaskBaseType.FullName != typeof(ContextIsolatedTask).FullName)
            {
                innerTaskBaseType = innerTaskBaseType.GetTypeInfo().BaseType;
            }

            var outerProperties = this.GetType().GetRuntimeProperties().ToDictionary(i => i.Name);
            var innerProperties = innerTaskType.GetRuntimeProperties().ToDictionary(i => i.Name);
            var propertiesDiscovery = from outerProperty in outerProperties.Values
                                      where outerProperty.SetMethod != null && outerProperty.GetMethod != null
                                      let innerProperty = innerProperties[outerProperty.Name]
                                      select new { outerProperty, innerProperty };
            var propertiesMap = propertiesDiscovery.ToArray();
            var outputPropertiesMap = propertiesMap.Where(pair => pair.outerProperty.GetCustomAttribute<OutputAttribute>() != null).ToArray();

            foreach (var propertyPair in propertiesMap)
            {
                object outerPropertyValue = propertyPair.outerProperty.GetValue(this);
                propertyPair.innerProperty.SetValue(innerTask, outerPropertyValue);
            }

            // Forward any cancellation requests
            MethodInfo innerCancelMethod = innerTaskType.GetMethod(nameof(Cancel));
            using (this.CancellationToken.Register(() => innerCancelMethod.Invoke(innerTask, new object[0])))
            {
                this.CancellationToken.ThrowIfCancellationRequested();

                // Execute the inner task.
                var executeInnerMethod = innerTaskType.GetMethod(nameof(ExecuteIsolated), BindingFlags.Instance | BindingFlags.NonPublic);
                bool result = (bool)executeInnerMethod.Invoke(innerTask, new object[0]);

                // Retrieve any output properties.
                foreach (var propertyPair in outputPropertiesMap)
                {
                    propertyPair.outerProperty.SetValue(this, propertyPair.innerProperty.GetValue(innerTask));
                }

                return result;
            }
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

private static void GenerateDeserializeWithCore(bool isImplGenerICollec, Type itemType, Func<Expression, Expression> ctor)
        {
            /*
               if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int8Code))/TryReadNullWithEnsureArray1NativeType(NativeBssomType.CharCode)/TryReadNullWithEnsureBuildInType(BssomType.Array2)
                    return default;
               context.option.Security.DepthStep(ref reader);
               reader.SkipVariableNumber();
               int len = reader.ReadVariableNumber();
               T t = new T(len);
               Fill<T>(ref t,ref reader,ref context,len);
               context.Depth--;
               return t;  
            */

            bool isArray1Type = Array1FormatterHelper.IsArray1Type(itemType, out bool isNativeType, out byte typeCode, out string typeCodeName);
            Type t = typeof(T);
            List<Expression> ary = new List<Expression>(7);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");

            if (isArray1Type)
            {
                if (isNativeType)
                {
                    //if (reader.ryReadNullWithEnsureArray1NativeType(NativeType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1NativeType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
                else
                {
                    //if (reader.Call_Reader_TryReadNullWithEnsureArray1BuildInType(BuildInType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1BuildInType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
            }
            else
            {
                //if (reader.TryReadNullWithEnsureBuildInType(BssomType.Array2))
                //      goto label;
                ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array2), Expression.Return(returnTarget, Expression.Default(t))));
            }

            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);

            //reader.SkipVariableNumber();
            ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);

            //int len = reader.ReadVariableNumber();
            ParameterExpression len = Expression.Variable(typeof(int));
            ary.Add(Expression.replacedign(len, CommonExpressionMeta.Call_Reader_ReadVariableNumber));

            //T t = ctor(len);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(len)));
            MethodInfo method = null;
            if (isImplGenerICollec == false)
            {
                //IColloctionFormatterHelper.Fill_ImplIList<T>(ref t,ref reader,ref context,len)
                method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
            }
            else
            {
                if (isArray1Type)
                {
                    //IColloctionFormatterHelper.Fill{TypeCodeName}<T>(ref t,ref reader,ref context,len)
                    method = typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.FillPrefix + typeCodeName.ToString().Replace("Code", ""), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
                }
                else
                {
                    //IColloctionFormatterHelper.Fill_ImplICollection<T,TElement>(ref t,ref reader,ref context,len)
                    method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplICollection), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { t, itemType });
                }
            }

            ary.Add(Expression.Call(null, method, instance, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext, len));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { instance, len }, ary);
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();


        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildGenericIDictionaryImplementationType(DynamicFormatterreplacedembly replacedembly, ConstructorInfo constructor, Type type, Type genericKeyType, Type genericValueType)
        {
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SerializeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { genericKeyType, genericValueType }));

            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            ParameterInfo[] args = constructor.GetParameters();
            Type dynamicCacheType = typeof(IDictionaryDynamicDelegateCache<>).MakeGenericType(type);
            if (args.Length == 0)
            {
                MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictEmptyCtor));
                methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
            }
            else
            {
                DEBUG.replacedert(args.Length == 1);
                if (args[0].ParameterType == typeof(int))
                {
                    MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateDeserializeWithGenericDictCapacityCtor));
                    methodinfo.Invoke(null, new object[] { constructor, genericKeyType, genericValueType });
                }
                else
                {
                    MethodInfo methodinfo = dynamicCacheType.GetMethod(nameof(IDictionaryDynamicDelegateCache<int>.GenerateInjectCtor));
                    methodinfo.Invoke(null, new object[] { constructor, args[0].ParameterType });
                }
            }
            TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, dynamicCacheType.GetField(nameof(IDictionaryDynamicDelegateCache<int>.Deserialize), BindingFlags.Public | BindingFlags.Static));

            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);
            TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.SizeGenericDictionary), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericKeyType, genericValueType));

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : MethodInvokerTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void ConstructMethodTest()
        {
            var method = typeof(MethodInvokerMethod).GetMethod("GetString");
            replacedert.Throws<ArgumentNullException>(() =>
            {
                new MethodInvoker(null);
            });
            var methodInvoker = new MethodInvoker(method);
            replacedert.NotNull(methodInvoker);
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_SerializeContextOptionResolver_GetFormatterWithVerify_Serialize(Expression value)
        {
            return Expression.Call(Call_GetFormatterWithVerify(SerializeContextOptionResolver, value.Type), typeof(IBssomFormatter<>).MakeGenericType(value.Type).GetMethod(nameof(IBssomFormatter<int>.Serialize)), Par_Writer, Par_SerializeContext, value);
        }

19 View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099

static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
        {
            var o_t = typeof(T);
            var o = Expression.Variable(o_t, "o");
            var o_new = Expression.New(typeof(T));

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_try_get_value = d_t.GetMethod("TryGetValue");

            var item_t = typeof(String);
            var item = Expression.Variable(item_t, "item");

            var tc_t = typeof(TypeConverter);
            var tc = Expression.Variable(tc_t, "tc");
            var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
            var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });

            var td_t = typeof(TypeDescriptor);
            var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });

            var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var value_t = x.PropertyType;
                    var value = Expression.Variable(value_t, "value");
                    var target = Expression.Label(x.PropertyType);

                    return Expression.Bind(x, Expression.Block(new[] { item, value },
                        Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
                        Expression.IfThen(
                            Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
                            Expression.IfThen(
                                Expression.NotEqual(item, Expression.Constant(null)),
                                Expression.IfThen(
                                    Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
                                    Expression.Block(
                                        Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
                                        Expression.Return(target, value, x.PropertyType))))),
                        Expression.Label(target, value)
                    ));
                }).ToArray();

            var body = Expression.Block(new[] { o, tc },
                Expression.MemberInit(o_new, binds)
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099

static Func<T, Dictionary<string, string>> CompilePropertySerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "o");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d");
            var d_init = Expression.MemberInit(Expression.New(d_t));
            var d_add = d_t.GetMethod("Add");
            var d_setters = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) // build setters via Add(k,v)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var prop = Expression.Property(o, x.Name);
                    var prop_mi_to_string = x.PropertyType.GetMethod("ToString", new Type[0]);
                    var add_to_dict = Expression.Call(d, d_add, Expression.Constant(x.Name), Expression.Call(prop, prop_mi_to_string));

                    if (!x.PropertyType.IsByRef)
                        return (Expression)add_to_dict;
                    else
                        return (Expression)Expression.IfThen(
                            Expression.Not(Expression.Equal(prop, Expression.Constant(null))),
                            add_to_dict);
                });

            // run this
            var body = Expression.Block(new[] { d }, // scope variables
                Expression.replacedign(d, d_init), // initialize
                Expression.Block(d_setters), // set
                d); // return

            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_DateTimeSize()
        {
            return Expression.Call(null, typeof(BssomBinaryPrimitives).GetMethod(nameof(BssomBinaryPrimitives.DateTimeSize)), Field_SizeOption_IsUseStandardDateTime);
        }

19 View Source File : Admin.cs
License : MIT License
Project Creator : 2881099

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				var tpl = _tpl.Value;

				switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
					case null:
						//首页
						if (true) {
							MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);

							//ManyToOne/OneToOne
							var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
								}
							}

							int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
							int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
							if (getpage <= 0) getpage = 1;
							if (getlimit <= 0) getlimit = 20;

							var getselect = fsql.Select<object>().AsType(enreplacedyType);
							foreach (var getlistF in getlistFilter) {
								var qv = req.Query[getlistF.Item3].ToArray();
								if (qv.Any()) {
									switch (getlistF.Item1.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											if (true) {
												var midType = getlistF.Item1.RefMiddleEnreplacedyType;
												var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
												var midISelect = typeof(ISelect<>).MakeGenericType(midType);

												var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
												var expParam = Expression.Parameter(typeof(object), "a");
												var midParam = Expression.Parameter(midType, "mdtp");

												var anyMethod = midISelect.GetMethod("Any");
												var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
												var expLambad = Expression.Lambda<Func<object, bool>>(
													Expression.Call(
														Expression.Call(
															Expression.Call(
																Expression.Constant(fsql),
																typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
															),
															midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
															Expression.Lambda(
																typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
																Expression.AndAlso(
																	Expression.Equal(
																		Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
																	),
																	Expression.Call(
																		Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
																		Expression.NewArrayInit(
																			getlistF.Item1.MiddleColumns[1].CsType,
																			selectExp
																		),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
																	)
																),
																midParam
															)
														),
														anyMethod,
														Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
													),
													expParam);

												getselect.Where(expLambad);
											}
											continue;
									}
								}
							}

							var getlistTotal = await getselect.CountAsync();
							var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
							var gethashlists = new Dictionary<string, object>[getlist.Count];
							var gethashlistsIndex = 0;
							foreach (var getlisreplacedem in getlist) {
								var gethashlist = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
								}
								gethashlists[gethashlistsIndex++] = gethashlist;
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["getlist"] = gethashlists;
							options["getlistTotal"] = getlistTotal;
							options["getlistFilter"] = getlistFilter;
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
							await res.WriteAsync(str);
						}
						return true;
					case "add":
					case "edit":
						//编辑页
						object gereplacedem = null;
						Dictionary<string, object> gethash = null;
						if (req.Query.Any()) {
							gereplacedem = Activator.CreateInstance(enreplacedyType);
							foreach (var getpk in tb.Primarys) {
								var reqv = req.Query[getpk.CsName].ToArray();
								if (reqv.Any())
									fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
							}
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							if (gereplacedem != null) {
								gethash = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
								}
							}
						}

						if (req.Method.ToLower() == "get") {
							MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);

							//ManyToOne/OneToOne
							var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							var getlistManyed = new Dictionary<string, IEnumerable<string>>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));

										if (gereplacedem != null) {
											var midType = tbref.RefMiddleEnreplacedyType;
											var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
											var manyed = await fsql.Select<object>().AsType(midType)
												.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
												.ToListAsync();
											getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
										}
										continue;
								}
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["gethash"] = gethash;
							options["getlistFilter"] = getlistFilter;
							options["getlistManyed"] = getlistManyed;
							options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
							await res.WriteAsync(str);

						} else {
							if (gereplacedem == null) {
								gereplacedem = Activator.CreateInstance(enreplacedyType);
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
								}
							}
							var manySave = new List<(TableRef, object[], List<object>)>();
							if (req.Form.Any()) {
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);

									var reqv = req.Form[getcol.CsName].ToArray();
									if (reqv.Any())
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
								}
								//ManyToMany
								foreach (var prop in tb.Properties) {
									if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
									var tbref = tb.GetTableRef(prop.Key, false);
									if (tbref == null) continue;
									switch (tbref.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											var midType = tbref.RefMiddleEnreplacedyType;
											var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);

											var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
											var reqvIndex = 0;
											var manyVals = new object[reqv.Length];
											foreach (var rv in reqv) {
												var miditem = Activator.CreateInstance(midType);
												foreach (var getcol in tb.Columns.Values) {
													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);

													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
												}
												//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
												fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
												manyVals[reqvIndex++] = miditem;
											}
											var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
											manySave.Add((tbref, manyVals, molds));
											continue;
									}
								}
							}


							using (var db = fsql.CreateDbContext()) {

								var dbset = db.Set<object>();
								dbset.AsType(enreplacedyType);

								await dbset.AddOrUpdateAsync(gereplacedem);

								foreach (var ms in manySave) {
									var midType = ms.Item1.RefMiddleEnreplacedyType;
									var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));

									var manyset = db.Set<object>();
									manyset.AsType(midType);
									
									foreach (var msVal in ms.Item2) {
										fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
										await manyset.AddOrUpdateAsync(msVal);
										moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
									}
									manyset.RemoveRange(moldsDic.Values);
								}

								await db.SaveChangesAsync();
							}
							gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
						}
						return true;
					case "del":
						if (req.Method.ToLower() == "post") {

							var delitems = new List<object>();
							var reqv = new List<string[]>();
							foreach(var delpk in tb.Primarys) {
								var reqvs = req.Form[delpk.CsName].ToArray();
								if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
								reqv.Add(reqvs);
							}
							if (reqv[0].Length == 0) return true;

							using (var ctx = fsql.CreateDbContext()) {
								var dbset = ctx.Set<object>();
								dbset.AsType(enreplacedyType);

								for (var a = 0; a < reqv[0].Length; a++) {
									object delitem = Activator.CreateInstance(enreplacedyType);
									var delpkindex = 0;
									foreach (var delpk in tb.Primarys)
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
									dbset.Remove(delitem);
								}
								await ctx.SaveChangesAsync();
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
							return true;
						}
						break;
				}
			}
			return false;
		}

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_MapFormatterHelper_Deserialize(Type keyType, Type valueType)
        {
            return Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.Deserialize)).MakeGenericMethod(keyType, valueType), Par_Reader, Par_DeserializeContext);
        }

19 View Source File : QueryableExtension.cs
License : GNU General Public License v3.0
Project Creator : 2dust

static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName, bool isDesc)
        {
            string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal";

            var memberProp = typeof(T).GetProperty(propertyName);

            var method = typeof(QueryableExtension).GetMethod(methodname)
                                       .MakeGenericMethod(typeof(T), memberProp.PropertyType);

            return (IOrderedQueryable<T>)method.Invoke(null, new object[] { query, memberProp });
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallSerializeDelegate(MethodBuilder serializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = serializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_3);
            il.Emit(OpCodes.Call, typeof(Serialize<>).MakeGenericType(genericType).GetMethod(nameof(Serialize<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : MonoManager.cs
License : MIT License
Project Creator : 404Lcc

public unsafe void OnHotfixLoaded()
        {
            object instance = replacedembly.CreateInstance("LccHotfix.Init");
            Type type = instance.GetType();
            MethodInfo methodInfo = type.GetMethod("InitHotfix");
            methodInfo.Invoke(null, null);
        }

19 View Source File : XnaToFnaHelper.cs
License : zlib License
Project Creator : 0x0ade

public static void PlatformHook(string name) {
            Type t_Helper = typeof(XnaToFnaHelper);

            replacedembly fna = replacedembly.Getreplacedembly(typeof(Game));
            FieldInfo field = fna.GetType("Microsoft.Xna.Framework.FNAPlatform").GetField(name);

            // Store the original delegate into fna_name.
            t_Helper.GetField($"fna_{name}").SetValue(null, field.GetValue(null));
            // Replace the value with the new method.
            field.SetValue(null, Delegate.CreateDelegate(fna.GetType($"Microsoft.Xna.Framework.FNAPlatform+{name}Func"), t_Helper.GetMethod(name)));
        }

19 View Source File : ParseableSerializer.cs
License : MIT License
Project Creator : 404Lcc

private static MethodInfo GetCustomToString(Type type)
        {
#if WINRT
            foreach (MethodInfo method in type.GetTypeInfo().GetDeclaredMethods("ToString"))
            {
                if (method.IsPublic && !method.IsStatic && method.GetParameters().Length == 0) return method;
            }
            return null;
#elif PORTABLE || COREFX || PROFILE259
			MethodInfo method = Helpers.GetInstanceMethod(type, "ToString", Helpers.EmptyTypes);
            if (method == null || !method.IsPublic || method.IsStatic || method.DeclaringType != type) return null;
            return method;
#else

            return type.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
                        null, Helpers.EmptyTypes, null);
#endif
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallSizeDelegate(MethodBuilder serializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = serializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, typeof(Size<>).MakeGenericType(genericType).GetMethod(nameof(Size<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

internal static TDelegate MakeDelegate<TDelegate>(string name, Action<ILGenerator> ilgen, Type owner = null)
            where TDelegate : Delegate
        {
            MethodInfo invokeMethod = typeof(TDelegate).GetMethod("Invoke");

            Debug.replacedert(invokeMethod != null);

            ParameterInfo[] parameters = invokeMethod.GetParameters();
            Type[] parameterTypes = new Type[parameters.Length];

            for (int i = 0; i < parameters.Length; i++)
            {
                parameterTypes[i] = parameters[i].ParameterType;
            }

            DynamicMethod method = owner == null
                ? new DynamicMethod(name, invokeMethod.ReturnType, parameterTypes, true)
                : new DynamicMethod(name, invokeMethod.ReturnType, parameterTypes, owner, true);

            ILGenerator il = method.GetILGenerator();

            ilgen(il);

            return (TDelegate)method.CreateDelegate(typeof(TDelegate));
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_FormatterSerialize(Expression formatter, Expression value)
        {
            return Expression.Call(formatter, formatter.Type.GetMethod(nameof(IBssomFormatter<int>.Serialize)), Par_Writer, Par_SerializeContext, value);
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetVectorObject(Span<byte> buffer, out object value, out int consumed)
        {
            value = default;
            consumed = default;

            if (!DataIsType(buffer, Amf3Type.VectorObject))
            {
                return false;
            }

            buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);

            int arrayConsumed = 0;

            if (!ReadVectorHeader(ref buffer, ref value, ref arrayConsumed, out var itemCount, out var isFixedSize, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                consumed = arrayConsumed;
                return true;
            }

            if (!ReadVectorTypeName(ref buffer, out var typeName, out var typeNameConsumed))
            {
                return false;
            }

            var arrayBodyBuffer = buffer;

            object resultVector = null;
            Type elementType = null;
            Action<object> addAction = null;
            if (typeName == "*")
            {
                elementType = typeof(object);
                var v = new Vector<object>();
                _objectReferenceTable.Add(v);
                v.IsFixedSize = isFixedSize;
                resultVector = v;
                addAction = v.Add;
            }
            else
            {
                if (!_registeredTypedObejectStates.TryGetValue(typeName, out var state))
                {
                    return false;
                }
                elementType = state.Type;

                var vectorType = typeof(Vector<>).MakeGenericType(elementType);
                resultVector = Activator.CreateInstance(vectorType);
                _objectReferenceTable.Add(resultVector);
                vectorType.GetProperty("IsFixedSize").SetValue(resultVector, isFixedSize);
                var addMethod = vectorType.GetMethod("Add");
                addAction = o => addMethod.Invoke(resultVector, new object[] { o });
            }
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetValue(arrayBodyBuffer, out var item, out var itemConsumed))
                {
                    return false;
                }
                addAction(item);

                arrayBodyBuffer = arrayBodyBuffer.Slice(itemConsumed);
                arrayConsumed += itemConsumed;
            }
            value = resultVector;
            consumed = typeNameConsumed + arrayConsumed;
            return true;
        }

19 View Source File : NativeAPI.cs
License : Apache License 2.0
Project Creator : 1694439208

public static int GetMethodPTR(Type type,string name) {
            return type.GetMethod(name).MethodHandle.GetFunctionPointer().ToInt32();
        }

19 View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin

public static void HideAll()
		{
			var persistance = GetPowerPackPersistanceType();
			var instance = GetPowerPackPersistanceInstance();
			var hideAllMethod = persistance.GetMethod("HideAll");
			hideAllMethod.Invoke(instance, null);
			ReleasePowerPackPersistanceInstance(instance);
		}

19 View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade

public static IntPtr AsPointer<T>(ref T value) {
            Delegate cached;
            lock (_AsPointerCache)
                _AsPointerCache.TryGetValue(typeof(T), out cached);
            if (cached != null)
                return (cached as _AsPointer<T>)(ref value);

            if (_AsPointerHelper == null) {
                replacedembly asm;

                const string @namespace = "Celeste.Mod.CelesteNet.Client";
                const string @name = "AsPointerHelper";
                const string @fullName = @namespace + "." + @name;

                using (ModuleDefinition module = ModuleDefinition.CreateModule(
                    @fullName,
                    new ModuleParameters() {
                        Kind = ModuleKind.Dll,
                        ReflectionImporterProvider = MMReflectionImporter.Provider
                    }
                )) {

                    TypeDefinition type = new(
                        @namespace,
                        @name,
                        MC.TypeAttributes.Public | MC.TypeAttributes.Abstract | MC.TypeAttributes.Sealed
                    ) {
                        BaseType = module.TypeSystem.Object
                    };
                    module.Types.Add(type);

                    MethodDefinition method = new(@name,
                        MC.MethodAttributes.Public | MC.MethodAttributes.Static | MC.MethodAttributes.HideBySig,
                        module.TypeSystem.Int32
                    );
                    GenericParameter genParam = new("T", method);
                    method.GenericParameters.Add(genParam);
                    method.Parameters.Add(new("value", MC.ParameterAttributes.None, new ByReferenceType(genParam)));
                    type.Methods.Add(method);

                    ILProcessor il = method.Body.GetILProcessor();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Conv_U);
                    il.Emit(OpCodes.Ret);

                    asm = ReflectionHelper.Load(module);
                }

                _AsPointerHelper = asm.GetType(@fullName).GetMethod(@name);
            }

            _AsPointer<T> generated = _AsPointerHelper.MakeGenericMethod(typeof(T)).CreateDelegate<_AsPointer<T>>() as _AsPointer<T>;
            lock (_AsPointerCache)
                _AsPointerCache[typeof(T)] = generated;
            return generated(ref value);
        }

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

private static void ConvertValueToEnum(ILGenerator il, Type from, Type to, Type via)
        {
            MethodInfo op;
            if (from == (via ?? to))
            {
                il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
            }
            else if ((op = GetOperator(from, to)) != null)
            {
                // this is handy for things like decimal <===> double
                il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][data-typed-value]
                il.Emit(OpCodes.Call, op); // stack is now [target][target][typed-value]
            }
            else
            {
                bool handled = false;
                OpCode opCode = default;
                switch (Type.GetTypeCode(from))
                {
                    case TypeCode.Boolean:
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                    case TypeCode.Single:
                    case TypeCode.Double:
                        handled = true;
                        switch (Type.GetTypeCode(via ?? to))
                        {
                            case TypeCode.Byte:
                                opCode = OpCodes.Conv_Ovf_I1_Un; break;
                            case TypeCode.SByte:
                                opCode = OpCodes.Conv_Ovf_I1; break;
                            case TypeCode.UInt16:
                                opCode = OpCodes.Conv_Ovf_I2_Un; break;
                            case TypeCode.Int16:
                                opCode = OpCodes.Conv_Ovf_I2; break;
                            case TypeCode.UInt32:
                                opCode = OpCodes.Conv_Ovf_I4_Un; break;
                            case TypeCode.Boolean: // boolean is basically an int, at least at this level
                            case TypeCode.Int32:
                                opCode = OpCodes.Conv_Ovf_I4; break;
                            case TypeCode.UInt64:
                                opCode = OpCodes.Conv_Ovf_I8_Un; break;
                            case TypeCode.Int64:
                                opCode = OpCodes.Conv_Ovf_I8; break;
                            case TypeCode.Single:
                                opCode = OpCodes.Conv_R4; break;
                            case TypeCode.Double:
                                opCode = OpCodes.Conv_R8; break;
                            default:
                                handled = false;
                                break;
                        }
                        break;
                }
                if (handled)
                {
                    il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][col-typed-value]
                    il.Emit(opCode); // stack is now [target][target][typed-value]
                    if (to == typeof(bool))
                    { // compare to zero; I checked "csc" - this is the trick it uses; nice
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                    }
                }
                else
                {
                    il.Emit(OpCodes.Ldtoken, via ?? to); // stack is now [target][target][value][member-type-token]
                    il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null); // stack is now [target][target][value][member-type]
                    il.EmitCall(OpCodes.Call, typeof(Convert).GetMethod(nameof(Convert.ChangeType), new Type[] { typeof(object), typeof(Type) }), null); // stack is now [target][target][boxed-member-type-value]
                    il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
                }
            }
        }

19 View Source File : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

public static TypeInfo BuildICollectionInterfaceType(DynamicFormatterreplacedembly replacedembly, Type type, Type elementType)
        {
            TypeBuilder typeBuilder = replacedembly.DefineCollectionFormatterType(type, elementType);

            MethodBuilder serializeMethod = TypeBuildHelper.DefineSerializeMethod(typeBuilder, type);
            MethodBuilder deserializeMethod = TypeBuildHelper.DefineDeserializeMethod(typeBuilder, type);
            MethodBuilder sizeMethod = TypeBuildHelper.DefineSizeMethod(typeBuilder, type);

            if (type.IsGenericType == false)
            {
                DEBUG.replacedert(type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection));
                //itemType is Object, Array2
                if (type == typeof(IList))
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIList), BindingFlags.Public | BindingFlags.Static));
                }
                else
                {
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeIEnumerable), BindingFlags.Public | BindingFlags.Static));
                }

                TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(typeof(object)));

                TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeIEnumerable), BindingFlags.Public | BindingFlags.Static));
            }
            else
            {
                Type genericTypeDefine = type.GetGenericTypeDefinition();
                DEBUG.replacedert(genericTypeDefine == typeof(IEnumerable<>) || genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(ICollection<>) || genericTypeDefine == typeof(ISet<>) || genericTypeDefine == typeof(IReadOnlyList<>) || genericTypeDefine == typeof(IReadOnlyCollection<>));

                if (Array1FormatterHelper.IsArray1Type(elementType))
                {
                    //Array1
                    TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SerializeIEnumerable), new Type[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.DeserializeSetPrefix + elementType.Name, BindingFlags.Public | BindingFlags.Static));
                    }
                    else
                    {
                        Type listFormatterType = Array1ResolverGetFormatterHelper.GetListFormatterType(elementType);
                        FieldInfo field = listFormatterType.GetField(nameof(DateTimeListFormatter.Instance), BindingFlags.Static | BindingFlags.Public);
                        MethodInfo method = listFormatterType.GetMethod(nameof(DateTimeListFormatter.Deserialize));
                        TypeBuildHelper.CallOneStaticFieldMethodInDeserialize(deserializeMethod, field, method);
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array1FormatterHelper).GetMethod(nameof(Array1FormatterHelper.SizeIEnumerable), new Type[] { typeof(BssomSizeContext).MakeByRefType(), typeof(IEnumerable<>).MakeGenericType(elementType) }));
                }
                else
                {
                    if (genericTypeDefine == typeof(IList<>) || genericTypeDefine == typeof(IReadOnlyList<>))
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenerIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInSerialize(serializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SerializeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    if (genericTypeDefine == typeof(ISet<>))
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeSet), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }
                    else
                    {
                        TypeBuildHelper.CallOneMethodInDeserialize(deserializeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.DeserializeList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                    }

                    TypeBuildHelper.CallOneMethodInSize(sizeMethod, typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.SizeGenericIEnumerable), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType));
                }
            }

            return typeBuilder.CreateTypeInfo();
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_FormatterSize(Expression formatter, Expression value)
        {
            return Expression.Call(formatter, formatter.Type.GetMethod(nameof(IBssomFormatter<int>.Size)), Par_SizeContext, value);
        }

19 View Source File : CelesteNetMainComponent.cs
License : MIT License
Project Creator : 0x0ade

public override void Initialize() {
            base.Initialize();

            MainThreadHelper.Do(() => {
                using (new DetourContext("CelesteNetMain") {
                    Before = { "*" }
                }) {
                    On.Celeste.Level.LoadLevel += OnLoadLevel;
                    Everest.Events.Level.OnExit += OnExitLevel;
                    On.Celeste.PlayerHair.GetHairColor += OnGetHairColor;
                    On.Celeste.PlayerHair.GetHairTexture += OnGetHairTexture;
                    On.Celeste.Player.Play += OnPlayerPlayAudio;
                    On.Celeste.TrailManager.Add_Vector2_Image_PlayerHair_Vector2_Color_int_float_bool_bool += OnDashTrailAdd;
                    On.Celeste.PlayerSprite.ctor += OnPlayerSpriteCtor;
                    On.Celeste.Level.LoadNewPlayer += OnLoadNewPlayer;
                    On.Celeste.Player.Added += OnPlayerAdded;

                    MethodInfo transitionRoutine =
                        typeof(Level).GetNestedType("<TransitionRoutine>d__24", BindingFlags.NonPublic)
                        ?.GetMethod("MoveNext");
                    if (transitionRoutine != null)
                        ILHookTransitionRoutine = new(transitionRoutine, ILTransitionRoutine);
                }
            });
        }

19 View Source File : CelesteNetClientUtils.cs
License : MIT License
Project Creator : 0x0ade

public static ref T AsRef<T>(IntPtr value) {
            Delegate cached;
            lock (_AsRefCache)
                _AsRefCache.TryGetValue(typeof(T), out cached);
            if (cached != null)
                return ref (cached as _AsRef<T>)(value);

            if (_AsRefHelper == null) {
                replacedembly asm;

                const string @namespace = "Celeste.Mod.CelesteNet.Client";
                const string @name = "AsRefHelper";
                const string @fullName = @namespace + "." + @name;

                using (ModuleDefinition module = ModuleDefinition.CreateModule(
                    @fullName,
                    new ModuleParameters() {
                        Kind = ModuleKind.Dll,
                        ReflectionImporterProvider = MMReflectionImporter.Provider
                    }
                )) {

                    TypeDefinition type = new(
                        @namespace,
                        @name,
                        MC.TypeAttributes.Public | MC.TypeAttributes.Abstract | MC.TypeAttributes.Sealed
                    ) {
                        BaseType = module.TypeSystem.Object
                    };
                    module.Types.Add(type);

                    MethodDefinition method = new(@name,
                        MC.MethodAttributes.Public | MC.MethodAttributes.Static | MC.MethodAttributes.HideBySig,
                        module.TypeSystem.Int32
                    );
                    GenericParameter genParam = new("T", method);
                    method.GenericParameters.Add(genParam);
                    method.Parameters.Add(new("value", MC.ParameterAttributes.None, new ByReferenceType(module.TypeSystem.Int32)));
                    method.Body.Variables.Add(new(new ByReferenceType(genParam)));
                    type.Methods.Add(method);

                    ILProcessor il = method.Body.GetILProcessor();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Stloc_0);
                    il.Emit(OpCodes.Ldloc_0);
                    il.Emit(OpCodes.Ret);

                    asm = ReflectionHelper.Load(module);
                }

                _AsRefHelper = asm.GetType(@fullName).GetMethod(@name);
            }

            _AsRef<T> generated = _AsRefHelper.MakeGenericMethod(typeof(T)).CreateDelegate<_AsRef<T>>() as _AsRef<T>;
            lock (_AsRefCache)
                _AsRefCache[typeof(T)] = generated;
            return ref generated(value);
        }

19 View Source File : MethodInvokerTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void InvokerAsyncTest()
        {
            var type = typeof(MethodInvokerMethod);
            var method1 = type.GetMethod("GetString");
            var methodInvoker1 = new MethodInvoker(method1);
            var result1 = methodInvoker1.InvokeAsync(new MethodInvokerMethod()).GetAwaiter().GetResult();
            replacedert.Equal("test string", result1);

            var method2 = type.GetMethod("Exec");
            var methodInvoker2 = new MethodInvoker(method2);
            var result2 = methodInvoker2.InvokeAsync(new MethodInvokerMethod()).GetAwaiter().GetResult();
            replacedert.Null(result2);
        }

19 View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v

public static Expression Call_SizeContextOptionResolver_GetFormatterWithVerify_Size(Expression value)
        {
            return Expression.Call(Call_GetFormatterWithVerify(SizeContextOptionResolver, value.Type), typeof(IBssomFormatter<>).MakeGenericType(value.Type).GetMethod(nameof(IBssomFormatter<int>.Size)), Par_SizeContext, value);
        }

19 View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099

static Func<T, Dictionary<string, string>> CompileSerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "original");
            var o_get_object_data = o_t.GetMethod("GetObjectData");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d"); // define object variable
            var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor
            var d_add = d_t.GetMethod("Add"); // add method

            var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
            var fc = Expression.Variable(fc_t, "fc");
            var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));

            var info_t = typeof(SerializationInfo);
            var info = Expression.Variable(info_t, "info");
            var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
            var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
            var info_get_enumerator = info_t.GetMethod("GetEnumerator");

            var ctx_t = typeof(StreamingContext);
            var ctx = Expression.Variable(ctx_t, "ctx");
            var ctx_init = Expression.MemberInit(Expression.New(ctx_t));

            var enumerator_t = typeof(SerializationInfoEnumerator);
            var enumerator = Expression.Variable(enumerator_t, "enumerator");
            var enumerator_move_next = enumerator_t.GetMethod("MoveNext");
            var enumerator_name = Expression.Property(enumerator, "Name");
            var enumerator_value = Expression.Property(enumerator, "Value");
            var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]);
            var exit_loop = Expression.Label("exit_loop");
            var body = Expression.Block(new[] { d, fc, info, ctx },
                Expression.replacedign(d, d_init),
                Expression.replacedign(fc, fc_init),
                Expression.replacedign(info, info_init),
                Expression.replacedign(ctx, ctx_init),
                Expression.Call(o, o_get_object_data, info, ctx),

                Expression.Block(new[] { enumerator },
                    Expression.replacedign(enumerator, Expression.Call(info, info_get_enumerator)),
                    Expression.Loop(
                        Expression.IfThenElse(
                            Expression.Call(enumerator, enumerator_move_next), // test
                            Expression.IfThen(
                                Expression.NotEqual(enumerator_value, Expression.Constant(null)),
                                Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string))
                            ),
                            Expression.Break(exit_loop)), // if false
                        exit_loop)),
                d); // return

            // compile
            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

See More Examples