System.Reflection.MethodBase.Invoke(object, object[])

Here are the examples of the csharp api System.Reflection.MethodBase.Invoke(object, object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5930 Examples 7

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

public object InvokeOriginal(object obj, params object[] args)
        {
            IntPtr methodStart = originalMethodStart;
            bool wasRedirecting = isRedirecting;

            if (wasRedirecting)
                CopyToStart(originalBytes, methodStart);

            try
            {
                if (obj == null && Original.IsConstructor)
                    return ((ConstructorInfo)Original).Invoke(args);

                return Original.Invoke(obj, args);
            }
            finally
            {
                if (wasRedirecting)
                    CopyToStart(replacementBytes, methodStart);
            }
        }

19 View Source File : FolderSelectDialog.cs
License : MIT License
Project Creator : 86Box

public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string replacedle)
            {
                var openFileDialog = new OpenFileDialog
                {
                    AddExtension = false,
                    CheckFileExists = false,
                    DereferenceLinks = true,
                    Filter = c_foldersFilter,
                    InitialDirectory = initialDirectory,
                    Multiselect = false,
                    replacedle = replacedle
                };

                var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
                s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
                s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint)s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
                var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
                s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);

                try
                {
                    int retVal = (int)s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
                    return new ShowDialogResult
                    {
                        Result = retVal == 0,
                        FileName = openFileDialog.FileName
                    };
                }
                finally
                {
                    s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
                }
            }

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private object CallPrivateGenericMethod(Type typeOfT, string privateMethodName, object[] parameters)
        {
            var methodInfo = ((TypeInfo) typeof(TypeFuzzer)).DeclaredMethods.Single(m =>
                m.IsGenericMethod && m.IsPrivate && m.Name.Contains(privateMethodName));
            var generic = methodInfo.MakeGenericMethod(typeOfT);
            
            // private T GenerateInstanceOf<T>(int recursionLevel)
            var result = generic.Invoke(this, parameters);
            
            return result;
        }

19 View Source File : AssignIconTool.cs
License : MIT License
Project Creator : 5argon

[MenuItem("replacedets/Minefield/Auto-replacedign all script icons")]
        public static void replacedignIcons()
        {
            var beaconClreplacedes = MonoImporter.GetAllRuntimeMonoScripts().Where((x) =>
            {
                //There are null returning from GetClreplaced as well (why?)
                var cls = x.GetClreplaced();
                return cls == null ? false : typeof(ILabelBeacon).IsreplacedignableFrom(cls);
            });

            Texture2D navigationBeaconIcon = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(replacedetDatabase.GUIDToreplacedetPath("3d6634608b55541ddac251be41744121"));
            Texture2D testBeaconIcon = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(replacedetDatabase.GUIDToreplacedetPath("d99be7b16603541eebc812d11bb2edf4"));

            foreach (var bc in beaconClreplacedes)
            {
                Debug.Log($"[Minefield] replacedigning a new script icon to {bc.name}");
                SetIconForObject.Invoke(null, new object[] { bc,
                    typeof(IHandlerBeacon).IsreplacedignableFrom(bc.GetClreplaced()) ?
                    navigationBeaconIcon : testBeaconIcon });
                CopyMonoScriptIconToImporters.Invoke(null, new object[] { bc });
            }

            //Disable the icon in gizmos annotation.
            Array annotations = (Array)GetAnnotations.Invoke(null, null);

            foreach (var bc in beaconClreplacedes)
            {
                foreach (var a in annotations)
                {
                    string scriptClreplaced = (string)AnnotationScriptClreplaced.GetValue(a);
                    if (scriptClreplaced == bc.name)
                    {
                        int clreplacedId = (int)AnnotationClreplacedId.GetValue(a);
                        SetIconEnabled.Invoke(null, new object[] { clreplacedId, scriptClreplaced, 0 });
                    }
                }
            }
        }

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

public override object Read(object value, ProtoReader source)
        {
            object result = Tail.Read(value, source);
            if (setSpecified != null) setSpecified.Invoke(value, new object[] { true });
            return result;
        }

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

public override object Read(object value, ProtoReader source)
        {
            Helpers.Debugreplacedert(value != null);
            //object oldVal = Tail.RequiresOldValue ? property.GetValue(value, null) : null;
            object oldVal = Tail.RequiresOldValue ? property.GetGetMethod(true).Invoke(value, null) : null;
            object newVal = Tail.Read(oldVal, source);
            if (readOptionsWriteValue && newVal != null) // if the tail returns a null, intepret that as *no replacedign*
            {
                if (shadowSetter == null)
                {
                    property.SetValue(value, newVal, null);
                }
                else
                {
                    shadowSetter.Invoke(value, new object[] { newVal });
                }
            }
            return null;
        }

19 View Source File : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static T To<T>(this object value)
        {
            if (value == null) return default(T);
            Type tp = typeof(T);
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            if (tp.Name.ToLower() == "string")
            {
                return (T)value;
            }
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { value, Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            if (success)
            {
                return (T)parameters[1];
            }
            return default(T);
        }

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 : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WrapDictionary(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Amf3Dictionary<,>));
            var tKey = valueType.GetGenericArguments().First();
            var tValue = valueType.GetGenericArguments().Last();

            _writeDictionaryTMethod.MakeGenericMethod(tKey, tValue).Invoke(this, new object[] { value, context });
        }

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

void AddOrUpdateNavigateList(TEnreplacedy item) {
			Type itemType = null;
			foreach (var prop in _table.Properties) {
				if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
				if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;

				object propVal = null;

				if (itemType == null) itemType = item.GetType();
				if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
					var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
						_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
					if (lazyField != null) {
						var lazyFieldValue = (bool)lazyField.GetValue(item);
						if (lazyFieldValue == false) continue;
					}
					propVal = prop.Value.GetValue(item);
				} else {
					propVal = prop.Value.GetValue(item);
					if (propVal == null) continue;
				}

				var tref = _table.GetTableRef(prop.Key, true);
				if (tref == null) continue;

				switch(tref.RefType) {
					case Internal.Model.TableRefType.OneToOne:
					case Internal.Model.TableRefType.ManyToOne:
					case Internal.Model.TableRefType.ManyToMany:
						continue;
					case Internal.Model.TableRefType.OneToMany:
						var propValEach = propVal as IEnumerable;
						if (propValEach == null) continue;
						object dbset = null;
						MethodInfo dbsetAddOrUpdate = null;
						foreach (var propValItem in propValEach) {
							if (dbset == null) {
								dbset = _ctx.Set(tref.RefEnreplacedyType);
								dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEnreplacedyType });
							}
							for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
								tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
									.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
							}
							dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
						}
						break;
				}
			}
		}

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

private void VisitSymbol(ISymbol symbol)
        {
            // Only check methods
            if (!(symbol is IMethodSymbol method))
                return;

            // Find Invoke attribute
            var attr = method.GetAttributes().FirstOrDefault(x => x.AttributeClreplaced.Name == nameof(InvokeAttribute));

            if (attr == null)
                // No attribute found, return
                return;

            // We have the attribute, find its matching method
            var info = method.GetCorrespondingMethod() as MethodInfo;

            if (info == null)
            {
                ReportWarning("Cannot invoke given method", symbol.Locations[0]);
                return;
            }

            // Check method
            if (!method.IsStatic)
                throw new DiagnosticException("A compile-time function must be static.", symbol.Locations[0]);
            if (method.IsAbstract)
                throw new DiagnosticException("A compile-time function cannot be abstract.", symbol.Locations[0]);
            if (method.ReturnType.MetadataName != "Void")
                ReportWarning("A compile-time function should return void.", symbol.Locations[0]);

            // Populate args
            ParameterInfo[] parameters = info.GetParameters();
            object[] arguments = new object[parameters.Length];

            for (int i = 0; i < parameters.Length; i++)
            {
                ParameterInfo parameter = parameters[i];
                TypeInfo parameterType = parameter.ParameterType.GetTypeInfo();

                if (parameterType.IsreplacedignableFrom(typeof(IMethodSymbol).GetTypeInfo()))
                    arguments[i] = method;
                else if (parameterType.IsreplacedignableFrom(typeof(MethodInfo).GetTypeInfo()))
                    arguments[i] = info;
                else if (parameter.ParameterType.IsreplacedignableFrom(typeof(ITypeSymbol)))
                    arguments[i] = symbol.ContainingType;
                else if (parameter.ParameterType == typeof(TypeInfo))
                    arguments[i] = info.DeclaringType.GetTypeInfo();
                else if (parameter.ParameterType == typeof(Type))
                    arguments[i] = info.DeclaringType;
            }

            // Invoke and return
            try
            {
                info.Invoke(null, arguments);
            }
            catch (Exception e)
            {
                ReportError(e.Message, symbol.Locations[0]);
            }
        }

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

public override void Write(object value, ProtoWriter dest)
        {
            Helpers.Debugreplacedert(value != null);
            //value = property.GetValue(value, null);
            value = property.GetGetMethod(true).Invoke(value, null);
            if(value != null) Tail.Write(value, dest);
        }

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

public override bool TryGet(string key, bool publicOnly, out object value)
            {
                MemberInfo[] members = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly);
                foreach (MemberInfo member in members)
                {
#if FX11
                    if (member.Name.ToUpper() == key.ToUpper())
#else
                    if (string.Equals(member.Name, key, StringComparison.OrdinalIgnoreCase))
#endif
                    {
                        PropertyInfo prop = member as PropertyInfo;
                        if (prop != null) {
                            //value = prop.GetValue(attribute, null);
                            value = prop.GetGetMethod(true).Invoke(attribute, null);
                            return true;
                        }
                        FieldInfo field = member as FieldInfo;
                        if (field != null) {
                            value = field.GetValue(attribute);
                            return true;
                        }

                        throw new NotSupportedException(member.GetType().Name);
                    }
                }
                value = null;
                return false;
            }

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

public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            IInvocationExpression invocation = semanticModel.GetOperation(node, cancellationToken) as IInvocationExpression;

            if (invocation == null)
                return base.VisitInvocationExpression(node);

            bool IsMacroMethod(ISymbol methodSymbol, out string error)
            {
                foreach (var attr in methodSymbol.GetAttributes())
                {
                    if (attr.AttributeClreplaced.MetadataName != nameof(ExpandAttribute))
                        continue;

                    if (!methodSymbol.IsStatic)
                        error = "The target method must be static.";
                    else
                        error = null;

                    return true;
                }

                error = null;
                return false;
            }

            // Check if it's a call to a macro method
            var target = invocation.TargetMethod;

            if (!IsMacroMethod(target, out string err))
                return base.VisitInvocationExpression(node);

            // Make sure it's valid
            if (err != null)
                throw new DiagnosticException($"Cannot call the specified method as a macro method: {err}.",
                                              invocation.Syntax.GetLocation());

            // It is a method, find it
            MethodInfo method = target.GetCorrespondingMethod() as MethodInfo;

            if (method == null)
                throw new DiagnosticException("Cannot find corresponding method.", invocation.Syntax.GetLocation());

            // Found it, make the arguments
            ParameterInfo[] parameters = method.GetParameters();
            object[] arguments = new object[parameters.Length];

            for (int i = 0; i < arguments.Length; i++)
            {
                ParameterInfo param = parameters[i];
                Type paramType = param.ParameterType;

                if (param.HasDefaultValue)
                    arguments[i] = param.DefaultValue;
                else
                    arguments[i] = paramType.GetTypeInfo().IsValueType
                        ? Activator.CreateInstance(paramType)
                        : null;
            }

            // Set up the context
            var statementSyntax = node.FirstAncestorOrSelf<StatementSyntax>();
            var statementSymbol = new Lazy<IOperation>(() => semanticModel.GetOperation(statementSyntax, cancellationToken));

            var callerSymbol = new Lazy<IMethodSymbol>(() => semanticModel.GetEnclosingSymbol(statementSyntax.SpanStart, cancellationToken) as IMethodSymbol);
            var callerInfo = new Lazy<MethodInfo>(() => callerSymbol.Value?.GetCorrespondingMethod() as MethodInfo);

            ExpressionSyntax expr;
            StatementSyntax stmt;

            using (CallBinder.EnterContext(invocation, statementSymbol, node, statementSyntax, method, target, callerInfo, callerSymbol))
            {
                // Invoke the method
                try
                {
                    method.Invoke(null, arguments);
                }
                catch (Exception e)
                {
                    throw new DiagnosticException($"Exception thrown when expanding the '{method}' macro.", e, invocation.Syntax.GetLocation());
                }

                (expr, stmt) = CallBinder.Result;
            }

            // Edit the node accordingly
            if (stmt != statementSyntax)
            {
                // Return the new statement
                changes.Add(statementSyntax, stmt.WithTriviaFrom(statementSyntax).Accept(this) as StatementSyntax);
                return node;
            }

            return base.Visit(expr == node ? expr : expr.WithTriviaFrom(node));
        }

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 : MacroExpander.cs
License : MIT License
Project Creator : 71

public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
        {
            IOperation operation = semanticModel.GetOperation(node, cancellationToken);

            if (operation == null || !operation.IsInvalid)
                return base.VisitMemberAccessExpression(node);

            // Expression is invalid, might be a late-bound object
            IOperation expression = semanticModel.GetOperation(node.Expression, cancellationToken);

            if (expression.IsInvalid)
                return base.VisitMemberAccessExpression(node);

            // Find out if it is a late-bound object...
            INamedTypeSymbol type = expression.Type as INamedTypeSymbol;

            if (type == null)
                return base.VisitMemberAccessExpression(node);

            // ... by finding its Bind method
            object[] arguments = null;

            bool IsValidBindMethod(MethodInfo mi)
            {
                if (!mi.IsStatic || mi.IsAbstract || mi.Name != "Bind")
                    return false;

                if (!typeof(ExpressionSyntax).IsreplacedignableFrom(mi.ReturnType))
                    return false;

                ParameterInfo[] parameters = mi.GetParameters();
                object[] args = new object[parameters.Length];

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

                    if (paramType.IsreplacedignableFrom(typeof(MemberAccessExpressionSyntax)))
                        args[i] = node;
                    else if (paramType == typeof(IOperation))
                        args[i] = expression;
                    else
                        return false;
                }

                arguments = args;
                return true;
            }

            Type correspondingType = type.GetCorrespondingType();

            if (correspondingType == null)
                return base.VisitMemberAccessExpression(node);

            MethodInfo bindMethod = correspondingType
                .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                .FirstOrDefault(IsValidBindMethod);

            if (bindMethod == null)
                return base.VisitMemberAccessExpression(node);

            // We do have a binder!
            // Call the method
            try
            {
                ExpressionSyntax result = bindMethod.Invoke(null, arguments) as ExpressionSyntax;

                return result == null
                    ? SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)
                    : base.Visit(result);
            }
            catch (Exception e)
            {
                throw new DiagnosticException("Error thrown by binding method.", e, node.GetLocation());
            }
        }

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 : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static object Invoke(this object instance, string methodName, params object[] args)
        {
            if (null == instance) return null;
            var type = instance.GetType();
            var key = type.FullName + methodName;
            var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;

            if (!s_MethodInfoDic.ContainsKey(key))
            {
                s_MethodInfoDic.Add(key, type.GetMethod(methodName, bindingFlags));
            }

            return s_MethodInfoDic[key].Invoke(instance,args);
        }

19 View Source File : cMain.cs
License : MIT License
Project Creator : 0xPh0enix

[STAThread]
        static void Main()
        {
            replacedembly aASM = replacedembly.GetExecutingreplacedembly();

            using (Stream sResStream = aASM.GetManifestResourceStream("%RES_NAME%"))
            {
                if (sResStream == null)
                    return;

                byte[] bFile = new byte[sResStream.Length];
                sResStream.Read(bFile, 0, bFile.Length);

                bFile = Decrypt(bFile, System.Text.Encoding.Default.GetBytes("%ENC_KEY%"));

                replacedembly.Load(bFile).EntryPoint.Invoke(null, null);

            }
        }

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

private void WrapVector(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Vector<>));
            var vectorT = valueType.GetGenericArguments().First();

            _writeVectorTMethod.MakeGenericMethod(vectorT).Invoke(this, new object[] { value, context });
        }

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

public override object Read(object value, ProtoReader source)
        {
            try
            {
                int field = source.FieldNumber;
                object origValue = value;
                if (value == null) value = Activator.CreateInstance(concreteType);
                bool isList = IsList && !SuppressIList;
                if (packedWireType != WireType.None && source.WireType == WireType.String)
                {
                    SubItemToken token = ProtoReader.StartSubItem(source);
                    if (isList)
                    {
                        IList list = (IList)value;
                        while (ProtoReader.HreplacedubValue(packedWireType, source))
                        {
                            list.Add(Tail.Read(null, source));
                        }
                    }
                    else
                    {
                        object[] args = new object[1];
                        while (ProtoReader.HreplacedubValue(packedWireType, source))
                        {
                            args[0] = Tail.Read(null, source);
                            add.Invoke(value, args);
                        }
                    }
                    ProtoReader.EndSubItem(token, source);
                }
                else
                {
                    if (isList)
                    {
                        IList list = (IList)value;
                        do
                        {
                            list.Add(Tail.Read(null, source));
                        } while (source.TryReadFieldHeader(field));
                    }
                    else
                    {
                        object[] args = new object[1];
                        do
                        {
                            args[0] = Tail.Read(null, source);
                            add.Invoke(value, args);
                        } while (source.TryReadFieldHeader(field));
                    }
                }
                return origValue == value ? null : value;
            } catch(TargetInvocationException tie)
            {
                if (tie.InnerException != null) throw tie.InnerException;
                throw;
            }
        }

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

public override void Write(object value, ProtoWriter dest)
        {
            if(getSpecified == null || (bool)getSpecified.Invoke(value, null))
            {
                Tail.Write(value, dest);
            }
        }

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

public static TypeInfo Build(DynamicFormatterreplacedembly replacedembly, ObjectSerializationInfo serializationInfo)
        {
            Type type = serializationInfo.Type;
            TypeBuilder typeBuilder = replacedembly.DefineFormatterType(type);
            serializationInfo.SerializeMemberInfosOrderByKeyIndex(type);

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

            Type delegateCacheType = typeof(Array3DelegateCache<>).MakeGenericType(type);
            delegateCacheType.GetMethod(nameof(Array3DelegateCache<int>.Factory), BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { replacedembly, serializationInfo });

            TypeBuildHelper.CallSerializeDelegate(serializeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Serialize)));
            TypeBuildHelper.CallSizeDelegate(sizeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Size)));
            TypeBuildHelper.CallDeserializeDelegate(deserializeMethod, type, delegateCacheType.GetField(nameof(Array3DelegateCache<int>.Deserialize)));

            return typeBuilder.CreateTypeInfo();
        }

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

public object Read(object value, ProtoReader source)
        {
            Helpers.Debugreplacedert(value == null); // since replaces
            return parse.Invoke(null, new object[] { source.ReadString() });
        }

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 : TupleSerializer.cs
License : MIT License
Project Creator : 404Lcc

private object GetValue(object obj, int index)
        {
            PropertyInfo prop;
            FieldInfo field;

            if ((prop = members[index] as PropertyInfo) != null)
            {
                if (obj == null)
                    return Helpers.IsValueType(prop.PropertyType) ? Activator.CreateInstance(prop.PropertyType) : null;
                //return prop.GetValue(obj, null);
                return prop.GetGetMethod(true).Invoke(obj, null);
            }
            else if ((field = members[index] as FieldInfo) != null)
            {
                if (obj == null)
                    return Helpers.IsValueType(field.FieldType) ? Activator.CreateInstance(field.FieldType) : null;
                return field.GetValue(obj);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }

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

public void Write(object value, ProtoWriter writer)
        {
            rootTail.Write(toTail.Invoke(null, new object[] { value }), writer);
        }

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

private static object ReadValue (Type inst_type, JsonReader reader)
        {
            reader.Read ();

            if (reader.Token == JsonToken.ArrayEnd)
                return null;

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type = inst_type;

            if (reader.Token == JsonToken.Null) {
                if (inst_type.IsClreplaced || underlying_type != null) {
                    return null;
                }

                throw new JsonException (String.Format (
                            "Can't replacedign null to an instance of type {0}",
                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean) {

                Type json_type = reader.Value.GetType();
                var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.IsreplacedignableFrom(json_type))
                    return reader.Value;
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                        return reader.Value;
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey (json_type) &&
                    custom_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey (json_type) &&
                    base_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                    return Enum.ToObject (vt, reader.Value);

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp (vt, json_type);

                if (conv_op != null)
                    return conv_op.Invoke (null,
                                           new object[] { reader.Value });

                // No luck
                throw new JsonException (String.Format (
                        "Can't replacedign value '{0}' (type {1}) to type {2}",
                        reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart) {

                AddArrayMetadata (inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (! t_data.IsArray && ! t_data.IsList)
                    throw new JsonException (String.Format (
                            "Type {0} can't act as an array",
                            inst_type));

                IList list;
                Type elem_type;

                if (! t_data.IsArray) {
                    list = (IList) Activator.CreateInstance (inst_type);
                    elem_type = t_data.ElementType;
                } else {
                    list = new ArrayList ();
                    elem_type = inst_type.GetElementType ();
                }

                while (true) {
                    object item = ReadValue (elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                        break;
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = (int) item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);            
                    }
                    list.Add (item);         
                    
                }

                if (t_data.IsArray) {
                    int n = list.Count;
                    instance = Array.CreateInstance (elem_type, n);

                    for (int i = 0; i < n; i++)
                        ((Array) instance).SetValue (list[i], i);
                } else
                    instance = list;

            } else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                    instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
                else
                    instance = Activator.CreateInstance(value_type);
                bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                        break;

                    string key = (string) reader.Value;

                    if (t_data.Properties.ContainsKey(key))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[key];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo) prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo) prop_data.Info;

                            if (p_info.CanWrite)
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            else
                                ReadValue(prop_data.Type, reader);
                        }

                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {

                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                    "The type {0} doesn't have the " +
                                    "property '{1}'",
                                    inst_type, key));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var dict = ((IDictionary) instance);
                        var elem_type = t_data.ElementType;
                        object readValue = ReadValue(elem_type, reader);
                        var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
                            : t_data.ElementType;
                        //value 是枚举的情况没处理,毕竟少
                        if (isIntKey)
                        {
                            var dictValueType = value_type.GetGenericArguments()[1];
                            IConvertible convertible = dictValueType as IConvertible;
                            if (convertible == null)
                            {
                                //自定义类型扩展
                                if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
                                {
                                    var v = Convert.ChangeType(readValue.ToString(), dictValueType);
                                    dict.Add(Convert.ToInt32(key), v);
                                }
                                else
                                {
                                    readValue = rt.CheckCLRTypes(readValue);
                                    dict.Add(Convert.ToInt32(key), readValue);
                                    // throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
                                }
                            }
                            else
                            {
                                var v = Convert.ChangeType(readValue, dictValueType);
                                dict.Add(Convert.ToInt32(key), v);
                            }
                        }
                        else
                        {
                            readValue = rt.CheckCLRTypes(readValue);
                            dict.Add(key, readValue);
                        }
                    }

                }
            }

            return instance;
        }

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

public bool TryInvoke(string name, object[] args, out object result)
        {
            object obj = Object;

            // Compute key, and try to find an already computed delegate
            int key = Combine(Combine(ObjectTypeHash, name.GetHashCode()), args.Length.GetHashCode());
            var objType = obj.GetType();

            if (data.Invokers.TryGetValue(key, out var del))
            {
                result = del(obj, args);
                return true;
            }

            // Nothing already computed, compute it now
            MethodInfo mi = FindMatchingMethod(objType.GetMethods(ALL), name, args) as MethodInfo;

            if (mi == null)
            {
                result = null;
                return false;
            }

            result = mi.Invoke(obj, args);
            return true;

            // TODO: Fix this. I can't get it to work.
            //data.Invokers[key] = del = Helpers.MakeDelegate<Func<object, object[], object>>(name, il =>
            //{
            //    bool isStatic = mi.IsStatic;

            //    if (!isStatic)
            //    {
            //        Type declaringType = mi.DeclaringType;

            //        il.Emit(OpCodes.Ldarg_0);

            //        if (declaringType.GetTypeInfo().IsValueType)
            //        {
            //            LocalBuilder loc = il.DeclareLocal(declaringType, false);

            //            il.Emit(OpCodes.Unbox_Any, declaringType);
            //            il.Emit(OpCodes.Stloc, loc);
            //            il.Emit(OpCodes.Ldloca, loc);
            //        }
            //        else // Who the f proxies object? if (declaringType != typeof(object))
            //        {
            //            il.Emit(OpCodes.Castclreplaced, declaringType);
            //        }
            //    }

            //    for (int j = 0; j < parameters.Length; j++)
            //    {
            //        Type type = parameters[j].ParameterType;

            //        il.Emit(OpCodes.Ldarg_1);
            //        il.Emit(OpCodes.Ldc_I4, j);
            //        il.Emit(OpCodes.Ldelem_Ref);

            //        if (type.GetTypeInfo().IsValueType)
            //            il.Emit(OpCodes.Unbox_Any, type);
            //        else if (type != typeof(object))
            //            il.Emit(OpCodes.Castclreplaced, type);
            //    }

            //    il.Emit(isStatic || mi.DeclaringType.GetTypeInfo().IsValueType ? OpCodes.Call : OpCodes.Callvirt, mi);

            //    if (mi.ReturnType.GetTypeInfo().IsValueType)
            //    {
            //        il.Emit(OpCodes.Box, mi.ReturnType);
            //    }
            //    else if (mi.ReturnType == typeof(void))
            //    {
            //        il.Emit(OpCodes.Ldnull);
            //    }

            //    il.Emit(OpCodes.Ret);
            //}, mi.DeclaringType);

            //result = del(obj, args);
            //return true;
        }

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 : NotchSimulatorUtility.cs
License : MIT License
Project Creator : 5argon

internal static Vector2 GetMainGameViewSize()
        {
#if UNITY_2019_3_OR_NEWER
            return (Vector2)GetSizeOfMainGameView.Invoke(null, null);
#else
            System.Object Res = GetSizeOfMainGameView.Invoke(null, argsForOut);
            return (Vector2)argsForOut[0];
#endif
        }

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

public override object Read(object value, ProtoReader source)
        {
            object builderInstance = builderFactory.Invoke(null, null);
            int field = source.FieldNumber;
            object[] args = new object[1];
            if (AppendToCollection && value != null && ((ICollection)value).Count != 0)
            {   
                if(addRange !=null)
                {
                    args[0] = value;
                    addRange.Invoke(builderInstance, args);
                }
                else
                {
                    foreach(object item in (ICollection)value)
                    {
                        args[0] = item;
                        add.Invoke(builderInstance, args);
                    }
                }
            }

            if (packedWireType != WireType.None && source.WireType == WireType.String)
            {
                SubItemToken token = ProtoReader.StartSubItem(source);
                while (ProtoReader.HreplacedubValue(packedWireType, source))
                {
                    args[0] = Tail.Read(null, source);
                    add.Invoke(builderInstance, args);
                }
                ProtoReader.EndSubItem(token, source);
            }
            else
            {
                do
                {
                    args[0] = Tail.Read(null, source);
                    add.Invoke(builderInstance, args);
                } while (source.TryReadFieldHeader(field));
            }

            return finish.Invoke(builderInstance, null);
        }

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

public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
        {
            // First, try the good ol' RuntimeHelpers.PrepareMethod.
            if (PrepareMethod != null)
            {
                PrepareMethod(handle);
                return true;
            }

            // No chance, we gotta go lower.
            // Invoke the method with uninitialized arguments.
            object sender = null;

            object[] GetArguments(ParameterInfo[] parameters)
            {
                object[] args = new object[parameters.Length];

                for (int i = 0; i < parameters.Length; i++)
                {
                    ParameterInfo param = parameters[i];

                    if (param.HasDefaultValue)
                        args[i] = param.DefaultValue;
                    else if (param.ParameterType.GetTypeInfo().IsValueType)
                        args[i] = Activator.CreateInstance(param.ParameterType);
                    else
                        args[i] = null;
                }

                return args;
            }

            if (!method.IsStatic)
            {
                // Gotta make the instance
                Type declaringType = method.DeclaringType;

                if (declaringType.GetTypeInfo().IsValueType)
                {
                    sender = Activator.CreateInstance(declaringType);
                }
                else if (declaringType.GetTypeInfo().IsAbstract)
                {
                    // Overkill solution: Find a type in the replacedembly that implements the declaring type,
                    // and use it instead.
                    throw new InvalidOperationException("Cannot manually JIT a method");
                }
                else if (GetUninitializedObject != null)
                {
                    sender = GetUninitializedObject(declaringType);
                }
                else
                {
                    /* TODO
                     * Since I just made the whole 'gotta JIT the method' step mandatory
                     * in the MethodRedirection ctor, i should make sure this always returns true.
                     * That means looking up every type for overriding types for the throwing step above,
                     * and testing every possible constructor to create the instance.
                     * 
                     * Additionally, if we want to go even further, we can repeat this step for every
                     * single argument of the ctor, thus making sure that we end up having an actual clreplaced.
                     * In this case, unless the user wants to instantiate an abstract clreplaced with no overriding clreplaced,
                     * everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
                     * may mean scanning the replacedembly a dozen times for overriding types, calling their constructors
                     * hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
                     * perfs-friendly).
                     */
                    ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);

                    if (ctor != null)
                    {
                        sender = ctor.Invoke(null);
                    }
                    else
                    {
                        ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);

                        Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));

                        ctor = ctors[0];

                        try
                        {
                            sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
                        }
                        catch (TargetInvocationException)
                        {
                            // Nothing we can do, give up.
                            return false;
                        }
                    }
                }
            }

            try
            {
                method.Invoke(sender, GetArguments(method.GetParameters()));
            }
            catch (TargetInvocationException)
            {
                // That's okay.
            }

            return true;
        }

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

public void RegisterHandlersIn(object owner) {
            if (RegisteredHandlers.ContainsKey(owner))
                return;

            List<Tuple<Type, DataHandler>> handlers = RegisteredHandlers[owner] = new();
            List<Tuple<Type, DataFilter>> filters = RegisteredFilters[owner] = new();

            foreach (MethodInfo method in owner.GetType().GetMethods()) {
                if (method.Name == "Handle" || method.Name == "Filter") {
                    ParameterInfo[] args = method.GetParameters();
                    if (args.Length != 2 || !args[0].ParameterType.IsCompatible(typeof(CelesteNetConnection)))
                        continue;

                    Type argType = args[1].ParameterType;
                    if (!argType.IsCompatible(typeof(DataType)))
                        continue;

                    if (method.Name == "Filter") {
                        Logger.Log(LogLevel.VVV, "data", $"Autoregistering filter for {argType}: {method.GetID()}");
                        DataFilter filter = (con, data) => method.Invoke(owner, new object[] { con, data }) as bool? ?? false;
                        filters.Add(Tuple.Create(argType, filter));
                        RegisterFilter(argType, filter);

                    } else {
                        Logger.Log(LogLevel.VVV, "data", $"Autoregistering handler for {argType}: {method.GetID()}");
                        DataHandler handler = (con, data) => method.Invoke(owner, new object[] { con, data });
                        handlers.Add(Tuple.Create(argType, handler));
                        RegisterHandler(argType, handler);
                    }
                }
            }
        }

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

public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
            {
                // First, try the good ol' RuntimeHelpers.PrepareMethod.
                if (PrepareMethod != null)
                {
                    PrepareMethod(handle);
                    return true;
                }

                // No chance, we gotta go lower.
                // Invoke the method with uninitialized arguments.
                object sender = null;

                object[] GetArguments(ParameterInfo[] parameters)
                {
                    object[] args = new object[parameters.Length];

                    for (int i = 0; i < parameters.Length; i++)
                    {
                        ParameterInfo param = parameters[i];

                        if (param.HasDefaultValue)
                            args[i] = param.DefaultValue;
                        else if (param.ParameterType.GetTypeInfo().IsValueType)
                            args[i] = Activator.CreateInstance(param.ParameterType);
                        else
                            args[i] = null;
                    }

                    return args;
                }

                if (!method.IsStatic)
                {
                    // Gotta make the instance
                    Type declaringType = method.DeclaringType;

                    if (declaringType.GetTypeInfo().IsValueType)
                    {
                        sender = Activator.CreateInstance(declaringType);
                    }
                    else if (declaringType.GetTypeInfo().IsAbstract)
                    {
                        // Overkill solution: Find a type in the replacedembly that implements the declaring type,
                        // and use it instead.
                        throw new InvalidOperationException("Cannot manually JIT a method");
                    }
                    else if (GetUninitializedObject != null)
                    {
                        sender = GetUninitializedObject(declaringType);
                    }
                    else
                    {
                        /* TODO
                         * Since I just made the whole 'gotta JIT the method' step mandatory
                         * in the MethodRedirection ctor, i should make sure this always returns true.
                         * That means looking up every type for overriding types for the throwing step above,
                         * and testing every possible constructor to create the instance.
                         * 
                         * Additionally, if we want to go even further, we can repeat this step for every
                         * single argument of the ctor, thus making sure that we end up having an actual clreplaced.
                         * In this case, unless the user wants to instantiate an abstract clreplaced with no overriding clreplaced,
                         * everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
                         * may mean scanning the replacedembly a dozen times for overriding types, calling their constructors
                         * hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
                         * perfs-friendly).
                         */
                        ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);

                        if (ctor != null)
                        {
                            sender = ctor.Invoke(null);
                        }
                        else
                        {
                            ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);

                            Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));

                            ctor = ctors[0];

                            try
                            {
                                sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
                            }
                            catch (TargetInvocationException)
                            {
                                // Nothing we can do, give up.
                                return false;
                            }
                        }
                    }
                }

                try
                {
                    method.Invoke(sender, GetArguments(method.GetParameters()));
                }
                catch (TargetInvocationException)
                {
                    // That's okay.
                }

                return true;
            }

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

private object InvokeCallback(MethodInfo method, object obj, SerializationContext context)
        {
            object result = null;
            object[] args;
            if (method != null)
            {   // preplaced in a streaming context if one is needed, else null
                bool handled;
                ParameterInfo[] parameters = method.GetParameters();
                switch (parameters.Length)
                {
                    case 0:
                        args = null;
                        handled = true;
                        break;
                    default:
                        args = new object[parameters.Length];
                        handled = true;
                        for (int i = 0; i < args.Length; i++)
                        {
                            object val;
                            Type paramType = parameters[i].ParameterType;
                            if (paramType == typeof(SerializationContext)) val = context;
                            else if (paramType == typeof(System.Type)) val = constructType;
#if PLAT_BINARYFORMATTER || (SILVERLIGHT && NET_4_0)
                            else if (paramType == typeof(System.Runtime.Serialization.StreamingContext)) val = (System.Runtime.Serialization.StreamingContext)context;
#endif
                            else
                            {
                                val = null;
                                handled = false;
                            }
                            args[i] = val;
                        }
                        break;
                }
                if(handled)
                {
                    result = method.Invoke(obj, args);
                }
                else
                { 
                    throw Meta.CallbackSet.CreateInvalidCallbackSignature(method);
                }

            }
            return result;
        }

19 View Source File : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static object To(this object value,Type tp)
        {
            if (value == null) return null;

            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            if (tp.Name.ToLower() == "string")
            {
                return value;
            }
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { value, Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            if (success)
            {
                return parameters[1];
            }
            return null;
        }

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 : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static object Invoke(this object instance,string methodName,Type[] argTypes,object[] args)
        {
            if (null == instance) return null;
            var type = instance.GetType();
            var key = type.FullName + methodName;
            var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
            if (!s_MethodInfoDic.ContainsKey(key))
            {
                s_MethodInfoDic.Add(key, type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, argTypes, new ParameterModifier[] { new ParameterModifier(argTypes.Length) }));
            }
            return s_MethodInfoDic[key].Invoke(instance, args);
        }

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 : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static void Invoke(Type type,string methodName,params object[] args)
            {
                BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
                var method = type.GetMethod(methodName,bindingFlags);
                method.Invoke(null,args);
            }

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

protected override void CreateModMenuSectionHeader(TextMenu menu, bool inGame, EventInstance snapshot) {
            base.CreateModMenuSectionHeader(menu, inGame, snapshot);

            CelesteNetModShareComponent sharer = Context?.Get<CelesteNetModShareComponent>();
            if (sharer != null && !inGame) {
                List<EverestModuleMetadata> requested;
                lock (sharer.Requested)
                    requested = new List<EverestModuleMetadata>(sharer.Requested);

                if (requested.Count != 0) {
                    TextMenu.Item item;
                    menu.Add(item = new TextMenu.Button("modoptions_celestenetclient_recommended".DialogClean()).Pressed(() => {
                        f_OuiDependencyDownloader_MissingDependencies.SetValue(null, requested);
                        m_Overworld_Goto_OuiDependencyDownloader.Invoke(Engine.Scene, Dummy<object>.EmptyArray);
                    }));

                    item.AddDescription(
                        menu,
                        "modoptions_celestenetclient_recommendedhint".DialogClean()
                        .Replace("((list))", string.Join(", ", requested.Select(r => r.DLL)))
                    );
                }
            }
        }

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 : 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 : DbSetAsync.cs
License : MIT License
Project Creator : 2881099

async Task AddOrUpdateNavigateListAsync(TEnreplacedy item) {
			Type itemType = null;
			foreach (var prop in _table.Properties) {
				if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
				if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
				var tref = _table.GetTableRef(prop.Key, true);
				if (tref == null) continue;

				switch (tref.RefType) {
					case Internal.Model.TableRefType.OneToOne:
					case Internal.Model.TableRefType.ManyToOne:
					case Internal.Model.TableRefType.ManyToMany:
						continue;
					case Internal.Model.TableRefType.OneToMany:
						if (itemType == null) itemType = item.GetType();
						if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
							var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, System.Reflection.FieldInfo>()).GetOrAdd(prop.Key, propName =>
								_table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance));
							if (lazyField != null) {
								var lazyFieldValue = (bool)lazyField.GetValue(item);
								if (lazyFieldValue == false) continue;
							}
						}
						var propVal = prop.Value.GetValue(item);
						var propValEach = propVal as IEnumerable;
						if (propValEach == null) continue;
						object dbset = null;
						System.Reflection.MethodInfo dbsetAddOrUpdate = null;
						foreach (var propValItem in propValEach) {
							if (dbset == null) {
								dbset = _ctx.Set(tref.RefEnreplacedyType);
								dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEnreplacedyType });
							}
							for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
								tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
									.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
							}
							Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task;
							await task;
						}
						break;
				}
			}
		}

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

public override void Init(CelesteNetServerModuleWrapper wrapper) {
            base.Init(wrapper);

            Logger.Log(LogLevel.VVV, "frontend", "Scanning for endpoints");
            foreach (Type t in CelesteNetUtils.GetTypes()) {
                foreach (MethodInfo m in t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) {
                    foreach (RCEndpointAttribute epa in m.GetCustomAttributes(typeof(RCEndpointAttribute), false)) {
                        RCEndpoint ep = epa.Data;
                        Logger.Log(LogLevel.VVV, "frontend", $"Found endpoint: {ep.Path} - {ep.Name} ({m.Name}::{t.FullName})");
                        ep.Handle = (f, c) => m.Invoke(null, new object[] { f, c });
                        EndPoints.Add(ep);
                    }
                }
            }

            Server.OnConnect += OnConnect;
            Server.OnSessionStart += OnSessionStart;
            using (Server.ConLock.R())
                foreach (CelesteNetPlayerSession session in Server.Sessions)
                    session.OnEnd += OnSessionEnd;
            Server.OnDisconnect += OnDisconnect;

            Server.Channels.OnBroadcastList += OnBroadcastChannels;

            ChatModule chat = Server.Get<ChatModule>();
            chat.OnReceive += OnChatReceive;
            chat.OnForceSend += OnForceSend;
        }

19 View Source File : MainActivity.cs
License : Microsoft Public License
Project Creator : 0x0ade

public static void SDL_Main()
		{
			if (string.IsNullOrEmpty(Instance.GamePath))
			{
				AlertDialog dialog = null;
				Instance.RunOnUiThread(() =>
				{
					using (AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Instance))
					{
						StringBuilder stringBuilder = new StringBuilder();
						stringBuilder.Append("Game not found: ").AppendLine(Game);
						foreach (Java.IO.File root in Instance.GetExternalFilesDirs(null))
						{
							stringBuilder.AppendLine();
							stringBuilder.AppendLine(Path.Combine(root.AbsolutePath, Game));
						}

						dialogBuilder.SetMessage(stringBuilder.ToString());
						dialogBuilder.SetCancelable(false);
						dialog = dialogBuilder.Show();
					}
				});

				while (dialog == null || dialog.IsShowing)
				{
					System.Threading.Thread.Sleep(0);
				}
				dialog.Dispose();
				return;
			}

			// Replace the following with whatever was in your Program.Main method.

			/*/
			using (TestGame game = new TestGame())
			{
				game.Run();
			}
			/*/
			replacedembly.LoadFrom(Instance.GamePath).EntryPoint.Invoke(null, new object[] { new string[] { /*args*/ } });
			/**/
		}

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 : 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 : SurrogateSerializer.cs
License : MIT License
Project Creator : 404Lcc

public object Read(object value, ProtoReader source)
        {
            // convert the incoming value
            object[] args = { value };
            value = toTail.Invoke(null, args);
            
            // invoke the tail and convert the outgoing value
            args[0] = rootTail.Read(value, source);
            return fromTail.Invoke(null, args);
        }

See More Examples