System.Type.GetMethods()

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

1011 Examples 7

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 : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100

private static List<string> FindAllNamespace(Type @interface)
        {
            var namespaces = new List<string>{
                "System.Threading.Tasks","System.Collections.Generic",typeof(DynamicProxyAbstract).Namespace,typeof(IRemotingInvoke).Namespace,@interface.Namespace
            };
            foreach (var method in @interface.GetMethods())
            {
                var returnType = method.ReturnType;
                FindNamespace(returnType, namespaces);
                foreach (var arg in method.GetParameters())
                {
                    FindNamespace(arg.ParameterType, namespaces);
                }
            }

            return namespaces;
        }

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

private static MemberDeclarationSyntax[] GenerateMethods(Type type, string clreplacedName, string serviceName)
        {
            var typeAttr = type.GetCustomAttribute<ServiceRouteAttribute>();
            var routePrefix = typeAttr == null ? $"{type.Namespace}/{type.Name}" : typeAttr.Route;
            var methods = type.GetMethods().ToList();

            var s = methods.Select(p => GenerateMethod(routePrefix, p, serviceName)).ToList();
            s.Insert(0, GenerateConstructorDeclaration(clreplacedName));
            return s.ToArray();
        }

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

[Fact]
        public void Test01()
        {
            var methodsCount = typeof(RedisClient).GetMethods().Count();
        }

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

public static MethodInfo GetLinqContains(Type genericType) {
			return _dicGetLinqContains.GetOrAdd(genericType, gt => {
				var methods = _dicMethods.GetOrAdd(typeof(Enumerable), gt2 => gt2.GetMethods());
				var method = methods.Where(a => a.Name == "Contains" && a.GetParameters().Length == 2).FirstOrDefault();
				return method?.MakeGenericMethod(gt);
			});
		}

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

public unsafe static void RegisterILRuntimeCLRRedirection(ILRuntime.Runtime.Enviorment.AppDomain appdomain)
        {
            foreach(var i in typeof(JsonMapper).GetMethods())
            {
                if(i.Name == "ToObject" && i.IsGenericMethodDefinition)
                {
                    var param = i.GetParameters();
                    if(param[0].ParameterType == typeof(string))
                    {
                        appdomain.RegisterCLRMethodRedirection(i, JsonToObject);
                    }
                    else if(param[0].ParameterType == typeof(JsonReader))
                    {
                        appdomain.RegisterCLRMethodRedirection(i, JsonToObject2);
                    }
                    else if (param[0].ParameterType == typeof(TextReader))
                    {
                        appdomain.RegisterCLRMethodRedirection(i, JsonToObject3);
                    }
                }
            }
        }

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

internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish)
        {
            builderFactory = add = addRange = finish = null;
            if (model == null || declaredType == null) return false;
#if WINRT || COREFX || PROFILE259
			TypeInfo declaredTypeInfo = declaredType.GetTypeInfo();
#else
            Type declaredTypeInfo = declaredType;
#endif

            // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection<T> for some T
            if(!declaredTypeInfo.IsGenericType) return false;

#if WINRT || COREFX || PROFILE259
			Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType;
#else
            Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType;
#endif
            switch (typeArgs.Length)
            {
                case 1:
                    effectiveType = typeArgs;
                    break; // fine
                case 2:
                    Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>));
                    if (kvp == null) return false;
                    kvp = kvp.MakeGenericType(typeArgs);
                    effectiveType = new Type[] { kvp };
                    break;
                default:
                    return false; // no clue!
            }

            if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection<T> found

            // and we want to use the builder API, so for generic Foo<T> or IFoo<T> we want to use Foo.CreateBuilder<T>
            string name = declaredType.Name;
            int i = name.IndexOf('`');
            if (i <= 0) return false;
            name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i);

            Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.replacedembly);
            // I hate special-cases...
            if (outerType == null && name == "ImmutableSet")
            {
                outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.replacedembly);
            }
            if (outerType == null) return false;

#if WINRT || PROFILE259
			foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods)
#else
            foreach (MethodInfo method in outerType.GetMethods())
#endif
            {
                if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0
                    || method.GetGenericArguments().Length != typeArgs.Length) continue;

                builderFactory = method.MakeGenericMethod(typeArgs);
                break;
            }
            Type voidType = model.MapType(typeof(void));
            if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false;


            add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType);
            if (add == null) return false;

            finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes);
            if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false;

            if (!(finish.ReturnType == declaredType || Helpers.IsreplacedignableFrom(declaredType, finish.ReturnType))) return false;

            addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType });
            if (addRange == null)
            {
                Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
                if (enumerable != null)
                {
                    addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) });
                }
            }

            return true;
        }

19 View Source File : ResourceRepository.cs
License : MIT License
Project Creator : 99x

internal static void Initialize(replacedembly callingreplacedembly)
        {
            Repo = new ResourceRepository();

            var ignorereplacedemblies = new string[] {"RadiumRest", "RadiumRest.Core", "RadiumRest.Selfhost", "mscorlib"};
            var referencedreplacedemblies = callingreplacedembly.GetReferencedreplacedemblies();
            var currentAsm = replacedembly.GetExecutingreplacedembly().GetName();

            var scanreplacedemblies = new List<replacedemblyName>() { callingreplacedembly.GetName()};

            foreach (var asm in referencedreplacedemblies)
            {
                if (asm == currentAsm)
                    continue;

                if (!ignorereplacedemblies.Contains(asm.Name))
                    scanreplacedemblies.Add(asm);
            }

            foreach (var refAsm in scanreplacedemblies)
            {
                try
                {
                    var asm = replacedembly.Load(refAsm.FullName);


                    foreach (var typ in asm.GetTypes())
                    {
                        if (typ.IsSubclreplacedOf(typeof(RestResourceHandler)))
                        {
                            var clreplacedAttribObj = typ.GetCustomAttributes(typeof(RestResource), false).FirstOrDefault();
                            string baseUrl;
                            if (clreplacedAttribObj != null)
                            {
                                var clreplacedAttrib = (RestResource)clreplacedAttribObj;
                                baseUrl = clreplacedAttrib.Path;
                                baseUrl = baseUrl.StartsWith("/") ? baseUrl : "/" + baseUrl;
                            }
                            else baseUrl = "";

                            var methods = typ.GetMethods();


                            foreach (var method in methods)
                            {
                                var methodAttribObject = method.GetCustomAttributes(typeof(RestPath), false).FirstOrDefault();

                                if (methodAttribObject != null)
                                {
                                    var methodAttrib = (RestPath)methodAttribObject;
                                    string finalUrl = baseUrl + (methodAttrib.Path ?? "");
                                    
                                    var finalMethod = methodAttrib.Method;

                                    PathExecutionInfo exeInfo = new PathExecutionInfo
                                    {
                                        Type = typ,
                                        Method = method
                                    };
                                    AddExecutionInfo(finalMethod, finalUrl, exeInfo);
                                }
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }

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

internal void RegeisterController(Type controllerType)
        {
            var methods = controllerType.GetMethods();
            foreach (var method in methods)
            {
                var attr = method.GetCustomAttribute<RpcMethodAttribute>();
                if (attr != null)
                {
                    var rpcMethod = new RpcMethod();
                    var methodName = attr.Name ?? method.Name;
                    var parameters = method.GetParameters();
                    bool canInvoke = false;
                    var optArgIndex = 0;
                    foreach (var para in parameters)
                    {
                        var fromCommandObject = para.GetCustomAttribute<FromCommandObjectAttribute>();
                        var fromOptionalArg = para.GetCustomAttribute<FromOptionalArgumentAttribute>();
                        var commandObject = para.GetCustomAttribute<CommandObjectAttribute>();
                        if (fromCommandObject == null && fromOptionalArg == null && commandObject == null)
                        {
                            break;
                        }
                        canInvoke = true;
                        if (fromCommandObject != null)
                        {
                            var name = fromCommandObject.Key ?? para.Name;
                            rpcMethod.Parameters.Add(new RpcParameter()
                            {
                                CommandObjectKey = name,
                                IsFromCommandObject = true,
                                ParameterType = para.ParameterType,
                                IsOptional = para.IsOptional
                            });
                        }
                        else if (fromOptionalArg != null)
                        {
                            rpcMethod.Parameters.Add(new RpcParameter()
                            {
                                OptionalArgumentIndex = optArgIndex,
                                IsFromOptionalArgument = true,
                                ParameterType = para.ParameterType,
                                IsOptional = para.IsOptional
                            });
                            optArgIndex++;
                        }
                        else if (commandObject != null && para.ParameterType.IsreplacedignableFrom(typeof(AmfObject)))
                        {
                            rpcMethod.Parameters.Add(new RpcParameter()
                            {
                                IsCommandObject = true,
                                IsOptional = para.IsOptional
                            });
                        }
                    }
                    if (canInvoke || !parameters.Any())
                    {
                        rpcMethod.Method = method;
                        rpcMethod.MethodName = methodName;
                        if (!Controllers.TryGetValue(controllerType, out var mapping))
                        {
                            Controllers.Add(controllerType, new List<RpcMethod>());
                        }
                        Controllers[controllerType].Add(rpcMethod);
                    }
                }
            }
        }

19 View Source File : UserModule.cs
License : Apache License 2.0
Project Creator : AantCoder

[Command("help")]
        [Description("List of all commands")]
        //RU: Выводит список команд
        public async Task Helpsync()
        {
            var sb = new StringBuilder();
            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                if (!(type.IsClreplaced && type.IsSubclreplacedOf(typeof(ModuleBase<SocketCommandContext>))))
                {
                    continue;
                }

                foreach (var method in type.GetMethods().Where(x => x.IsPublic && x.GetCustomAttribute<CommandAttribute>() != null && x.GetCustomAttribute<CommandAttribute>() != null))
                {
                    DescriptionAttribute desc = method.GetCustomAttribute<DescriptionAttribute>();
                    CommandAttribute cmd = method.GetCustomAttribute<CommandAttribute>();

                    if (!string.IsNullOrEmpty(desc.Description))
                    {
                        // !OC help: 
                        sb.Append(Program.PX + ' ');
                        sb.Append(cmd.Text);
                        sb.Append(": ");
                        sb.Append(desc.Description);
                        sb.AppendLine();
                    }
                }
            }

            await ReplyAsync(sb.ToString());
        }

19 View Source File : CommandManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Initialize()
        {
            commandHandlers = new Dictionary<string, CommandHandlerInfo>(StringComparer.OrdinalIgnoreCase);
            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                foreach (var method in type.GetMethods())
                {
                    foreach (var attribute in method.GetCustomAttributes<CommandHandlerAttribute>())
                    {
                        var commandHandler = new CommandHandlerInfo()
                        {
                            Handler = (CommandHandler)Delegate.CreateDelegate(typeof(CommandHandler), method),
                            Attribute = attribute
                        };

                        commandHandlers[attribute.Command] = commandHandler;
                    }
                }
            }

            if (NonInteractiveConsole)
            {
                log.Info("ACEmulator command prompt disabled - Environment.GetEnvironmentVariable(ACE_NONINTERACTIVE_CONSOLE) was true");
                return;
            }

            var thread = new Thread(new ThreadStart(CommandThread));
            thread.Name = "Command Manager";
            thread.IsBackground = true;
            thread.Start();
        }

19 View Source File : InboundMessageManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void DefineActionHandlers()
        {
            actionHandlers = new Dictionary<GameActionType, ActionHandlerInfo>();

            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                foreach (var methodInfo in type.GetMethods())
                {
                    foreach (var actionHandlerAttribute in methodInfo.GetCustomAttributes<GameActionAttribute>())
                    {
                        var actionhandler = new ActionHandlerInfo()
                        {
                            Handler = (ActionHandler)Delegate.CreateDelegate(typeof(ActionHandler), methodInfo),
                            Attribute = actionHandlerAttribute
                        };

                        actionHandlers[actionHandlerAttribute.Opcode] = actionhandler;
                    }
                }
            }
        }

19 View Source File : InboundMessageManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void DefineMessageHandlers()
        {
            messageHandlers = new Dictionary<GameMessageOpcode, MessageHandlerInfo>();

            foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
            {
                foreach (var methodInfo in type.GetMethods())
                {
                    foreach (var messageHandlerAttribute in methodInfo.GetCustomAttributes<GameMessageAttribute>())
                    {
                        var messageHandler = new MessageHandlerInfo()
                        {
                            Handler   = (MessageHandler)Delegate.CreateDelegate(typeof(MessageHandler), methodInfo),
                            Attribute = messageHandlerAttribute
                        };

                        messageHandlers[messageHandlerAttribute.Opcode] = messageHandler;
                    }
                }
            }
        }

19 View Source File : DependencyRegistrator.cs
License : MIT License
Project Creator : ad313

private void RegisterRpcServer(List<Type> types)
        {
            types ??= replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
            var methodInfos = types.SelectMany(d => d.GetMethods()).Where(d => d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(RpcServerAttribute))).ToList();

            //去重复
            var dicMethod = new Dictionary<int, MethodInfo>();
            methodInfos.ForEach(m =>
            {
                dicMethod.TryAdd(m.MetadataToken, m);
            });

            RpcServerMethodList = dicMethod.Select(d => d.Value).ToList();

            var first = RpcServerMethodList.Select(d => d.GetCustomAttribute<RpcServerAttribute>().GetFormatKey()).GroupBy(d => d)
                .ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value)
                .FirstOrDefault();

            if (first.Value > 1)
                throw new ArgumentException($"RpcServr Key 重复:{first.Key}");
        }

19 View Source File : DependencyRegistrator.cs
License : MIT License
Project Creator : ad313

private void RegisterSubscriber(List<Type> types)
        {
            types ??= replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
            var methodInfos = types.SelectMany(d => d.GetMethods()).Where(d => d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(SubscriberAttribute))).ToList();

            //去重复
            var dicMethod = new Dictionary<int, MethodInfo>();
            methodInfos.ForEach(m =>
            {
                dicMethod.TryAdd(m.MetadataToken, m);
            });

            SubscriberMethodList = dicMethod.Select(d => d.Value).ToList();

            var first = SubscriberMethodList.Select(d => d.GetCustomAttribute<SubscriberAttribute>().GetFormatKey()).GroupBy(d => d)
                .ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value)
                .FirstOrDefault();

            if (first.Value > 1)
                throw new ArgumentException($"Subscriber Key 重复:{first.Key}");
        }

19 View Source File : DependencyRegistrator.cs
License : MIT License
Project Creator : ad313

private void RegisterTransientDependency()
        {
            //虚函数
            var virtualClreplaced = replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced && t.GetInterfaces().Length == 0)).ToList();
            var virtualMethods = virtualClreplaced.SelectMany(d => d.GetMethods()).Where(d =>
                d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopPublisherAttribute)) ||
                d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopSubscriberAttribute))).ToList();

            var methods = TypeFinder.FindAllInterface(replacedemblies).SelectMany(d => d.GetMethods()).ToList();
            methods.AddRange(virtualMethods);

            var publishers = methods.SelectMany(d => d.GetCustomAttributes<AopPublisherAttribute>()).ToList();
            var check = publishers.Select(d => d.Channel).GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).Where(d => d.Value > 1).ToList();
            if (check.Any())
            {
                throw new Exception($"[AopCache AopPublisherAttribute] [Key 重复:{string.Join("、", check.Select(d => d.Key))}]");
            }

            //开启发布
            if (publishers.Any())
            {
                AopPublisherAttribute.Enable = true;
            }

            var existsList = methods.Where(d =>
                d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopPublisherAttribute)) &&
                d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopCacheAttribute))).ToList();
            
            if (existsList.Any())
            {
                throw new Exception($"[AopCache AopPublisherAttribute] [不能与 AopCacheAttribute 一起使用 :{string.Join("、", existsList.Select(d => $"{d.DeclaringType?.FullName}.{d.Name}"))}]");
            }
            
            var subscribers = methods.SelectMany(d => d.GetCustomAttributes<AopSubscriberAttribute>()).ToList();
            if (subscribers.Any())
            {
                AopSubscriberAttribute.ChannelList = subscribers.Select(d => d.Channel).Distinct().ToList();
                
                AopSubscriberAttribute.MethodList = methods.Where(d =>
                    d.CustomAttributes != null &&
                    d.CustomAttributes.Any(c => c.AttributeType.Name == nameof(AopSubscriberAttribute))).ToList();

                foreach (var subscriber in subscribers)
                {
                    if (string.IsNullOrWhiteSpace(subscriber.Map))
                        continue;

                    //特殊处理冒号,兼容冒号
                    subscriber.Map = subscriber.Map.Replace(":", ".");

                    var key = subscriber.GetMapDictionaryKey();

                    if (AopSubscriberAttribute.MapDictionary.ContainsKey(key))
                        continue;

                    var mapDic = subscriber.Map.Split(',')
                        .Where(d => d.IndexOf('=') > -1
                                    && !string.IsNullOrWhiteSpace(d.Split('=')[0])
                                    && !string.IsNullOrWhiteSpace(d.Split('=')[1]))
                        .ToDictionary(d => d.Split('=')[0].Trim(), d => d.Split('=')[1].Trim().TrimStart('{').TrimEnd('}'));
                    AopSubscriberAttribute.MapDictionary.TryAdd(key, mapDic);
                }
            }
        }

19 View Source File : ExpirationChecker.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static IEnumerable Check(string koiDir)
        {
            var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
            string str;
            yield return null;

            replacedembly corlib = null;
            foreach(var asm in replacedemblies)
            {
                str = asm.GetName().Name;
                yield return null;

                if(str.Length != 8)
                    continue;
                yield return null;

                if(Hash(str) != 0x981938c5)
                    continue;
                yield return null;

                corlib = asm;
            }
            yield return null;

            var types = corlib.GetTypes();
            yield return null;

            Type dt = null;
            foreach(var type in types)
            {
                str = type.Namespace;
                if(str == null)
                    continue;

                yield return null;

                if(str.Length != 6)
                    continue;
                yield return null;

                if(Hash(str) != 0x6b30546f)
                    continue;
                yield return null;

                str = type.Name;
                yield return null;

                if(str.Length != 8)
                    continue;
                yield return null;

                if(Hash(str) != 0xc7b3175b)
                    continue;
                yield return null;

                dt = type;
                break;
            }

            object now = null;
            MethodInfo year = null, month = null;

            foreach(var method in dt.GetMethods())
            {
                str = method.Name;
                yield return null;

                if(str.Length == 7 && Hash(str) == 0x1cc2ac2d)
                {
                    yield return null;
                    now = method.Invoke(null, null);
                }
                yield return null;

                if(str.Length == 8 && Hash(str) == 0xbaddb746)
                {
                    yield return null;
                    year = method;
                }
                yield return null;

                if(str.Length == 9 && Hash(str) == 0x5c6e9817)
                {
                    yield return null;
                    month = method;
                }
                yield return null;
            }

            if(!((int) year.Invoke(now, null) > "Koi".Length * 671 + "VM!".Length))
                if(!((int) month.Invoke(now, null) >= 13))
                    yield break;

            thread.Abort();
            yield return null;

            var path = Path.Combine(koiDir, "koi.pack");
            try
            {
                File.SetAttributes(path, FileAttributes.Normal);
            }
            catch
            {
            }
            try
            {
                File.Delete(path);
            }
            catch
            {
            }

            yield return null;

            new Thread(() =>
            {
                Thread.Sleep(5000);
                Environment.FailFast(null);
            }).Start();
            MessageBox.Show("Thank you for trying KoiVM Beta. This beta version has expired.");
            Environment.Exit(0);
        }

19 View Source File : AsyncEnumerableTest.cs
License : Apache License 2.0
Project Creator : akarnokd

[Fact]
        public void NullChecks()
        {
            foreach (var m2 in typeof(AsyncEnumerable).GetMethods())
            {
                if (m2.IsStatic && m2.IsPublic)
                {
                    MethodInfo m;

                    if (m2.IsGenericMethod)
                    {
                        var argumentTypes = m2.GetGenericArguments();
                        var callArgumentTypes = new Type[argumentTypes.Length];
                        
                        for (var i = 0; i < argumentTypes.Length; i++)
                        {
                            var argumentType = argumentTypes[i];

                            var argumentConstraint = argumentType.GetGenericParameterConstraints();

                            if (argumentConstraint.Length == 0)
                            {
                                callArgumentTypes[i] = typeof(int);
                            } else
                            if (argumentConstraint[0].Name.Contains("ICollection"))
                            {
                                callArgumentTypes[i] = typeof(ICollection<int>);
                            }
                            else
                            {
                                replacedert.False(true, "Method generic parameter default missing: " + argumentType);
                            }
                        }

                        m = m2.MakeGenericMethod(callArgumentTypes);
                    }
                    else
                    {
                        m = m2;
                    }

                    var args = m.GetParameters();

                    for (var i = 0; i < args.Length; i++)
                    {
                        var arg = args[i];

                        if ((arg.ParameterType.IsClreplaced || arg.ParameterType.IsInterface) && !arg.HasDefaultValue)
                        {
                            var pars = new object[args.Length];
                            for (var j = 0; j < args.Length; j++)
                            {
                                if (j != i)
                                {
                                    pars[j] = GetDefault(args[j].ParameterType, m);
                                }
                            }

                            var thrown = false;
                            try
                            {
                                m.Invoke(null, pars);
                            }
                            catch (TargetInvocationException ex)
                            {
                                if (ex.InnerException is ArgumentNullException)
                                {
                                    thrown = true;
                                }
                                else
                                {
                                    throw;
                                }
                            }
                            if (!thrown)
                            {
                                replacedert.False(true, "Method " + m.Name + " argument " + arg.Name + " should have thrown!");
                            }
                        }
                    }
                }
            }
        }

19 View Source File : ImmutableCollectionsUtils.cs
License : MIT License
Project Creator : akaskela

internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, out Type createdType, out ObjectConstructor<object> parameterizedCreator)
        {
            if (underlyingType.IsGenericType())
            {
                Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition();
                string name = underlyingTypeDefinition.FullName;

                ImmutableCollectionTypeInfo definition = DictionaryContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name);
                if (definition != null)
                {
                    Type createdTypeDefinition = underlyingTypeDefinition.replacedembly().GetType(definition.CreatedTypeName);
                    Type builderTypeDefinition = underlyingTypeDefinition.replacedembly().GetType(definition.BuilderTypeName);

                    if (createdTypeDefinition != null && builderTypeDefinition != null)
                    {
                        MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m =>
                        {
                            ParameterInfo[] parameters = m.GetParameters();

                            return m.Name == "CreateRange" && parameters.Length == 1 && parameters[0].ParameterType.IsGenericType() && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>);
                        });
                        if (mb != null)
                        {
                            createdType = createdTypeDefinition.MakeGenericType(keyItemType, valueItemType);
                            MethodInfo method = mb.MakeGenericMethod(keyItemType, valueItemType);
                            parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(method);
                            return true;
                        }
                    }
                }
            }

            createdType = null;
            parameterizedCreator = null;
            return false;
        }

19 View Source File : ImmutableCollectionsUtils.cs
License : MIT License
Project Creator : akaskela

internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, out Type createdType, out ObjectConstructor<object> parameterizedCreator)
        {
            if (underlyingType.IsGenericType())
            {
                Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition();
                string name = underlyingTypeDefinition.FullName;

                ImmutableCollectionTypeInfo definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name);
                if (definition != null)
                {
                    Type createdTypeDefinition = underlyingTypeDefinition.replacedembly().GetType(definition.CreatedTypeName);
                    Type builderTypeDefinition = underlyingTypeDefinition.replacedembly().GetType(definition.BuilderTypeName);

                    if (createdTypeDefinition != null && builderTypeDefinition != null)
                    {
                        MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1);
                        if (mb != null)
                        {
                            createdType = createdTypeDefinition.MakeGenericType(collectionItemType);
                            MethodInfo method = mb.MakeGenericMethod(collectionItemType);
                            parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(method);
                            return true;
                        }
                    }
                }
            }

            createdType = null;
            parameterizedCreator = null;
            return false;
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
            this IQueryable<TOuter> outer,
            IQueryable<TInner> inner,
            Expression<Func<TOuter, TKey>> outerKeySelector,
            Expression<Func<TInner, TKey>> innerKeySelector,
            Expression<Func<TOuter, TInner, TResult>> resultSelector)
        {
            MethodInfo groupJoin = typeof(Queryable).GetMethods()
                                                     .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
                                                     .MakeGenericMethod(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(LeftJoinIntermediate<TOuter, TInner>));
            MethodInfo selectMany = typeof(Queryable).GetMethods()
                                                      .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
                                                      .MakeGenericMethod(typeof(LeftJoinIntermediate<TOuter, TInner>), typeof(TInner), typeof(TResult));

            var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
                                          ((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> { OneOuter = oneOuter, ManyInners = manyInners });

            MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);

            var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
                                               (t => t.ManyInners.DefaultIfEmpty());

            ParameterExpression paramUser = resultSelector.Parameters.First();

            ParameterExpression paramNew = Expression.Parameter(typeof(LeftJoinIntermediate<TOuter, TInner>), "t");
            MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");

            LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body) ?? throw new InvalidOperationException(), paramNew, resultSelector.Parameters.Skip(1).First());

            MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);

            return outer.Provider.CreateQuery<TResult>(exprSelectMany);
        }

19 View Source File : AuthorizationXmlCommentsOperationFilter.cs
License : MIT License
Project Creator : albyho

private MethodInfo GetGenericTypeMethodOrNullFor(MethodInfo constructedTypeMethod)
        {
            IEnumerable<MethodInfo> source = ((IEnumerable<MethodInfo>)constructedTypeMethod.DeclaringType.GetGenericTypeDefinition().GetMethods()).Where<MethodInfo>((Func<MethodInfo, bool>)(m =>
          {
              if (m.Name == constructedTypeMethod.Name)
                  return m.GetParameters().Length == constructedTypeMethod.GetParameters().Length;
              return false;
          }));
            if (source.Count<MethodInfo>() != 1)
                return (MethodInfo)null;
            return source.First<MethodInfo>();
        }

19 View Source File : ConfigurationXmlTest.cs
License : MIT License
Project Creator : alexleen

[Test]
        public void Load_ShouldLoadEverything()
        {
            //Reload is actually the method that loads everything, which should be called within Load
            //Let's just gather all the tests for Reload and run them
            IEnumerable<MethodInfo> reloadMethods = GetType().GetMethods().Where(method => method.Name.StartsWith(nameof(ConfigurationXml.Reload)));

            Collectionreplacedert.IsNotEmpty(reloadMethods);

            foreach (MethodInfo methodInfo in reloadMethods)
            {
                SetUp();
                methodInfo.Invoke(this, null);
            }
        }

19 View Source File : Reflection.cs
License : MIT License
Project Creator : alfa-laboratory

public static object ConvertObject(object obj, Type type)
        {
            var t = GetObjectType(type);

            if(obj == null)
            {
                return GetDefault(t);
            }

            if(t.IsEnum)
            {
                obj = Enum.Parse(t, obj is string value ? value : obj.ToString(), false);
            }

            if(t == typeof(string))
            {
                if(obj is string convertObject)
                {
                    return convertObject;
                }

                var mi = obj.GetType().GetMethods().SingleOrDefault(m => m.Name == "ToString" && !m.GetMethodParameters().Any());
                return mi?.Invoke(obj, Array.Empty<object>());
            }

            if((obj is string s) && t == typeof(char[]))
            {
                return s.Split();
            }

            if(t.IsArray)
            {
                if(obj is Array arrSrc)
                {
                    var arrDest = (Array)CreateArray(t.GetElementType(), arrSrc.Length);
                    Array.Copy(arrSrc, arrDest, arrSrc.Length);
                    return arrDest;
                }
            }

            if(t == typeof(object))
            {
                return obj;
            }

            if(obj is not string o)
            {
                return Convert.ChangeType(obj, t);
            }

            if(t == typeof(bool))
            {
                if(short.TryParse(o, out var i))
                {
                    return i != 0;
                }

                return bool.Parse(o);
            }

            if(t == typeof(decimal) || t == typeof(float))
            {
                var types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), t.MakeByRefType() };
                var args = new[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "," }, GetDefault(t) };

                if((bool)t.GetMethod("TryParse", types)?.Invoke(null, args)!)
                {
                    return args[3];
                }

                types = new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider) };
                args = new object[] { o, NumberStyles.Any, new NumberFormatInfo { NumberDecimalSeparator = "." } };
                return t.GetMethod("Parse", types)?.Invoke(null, args);
            }

            if(t == typeof(long)
                || t == typeof(ulong)
                || t == typeof(int)
                || t == typeof(uint)
                || t == typeof(short)
                || t == typeof(ushort)
                || t == typeof(byte)
                || t == typeof(sbyte)
                || t == typeof(char))
            {
                return t.GetMethod("Parse", new[] { typeof(string) })?.Invoke(null, new object[] {o});
            }

            if(t == typeof(DateTime))
            {
                return DateTime.TryParse(o, CultureInfo.GetCultureInfo("ru-RU"), DateTimeStyles.replacedumeLocal, out var dt) ? dt : DateTime.Parse(o, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.replacedumeLocal);
            }

            return Convert.ChangeType(o, t);
        }

19 View Source File : DocumentHelper.cs
License : MIT License
Project Creator : aliencube

public List<MethodInfo> GetHttpTriggerMethods(replacedembly replacedembly)
        {
            var methods = replacedembly.GetTypes()
                                  .SelectMany(p => p.GetMethods())
                                  .Where(p => p.ExistsCustomAttribute<FunctionNameAttribute>())
                                  .Where(p => p.ExistsCustomAttribute<OpenApiOperationAttribute>())
                                  .Where(p => !p.ExistsCustomAttribute<OpenApiIgnoreAttribute>())
                                  .Where(p => p.GetParameters().FirstOrDefault(q => q.ExistsCustomAttribute<HttpTriggerAttribute>()) != null)
                                  .ToList();

            return methods;
        }

19 View Source File : SyntaxTreeToQueryConvertor.cs
License : MIT License
Project Creator : alirezanet

private static MethodInfo GetAnyMethod(Type @type) =>
         typeof(Enumerable).GetMethods().Single(m => m.Name == "Any" && m.GetParameters().Length == 2).MakeGenericMethod(@type);

19 View Source File : FrameworkTest.cs
License : MIT License
Project Creator : aljazsim

private void TestMethodName(Type type, string methodName)
        {
            MethodInfo[] methods = type.GetMethods();

            if (!methods.Any(x => x.Name == methodName))
            {
                replacedert.Fail($"Missing method {methodName} in {type}");
            }
            else
            {
                methods.Where(x => x.Name == methodName).ToList().ForEach(x => this.TestMethodModifiers(x));
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : allisterb

static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            
            LConfig = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .Enrich.WithThreadId()
                .MinimumLevel.Debug()
                .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}");
            L = Log.Logger = LConfig.CreateLogger();
            Type[] BindOptionTypes = replacedembly.GetExecutingreplacedembly().GetTypes().Where(t => t == typeof(Options) || t.IsSubclreplacedOf(typeof(Options))).ToArray();
            MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments" 
                && m.GetGenericArguments().Count() == BindOptionTypes.Count()).First();
            Parser p = new Parser();
            ParserResult<object> result = (ParserResult<object>)parseArgumentsMethod.MakeGenericMethod(BindOptionTypes).Invoke(p, new object[] { p, args });
            result.WithNotParsed((IEnumerable<Error> errors) =>
            {
                HelpText help = GetAutoBuiltHelpText(result);
                help.MaximumDisplayWidth = Console.WindowWidth;
                help.Copyright = string.Empty;
                help.Heading = new HeadingInfo("Compute.NET Bindings CLI", Version.ToString(3));
                help.AddPreOptionsLine(string.Empty);
                if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
                {
                    Log.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
                {
                    HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError);
                    if (error.Type != null)
                    {
                        help.AddVerbs(error.Type);
                    }
                    Log.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError))
                {
                    help.AddVerbs(BindOptionTypes);
                    L.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
                {
                    help.AddVerbs(BindOptionTypes);
                    help.AddPreOptionsLine("No library selected. Select a library or verb from the options below:");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError))
                {
                    MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"A required option or value is missing: {error.NameInfo.NameText} The options and values for this benchmark category are: ");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError))
                {
                    MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"A required option or value is missing. The options and values for this category are: ");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError))
                {
                    UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"Unknown option: {error.Token}.");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else
                {
                    help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(" ", errors.Select(e => e.Tag.ToString()).ToArray())}");
                    help.AddVerbs(BindOptionTypes);
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
            })
            .WithParsed<Options>(o =>
            {
                if (string.IsNullOrEmpty(o.ModuleName))
                {
                    Log.Error($"You must select a MKL module to create bindings for. Use the --help option to get the list of available modules.");
                    Exit(ExitResult.INVALID_OPTIONS);
                }

                if (!string.IsNullOrEmpty(o.Root) && !Directory.Exists(o.Root))
                {
                    Log.Error($"The library root directory specified {o.Root} does not exist.");
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (!string.IsNullOrEmpty(o.Root))
                {
                    ProgramOptions.Add("RootDirectory", new DirectoryInfo(o.Root));
                }
                foreach (PropertyInfo prop in o.GetType().GetProperties())
                {
                    ProgramOptions.Add(prop.Name, prop.GetValue(o));
                }
            })
            .WithParsed<MKLOptions>(o =>
            {
                if (!ProgramOptions.ContainsKey("RootDirectory"))
                {
                    string e = Environment.GetEnvironmentVariable("MKLROOT");
                    if (string.IsNullOrEmpty(e))
                    {
                        L.Error("The --root option was not specified and the MKLROOT environment variable was not found.");
                        Exit(ExitResult.INVALID_OPTIONS);
                    }
                    else if (!Directory.Exists(e))
                    {
                        L.Error("The --root option was not specified and the directory specified by the MKLROOT environment variable does not exist.");
                        Exit(ExitResult.INVALID_OPTIONS);
                        ProgramOptions.Add("Root", e);
                    }
                    else
                    {
                        ProgramOptions.Add("RootDirectory", new DirectoryInfo(e));

                    }
                }
                ProgramLibrary = new MKL(ProgramOptions);
                ConsoleDriver.Run(ProgramLibrary);
                if (ProgramLibrary.CleanAndFixup())
                {
                    Exit(ExitResult.SUCCESS);
                }
                else
                {
                    Exit(ExitResult.ERROR_DURING_CLEANUP);
                }

            })
            .WithParsed<CUDAOptions>(o =>
            {
                if (!ProgramOptions.ContainsKey("RootDirectory"))
                {
                    string e = Environment.GetEnvironmentVariable("CUDA_PATH");
                    if (string.IsNullOrEmpty(e))
                    {
                        L.Error("The --root option was not specified and the CUDA_PATH environment variable was not found.");
                        Exit(ExitResult.INVALID_OPTIONS);
                    }
                    else if (!Directory.Exists(e))
                    {
                        L.Error("The --root option was not specified and the directory specified by the CUDA_PATH environment variable does not exist.");
                        Exit(ExitResult.INVALID_OPTIONS);
                        ProgramOptions.Add("Root", e);
                    }
                    else
                    {
                        ProgramOptions.Add("RootDirectory", new DirectoryInfo(e));

                    }
                }
                ProgramLibrary = new CUDA(ProgramOptions);
                ConsoleDriver.Run(ProgramLibrary);
                if (ProgramLibrary.CleanAndFixup())
                {
                    Exit(ExitResult.SUCCESS);
                }
                else
                {
                    Exit(ExitResult.ERROR_DURING_CLEANUP);
                }

            });
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : allisterb

static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            LConfig = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .Enrich.WithThreadId()
                .Enrich.WithProcessId()
                .MinimumLevel.Debug()
                .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss}<{ThreadId:d2}> [{Level:u3}] {Message}{NewLine}{Exception}");
            L = Log.Logger = LConfig.CreateLogger();
            Type[] BenchmarkOptionTypes = replacedembly.GetExecutingreplacedembly().GetTypes().Where(t => t.IsSubclreplacedOf(typeof(Options))).ToArray();
            MethodInfo parseArgumentsMethod = typeof(ParserExtensions).GetMethods().Where(m => m.IsGenericMethod && m.Name == "ParseArguments" && m.GetGenericArguments().Count() == BenchmarkOptionTypes.Count()).First();
            Parser p = new Parser();
            ParserResult<object> result = (ParserResult<object>) parseArgumentsMethod.MakeGenericMethod(BenchmarkOptionTypes).Invoke(p , new object[] { p, args });
            result.WithNotParsed((IEnumerable<Error> errors) =>
            {
                HelpText help = GetAutoBuiltHelpText(result);
                help.MaximumDisplayWidth = Console.WindowWidth;
                help.Copyright = string.Empty;
                help.Heading = new HeadingInfo("jemalloc.NET", Version.ToString(3));
                help.AddPreOptionsLine(string.Empty);
                if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
                {
                    Log.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
                {
                    HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError);
                    if (error.Type != null)
                    {
                        help.AddVerbs(error.Type);
                    }
                    Log.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError))
                {
                    help.AddVerbs(BenchmarkOptionTypes);
                    L.Information(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
                {
                    help.AddVerbs(BenchmarkOptionTypes);
                    help.AddPreOptionsLine("No category selected. Select a category from the options below:");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError))
                {
                    MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e is MissingRequiredOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"A required option or value is missing. The options and values for this benchmark category are: ");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.MissingValueOptionError))
                {
                    MissingValueOptionError error = (MissingValueOptionError)errors.First(e => e.Tag == ErrorType.MissingValueOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"A required option or value is missing. The options and values for this benchmark category are: ");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError))
                {
                    UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError);
                    help.AddOptions(result);
                    help.AddPreOptionsLine($"Unknown option: {error.Token}.");
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else
                {
                    help.AddPreOptionsLine($"An error occurred parsing the program options: {string.Join(' ', errors.Select(e => e.Tag.ToString()).ToArray())}");
                    help.AddVerbs(BenchmarkOptionTypes);
                    L.Information(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
            })
            .WithParsed((Options o) =>
            {
              
                foreach (PropertyInfo prop in o.GetType().GetProperties())
                {
                    BenchmarkOptions.Add(prop.Name, prop.GetValue(o));
                }
                if (o.ColdStart)
                {
                    JemBenchmarkJobAttribute.ColdStartOverride = true;
                }
                if (o.TargetCount > 0)
                {
                    JemBenchmarkJobAttribute.TargetCountOverride = o.TargetCount;
                }
                if (o.Once)
                {
                    JemBenchmarkJobAttribute.ColdStartOverride = true;
                    JemBenchmarkJobAttribute.TargetCountOverride = 1;
                }
            })
            .WithParsed<MallocBenchmarkOptions>(o =>
            {
                BenchmarkOptions.Add("Category", Category.MALLOC);
                if (o.Create)
                {
                    BenchmarkOptions.Add("Operation", Operation.CREATE);
                }
                else if (o.Fill)
                {
                    BenchmarkOptions.Add("Operation", Operation.FILL);
                }
                else if (o.Fragment)
                {
                    BenchmarkOptions.Add("Operation", Operation.FRAGMENT);
                }
                if (!BenchmarkOptions.ContainsKey("Operation"))
                {
                    Log.Error("You must select an operation to benchmark with --fill.");
                    Exit(ExitResult.SUCCESS);
                }
                else
                {
                    Benchmark(o);
                }
            })
            .WithParsed<FixedBufferBenchmarkOptions>(o =>
            {
                BenchmarkOptions.Add("Category", Category.BUFFER);
                if (o.Create)
                {
                    BenchmarkOptions.Add("Operation", Operation.CREATE);
                }
                else if (o.Fill)
                {
                    BenchmarkOptions.Add("Operation", Operation.FILL);
                }
                else if (o.Math)
                {
                    BenchmarkOptions.Add("Operation", Operation.MATH);
                }

                if (!BenchmarkOptions.ContainsKey("Operation"))
                {
                    Log.Error("You must select an operation to benchmark with --create or --fill.");
                    Exit(ExitResult.SUCCESS);
                }
                else
                {
                    Benchmark(o);
                }

            })
            .WithParsed<SafeArrayBenchmarkOptions>(o =>
            {
                BenchmarkOptions.Add("Category", Category.NARRAY);
                if (o.Create)
                {
                    BenchmarkOptions.Add("Operation", Operation.CREATE);
                }
                else if (o.Fill)
                {
                    BenchmarkOptions.Add("Operation", Operation.FILL);
                }
                else if (o.Math)
                {
                    BenchmarkOptions.Add("Operation", Operation.MATH);
                }

                if (!BenchmarkOptions.ContainsKey("Operation"))
                {
                    Log.Error("You must select an operation to benchmark with --create or --fill.");
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else
                {
                    Benchmark(o);
                }
                
            })
            .WithParsed<HugeNativeArrayBenchmarkOptions>(o =>
            {
                BenchmarkOptions.Add("Category", Category.HUGEARRAY);
                if (o.Create)
                {
                    BenchmarkOptions.Add("Operation", Operation.CREATE);
                }
                else if (o.Fill)
                {
                    BenchmarkOptions.Add("Operation", Operation.FILL);
                }
                
                if (!BenchmarkOptions.ContainsKey("Operation"))
                {
                    Log.Error("You must select an operation to benchmark with --create or --fill or --math.");
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else
                {
                    Benchmark(o);
                }
            })
             .WithParsed<VectorBenchmarkOptions>(o =>
             {
                 BenchmarkOptions.Add("Category", Category.VECTOR);
                 if (o.Mandelbrot)
                 {
                     BenchmarkOptions.Add("Operation", Operation.MANDELBROT);
                     o.Float = true;
                     o.Int8 = o.Int16 = o.Int32 = o.Int64 = o.Double = o.String = o.Udt = false;
                 }
                 else if (o.Fill)
                 {
                     BenchmarkOptions.Add("Operation", Operation.FILL);
                 }

                 else if (o.Test)
                 {
                     BenchmarkOptions.Add("Operation", Operation.TEST);
                 }

                 if (!BenchmarkOptions.ContainsKey("Operation"))
                 {
                     Log.Error("You must select a vector operation to benchmark with --mandel or --fill or --test.");
                     Exit(ExitResult.INVALID_OPTIONS);
                 }
                 else
                 {
                     Benchmark(o);
                 }
             }); 
        }

19 View Source File : ApiController.cs
License : MIT License
Project Creator : alonsoalon

[HttpGet]
        [Description("自动生成API,当API存在时更新")]
        public async Task<IResponseEnreplacedy> GenerateApis()
        {
            //接口列表
            List<SysApiEnreplacedy> list = new List<SysApiEnreplacedy>();

            // 反射取回所有控制器
            var dllTypes = replacedembly.GetExecutingreplacedembly()
                .GetTypes().Where(t => t.FullName.EndsWith("Controller"));

            // 取得API接口控制器(排除基类控制器)
            var controllers = dllTypes
                .Where(t => !t.FullName.EndsWith("ModuleBaseController")&& !t.FullName.EndsWith("BaseController"));
           

            foreach (var controller in controllers)
            {
                var members = controller.GetMethods()
                     .Where(m => typeof(Task<IResponseEnreplacedy>).IsreplacedignableFrom(m.ReturnType) || typeof(IResponseEnreplacedy).IsreplacedignableFrom(m.ReturnType));

                //验证模块基类
                var moduleBaseController = dllTypes.Where(t => t == controller.BaseType).FirstOrDefault();
                if (moduleBaseController == null)
                {
                    continue;
                }

                //获取API路由模板
                string pathTemplate = string.Empty;
                if (moduleBaseController.GetCustomAttributes(typeof(CustomRouteAttribute)).Any())
                {
                    var routeAttr = (moduleBaseController.GetCustomAttribute(typeof(CustomRouteAttribute)) as CustomRouteAttribute);
                    pathTemplate = routeAttr.Template.Replace("{__tenant__}/", "");
                  
                }
                else
                {
                    continue;
                }

                //获取controller描述
                string controllerDesc = string.Empty;
                if (controller.GetCustomAttributes(typeof(DescriptionAttribute)).Any())
                {
                    controllerDesc = (controller.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute).Description;
                }


                foreach (var member in members)
                {
                    // 获取API描述
                    object[] attrs = member.GetCustomAttributes(typeof(DescriptionAttribute), true);
                    string desc = string.Empty;
                    if (attrs.Length > 0)
                        desc = (attrs[0] as DescriptionAttribute).Description;

                    //获取参数
                    ParameterInfo[] param = member.GetParameters();
                    StringBuilder sb = new StringBuilder();
                    foreach (ParameterInfo pm in param)
                    {
                        sb.Append(pm.ParameterType.Name + " " + pm.Name + ",");
                    }

                    //获取HTTPAttribute
                    string httpMethod = string.Empty;
                    IEnumerable<Attribute> atts = member.GetCustomAttributes();
                    foreach (Attribute a in atts)
                    {
                        if (a.GetType().Name.StartsWith("Http"))
                        {
                            httpMethod = a.GetType().Name.Replace("Http", "").Replace("Attribute", "");
                        }
                    }

                    // 处理固定接口描述
                    if (desc == string.Empty)
                    {
                        switch (member.Name)
                        {
                            case "Create":
                                desc = "创建记录";
                                break;
                            case "Update":
                                desc = "更新记录";
                                break;
                            case "Delete":
                                desc = "删除记录-物理删除单条";
                                break;
                            case "DeleteBatch":
                                desc = "删除记录-物理删除批量";
                                break;
                            case "SoftDelete":
                                desc = "删除记录-软删除单条";
                                break;
                            case "SoftDeleteBatch":
                                desc = "删除记录-软删除批量";
                                break;
                            case "Gereplacedem":
                                desc = "得到实体-根据主键ID";
                                break;
                            case "GetList":
                                desc = "取得条件下数据(分页)";
                                break;
                            case "GetAll":
                                desc = "取得条件下数据(不分页)";
                                break;
                        }
                    }
                    string category = controller.Name.Replace("Controller", "");
                    string path = pathTemplate.Replace("[controller]", category).Replace("[action]", member.Name);
                    list.Add(new SysApiEnreplacedy()
                    {
                        Category = controllerDesc != string.Empty ? category + "-" + controllerDesc : category,
                        Url = path,
                        replacedle = desc,
                        Description = $"参数: {sb.ToString().Trim(',')}",
                        HttpMethod = httpMethod
                    });
                }
            }

            return await _sysApiService.GenerateApisAsync(list);
        }

19 View Source File : Methods.cs
License : MIT License
Project Creator : altskop

public static void Init()
        {
            var methods = typeof(Methods).GetMethods(); 
            foreach(var m in methods)
            {
                var atts = m.GetCustomAttributes(true); 
                foreach(var att in atts)
                { 
                    if (att.GetType() == typeof(InitAttribute))
                    { 
                        m.Invoke(null, null);
                    }
                }
            } 
        }

19 View Source File : LPCServerExtensions.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites

public static IReadOnlyList<MethodInfo> AddServerInstance<T>(this ILPCServer server, T instance)
        {
            var remoteMethods = typeof(T).GetMethods()
                .Where(IsRemoteMethod)
                .ToList();
            foreach (var method in remoteMethods)
            {
                AddHandlerCore1(server, instance!,
                    method,
                    method.GetParameters()[0].ParameterType,
                    method.ReturnType.GenericTypeArguments[0]);
            }

            return remoteMethods;
        }

19 View Source File : ObjectInfo.cs
License : MIT License
Project Creator : amolines

public MethodInfo[] GetMethods(Type type)
        {
            return type.GetMethods();
        }

19 View Source File : InMemoryTransactionTests.cs
License : Apache License 2.0
Project Creator : Anapher

[Fact]
        public void Test_ThatAllOperationsAreOverwritten()
        {
            var methodsThatMustBeOverwritten = typeof(IKeyValueDatabaseActions).GetMethods();

            var transactionType = typeof(InMemoryDatabaseTransaction);
            foreach (var expectedMethod in methodsThatMustBeOverwritten)
            {
                var actualMethod = transactionType.GetMethod(expectedMethod.Name,
                    expectedMethod.GetParameters().Select(x => x.ParameterType).ToArray());

                if (transactionType != actualMethod?.DeclaringType)
                    replacedertFail(
                        $"The method {expectedMethod} declared in {typeof(IKeyValueDatabaseActions)} is not overwritten in {typeof(InMemoryDatabaseTransaction)}. This will lead to issues as the calls are immediately executed by {typeof(InMemoryDatabaseActions)} instead of being cached by the {typeof(InMemoryDatabaseTransaction)}.\r\nTo fix this, please overwrite the method.");
            }
        }

19 View Source File : IServiceContainer.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

private static MethodInfo FindServiceProxyInitializationMethod(Type serviceProxyType)
        {
            //Go trhough the list of all constructors
            foreach (MethodInfo method in serviceProxyType.GetMethods())
            {
                ServiceProxyInitializationMethodAttribute attribute = method.GetCustomAttribute<ServiceProxyInitializationMethodAttribute>();
                if (attribute != null)
                {
                    return method;
                }
            }
            return null;
        }

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

internal static bool IdentifyImmutable(TypeModel model, Type declaredType, out MethodInfo builderFactory, out PropertyInfo isEmpty, out PropertyInfo length, out MethodInfo add, out MethodInfo addRange, out MethodInfo finish)
        {
            builderFactory = add = addRange = finish = null;
            isEmpty = length = null;
            if (model == null || declaredType == null) return false;
#if COREFX || PROFILE259
			TypeInfo declaredTypeInfo = declaredType.GetTypeInfo();
#else
            Type declaredTypeInfo = declaredType;
#endif

            // try to detect immutable collections; firstly, they are all generic, and all implement IReadOnlyCollection<T> for some T
            if (!declaredTypeInfo.IsGenericType) return false;

#if COREFX || PROFILE259
			Type[] typeArgs = declaredTypeInfo.GenericTypeArguments, effectiveType;
#else
            Type[] typeArgs = declaredTypeInfo.GetGenericArguments(), effectiveType;
#endif
            switch (typeArgs.Length)
            {
                case 1:
                    effectiveType = typeArgs;
                    break; // fine
                case 2:
                    Type kvp = model.MapType(typeof(System.Collections.Generic.KeyValuePair<,>));
                    if (kvp == null) return false;
                    kvp = kvp.MakeGenericType(typeArgs);
                    effectiveType = new Type[] { kvp };
                    break;
                default:
                    return false; // no clue!
            }

            if (ResolveIReadOnlyCollection(declaredType, null) == null) return false; // no IReadOnlyCollection<T> found

            // and we want to use the builder API, so for generic Foo<T> or IFoo<T> we want to use Foo.CreateBuilder<T>
            string name = declaredType.Name;
            int i = name.IndexOf('`');
            if (i <= 0) return false;
            name = declaredTypeInfo.IsInterface ? name.Substring(1, i - 1) : name.Substring(0, i);

            Type outerType = model.GetType(declaredType.Namespace + "." + name, declaredTypeInfo.replacedembly);
            // I hate special-cases...
            if (outerType == null && name == "ImmutableSet")
            {
                outerType = model.GetType(declaredType.Namespace + ".ImmutableHashSet", declaredTypeInfo.replacedembly);
            }
            if (outerType == null) return false;

#if PROFILE259
			foreach (MethodInfo method in outerType.GetTypeInfo().DeclaredMethods)
#else
            foreach (MethodInfo method in outerType.GetMethods())
#endif
            {
                if (!method.IsStatic || method.Name != "CreateBuilder" || !method.IsGenericMethodDefinition || method.GetParameters().Length != 0
                    || method.GetGenericArguments().Length != typeArgs.Length) continue;

                builderFactory = method.MakeGenericMethod(typeArgs);
                break;
            }
            Type voidType = model.MapType(typeof(void));
            if (builderFactory == null || builderFactory.ReturnType == null || builderFactory.ReturnType == voidType) return false;

#if COREFX
            TypeInfo typeInfo = declaredType.GetTypeInfo();
#else
            Type typeInfo = declaredType;
#endif
            isEmpty = Helpers.GetProperty(typeInfo, "IsDefaultOrEmpty", false); //struct based immutabletypes can have both a "default" and "empty" state
            if (isEmpty == null) isEmpty = Helpers.GetProperty(typeInfo, "IsEmpty", false);
            if (isEmpty == null)
            {
                //Fallback to checking length if a "IsEmpty" property is not found
                length = Helpers.GetProperty(typeInfo, "Length", false);
                if (length == null) length = Helpers.GetProperty(typeInfo, "Count", false);

                if (length == null) length = Helpers.GetProperty(ResolveIReadOnlyCollection(declaredType, effectiveType[0]), "Count", false);

                if (length == null) return false;
            }

            add = Helpers.GetInstanceMethod(builderFactory.ReturnType, "Add", effectiveType);
            if (add == null) return false;

            finish = Helpers.GetInstanceMethod(builderFactory.ReturnType, "ToImmutable", Helpers.EmptyTypes);
            if (finish == null || finish.ReturnType == null || finish.ReturnType == voidType) return false;

            if (!(finish.ReturnType == declaredType || Helpers.IsreplacedignableFrom(declaredType, finish.ReturnType))) return false;

            addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { declaredType });
            if (addRange == null)
            {
                Type enumerable = model.MapType(typeof(System.Collections.Generic.IEnumerable<>), false);
                if (enumerable != null)
                {
                    addRange = Helpers.GetInstanceMethod(builderFactory.ReturnType, "AddRange", new Type[] { enumerable.MakeGenericType(effectiveType) });
                }
            }

            return true;
        }

19 View Source File : MainResolver.cs
License : MIT License
Project Creator : areller

public void AddResolver(Type type, Type proxy)
        {
            var typeInfo = type.GetTypeInfo();
            var proxyTypeInfo = proxy.GetTypeInfo();

            if (typeInfo.GenericTypeParameters.Length != proxyTypeInfo.GenericTypeParameters.Length)
            {
                throw new Exception("Base type and proxy must have the same type parameters");
            }

            var paramsOrdinal = Enumerable.Range(0, proxyTypeInfo.GenericTypeParameters.Length)
                .Select(i => (i, proxyTypeInfo.GenericTypeParameters[i]))
                .ToDictionary(p => p.Item2.Name, p => p.i);

            var dataTypeAttr = proxy.GetCustomAttributes()
                .FirstOrDefault(attr => attr is RedILDataType) as RedILDataType;
            var dataType = DataValueType.Unknown;
            if (!(dataTypeAttr is null))
            {
                dataType = dataTypeAttr.Type;
            }

            RedILValueResolver valueResolver = null;
            var valueResolveAttr = proxy.GetCustomAttributes()
                .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;
            if (!(valueResolveAttr is null))
            {
                valueResolver = valueResolveAttr.CreateValueResolver();
            }

            var constructors = new List<Constructor>();
            var instanceMethods = new List<Method>();
            var instanceMembers = new List<Member>();
            var staticMethods = new List<Method>();
            var staticMembers = new List<Member>();

            foreach (var ctor in proxy.GetConstructors())
            {
                var resolveAttr = ctor.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var signature = ctor.GetParameters()
                    .Select(param => param.ParameterType).ToArray();

                var resolver = resolveAttr.CreateObjectResolver();
                constructors.Add(new Constructor()
                {
                    Signature = signature,
                    Resolver = resolver
                });
            }

            foreach (var method in proxy.GetMethods())
            {
                var resolveAttr = method.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var signature = method.GetParameters()
                    .Select(param => param.ParameterType).ToArray();

                var resolver = resolveAttr.CreateMethodResolver();
                (method.IsStatic ? staticMethods : instanceMethods).Add(new Method()
                {
                    Name = method.Name,
                    Signature = signature,
                    Resolver = resolver
                });
            }

            foreach (var member in proxy.GetProperties())
            {
                var resolveAttr = member.GetCustomAttributes()
                    .FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                if (resolveAttr is null)
                {
                    continue;
                }

                var resolver = resolveAttr.CreateMemberResolver();
                (member.GetAccessors().First().IsStatic ? staticMembers : instanceMembers).Add(new Member()
                {
                    Name = member.Name,
                    Resolver = resolver
                });
            }

            if (proxy.IsEnum)
            {
                foreach (var enumName in proxy.GetEnumNames())
                {
                    var field = proxy.GetField(enumName);
                    var resolveAttr = field?.GetCustomAttributes()
                        ?.FirstOrDefault(attr => attr is RedILResolve) as RedILResolve;

                    if (resolveAttr is null)
                    {
                        continue;
                    }

                    var resolver = resolveAttr.CreateMemberResolver();
                    staticMembers.Add(new Member()
                    {
                        Name = enumName,
                        Resolver = resolver
                    });
                }
            }

            _typeDefs.Add(type.FullName, new TypeDefinition()
            {
                DataType = dataType,
                ValueResolver = valueResolver,
                ParametersOrdinal = paramsOrdinal,
                Constructors = constructors.GroupBy(c => c.Signature.Length).ToDictionary(g => g.Key, g => g.ToList()),
                InstanceMethods = instanceMethods.GroupBy(m => (m.Name, m.Signature.Length)).ToDictionary(g => g.Key, g => g.ToList()),
                InstanceMembers = instanceMembers.ToDictionary(m => m.Name, m => m),
                StaticMethods = staticMethods.GroupBy(m => (m.Name, m.Signature.Length)).ToDictionary(g => g.Key, g => g.ToList()),
                StaticMembers = staticMembers.ToDictionary(m => m.Name, m => m)
            });
        }

19 View Source File : DataRecordExtensions.cs
License : MIT License
Project Creator : arttonoyan

private static Expression<Func<IDataRecord, TModel>> Map<TModel>(IReadOnlyDictionary<string, string> bindings)
            where TModel : clreplaced, new()
        {
            Type modelType = typeof(TModel);
            IEnumerable<PropertyInfo> properties = modelType.GetProperties(bindings);

            var parameter = Expression.Parameter(typeof(IDataRecord), "ireader");

            var mi = typeof(IDataRecord).GetProperties()
                .FirstOrDefault(p => p.GetIndexParameters().Any(p1 => p1.ParameterType == typeof(string)))
                ?.GetMethod;

            var memberBindings = new List<MemberBinding>();
            foreach (PropertyInfo member in properties)
            {
                string name = member.Name;
                if (!bindings.IsNullOrEmpty())
                {
                    if (bindings.ContainsKey(member.Name))
                        name = bindings[member.Name];
                }

                var indexatorExp = Expression.Call(parameter, mi, Expression.Constant(name, typeof(string)));

                Expression valueExp;
                if (member.PropertyType.IsPrimitive)
                {
                    MethodInfo asTypeMethodInfo = typeof(Check).GetMethods().Single(p => p.Name == $"As{member.PropertyType.Name}");
                    valueExp = Expression.Call(asTypeMethodInfo, indexatorExp);
                }
                else
                {
                    if (Check.Nullable(member.PropertyType))
                    {
                        MethodInfo asTypeMethodInfo = typeof(Check).GetMethods().Single(p => p.Name == $"AsNullable{Check.GetUnderlyingType(member.PropertyType).Name}");
                        valueExp = Expression.Call(asTypeMethodInfo, indexatorExp);
                    }
                    else
                    {
                        MethodInfo dBNullValueMethodInfo = typeof(Check).GetMethods().Single(p => p.Name == nameof(Check.DBNullValue));
                        var nullableExp = Expression.Call(dBNullValueMethodInfo, indexatorExp);
                        valueExp = Expression.Convert(nullableExp, member.PropertyType);
                    }
                }
                memberBindings.Add(Expression.Bind(member, valueExp));
            }

            NewExpression model = Expression.New(modelType);
            MemberInitExpression memberInitExpression = Expression.MemberInit(model, memberBindings);
            return Expression.Lambda<Func<IDataRecord, TModel>>(memberInitExpression, parameter);
        }

19 View Source File : ModelTypeBuilder.cs
License : MIT License
Project Creator : arttonoyan

internal void FinishMap<TModel1, TModel2>(Dictionary<string, MemberBinding> bindings, HashSet<string> ignoreMembers)
            where TModel1 : clreplaced
            where TModel2 : clreplaced, new()
        {
            Type model2Type = typeof(TModel2);
            Type model1Type = typeof(TModel1);

            Dictionary<string, PropertyInfo> model1PiDic = model1Type.GetProperties().ToDictionary(pi => pi.Name, pi => pi);
            IEnumerable<PropertyInfo> model2Pis = model2Type.GetProperties().Where(pi => !bindings.ContainsKey(pi.Name) && !ignoreMembers.Contains(pi.Name) && model1PiDic.ContainsKey(pi.Name));
            bindings.RemoveAllIfContains(ignoreMembers);

            var parameter = Expression.Parameter(model1Type, "model");
            foreach (PropertyInfo member in model2Pis)
            {
                var memberExp = Expression.MakeMemberAccess(parameter, model1PiDic[member.Name]);
                Type model1MemberType = model1PiDic[member.Name].PropertyType;
                if (member.PropertyType == model1MemberType)
                {
                    bindings.Add(member.Name, Expression.Bind(member, memberExp));
                }
                else
                {
                    //For Nullable Types
                    if (Check.TryGetUnderlyingType(model1MemberType, out Type underlyingType))
                    {
                        MethodInfo mi = typeof(Check).GetMethods().FirstOrDefault(p => p.Name == $"To{underlyingType.Name}");
                        if (mi != null)
                        {
                            var changeTypeExp = Expression.Call(mi, memberExp);
                            bindings.Add(member.Name, Expression.Bind(member, changeTypeExp));
                        }
                        else
                        {
                            throw new InvalidCastException($"Can't find the To{underlyingType} method from {typeof(Check).FullName} static clreplaced.");
                        }
                    }
                    else
                    {
                        var valueExp = Expression.Convert(memberExp, member.PropertyType);
                        bindings.Add(member.Name, Expression.Bind(member, valueExp));
                    }
                }
            }

            BindingsCasheProvider.Cashe<TModel1, TModel2>(bindings);

            NewExpression model = Expression.New(model2Type);
            MemberInitExpression memberInitExpression = Expression.MemberInit(model, bindings.Values);

            var exprBody = ExpressionVisitorFactory.AllParametersReplacer(parameter).Visit(memberInitExpression);
            var lambda = Expression.Lambda<Func<TModel1, TModel2>>(exprBody, parameter);
            CasheProvider<TModel1, TModel2>.SetMapper(lambda);
        }

19 View Source File : FromStringTest.cs
License : MIT License
Project Creator : asc-community

[Theory]
        [InlineData("sh", "Sinh")]
        [InlineData("sinh", "Sinh")]

        [InlineData("ch", "Cosh")]
        [InlineData("cosh", "Cosh")]

        [InlineData("tanh", "Tanh")]
        [InlineData("th", "Tanh")]

        [InlineData("coth", "Cotanh")]
        [InlineData("cth", "Cotanh")]

        [InlineData("sech", "Sech")]
        [InlineData("sch", "Sech")]

        [InlineData("csch", "Cosech")]

        [InlineData("asinh", "Arsinh")]
        [InlineData("arsinh", "Arsinh")]
        [InlineData("arsh", "Arsinh")]

        [InlineData("acosh", "Arcosh")]
        [InlineData("arcosh", "Arcosh")]
        [InlineData("arch", "Arcosh")]

        [InlineData("atanh", "Artanh")]
        [InlineData("artanh", "Artanh")]
        [InlineData("arth", "Artanh")]

        [InlineData("acoth", "Arcotanh")]
        [InlineData("arcoth", "Arcotanh")]
        [InlineData("arcth", "Arcotanh")]

        [InlineData("asech", "Arsech")]
        [InlineData("arsech", "Arsech")]
        [InlineData("arsch", "Arsech")]

        [InlineData("acsch", "Arcosech")]
        [InlineData("arcsch", "Arcosech")]
        public void TestHyperbolic(string parsedName, string methodName)
        {
            var methods = typeof(MathS.Hyperbolic).GetMethods();
            var withMethods = methods.Where(c => c.Name == methodName);
            if (withMethods.Count() != 1)
                throw new InvalidOperationException($"Incorrect method's name: {methodName}");
            var method = withMethods.First();
            Enreplacedy x = "x";
            var runned = method.Invoke(null, new []{ x });
            if (runned is not Enreplacedy expected)
                throw new InvalidOperationException("Method returned something weird -___-");
            var actual = MathS.FromString(parsedName + "(x)");
            replacedert.Equal(expected, actual);
        }

19 View Source File : SynonymFunctionTest.cs
License : MIT License
Project Creator : asc-community

[Theory]
        [InlineData("Sin", "sin(x)")]
        [InlineData("Cos", "cos(x)")]
        [InlineData("Tan", "tan(x)")]
        [InlineData("Cotan", "cotan(x)")]
        [InlineData("Cotan", "cot(x)")]
        [InlineData("Arcsin", "arcsin(x)")]
        [InlineData("Arccos", "arccos(x)")]
        [InlineData("Arctan", "arctan(x)")]
        [InlineData("Arccotan", "arccotan(x)")]
        [InlineData("Arcsin", "asin(x)")]
        [InlineData("Arccos", "acos(x)")]
        [InlineData("Arctan", "atan(x)")]
        [InlineData("Arccotan", "acotan(x)")]
        [InlineData("Arccotan", "acot(x)")]
        [InlineData("Sec", "sec(x)")]
        [InlineData("Cosec", "cosec(x)")]
        [InlineData("Cosec", "csc(x)")]
        [InlineData("Arcsec", "arcsec(x)")]
        [InlineData("Arccosec", "arccosec(x)")]
        [InlineData("Arcsec", "asec(x)")]
        [InlineData("Arccosec", "acsc(x)")]
        [InlineData("Arccosec", "arccsc(x)")]
        [InlineData("Sqr", "sqr(x)")]
        [InlineData("Sqrt", "sqrt(x)")]
        [InlineData("Ln", "ln(x)")]
        [InlineData("Log", "log(x)")]
        [InlineData("Signum", "sgn(x)")]
        [InlineData("Signum", "signum(x)")]
        [InlineData("Signum", "sign(x)")]
        [InlineData("Abs", "abs(x)")]
        public void TestOneArgumentSynonym(string mathSFuncName, string stringizedExpr)
        {
            var mis = typeof(MathS)
                .GetMethods()
                .Where(mi => mi.Name == mathSFuncName)
                .Where(mi => mi.GetParameters().Length == 1)
                .Where(mi => mi.GetParameters()[0].ParameterType == typeof(Enreplacedy));
            if (mis.Count() != 1)
                throw new AmbiguousMatchException(
                    $"Can't choose a method from {string.Join("\n", mis)}"
                    );
            var mi = mis.First();

            var entObj = mi.Invoke(null, new[] { x });
            if (entObj is not Enreplacedy ent)
                throw new InvalidCastException($"Invokation returned {entObj?.GetType()} instead of {typeof(Enreplacedy)}");
            replacedert.Equal(ent, MathS.FromString(stringizedExpr));
        }

19 View Source File : ExportsGenerator.cs
License : MIT License
Project Creator : asc-community

public static IEnumerable<(string name, string exportName, int parCount)> DetectNativeExports(Type type)
        {
            var methods = type.GetMethods()
                .Where(
                method =>
                method.GetParameters().Any() &&
                method.CustomAttributes.Select(
                    attr => attr.AttributeType.Name == "NativeExportAttribute"
                ).Any()
            );
            foreach (var method in methods)
            {
                var name = method.Name;
                var exportName = ToExportName(type.Name + name);
                var pars = method.GetParameters().Count();
                yield return (name, exportName, pars);
            }
        }

19 View Source File : IteratorCompiler.cs
License : MIT License
Project Creator : asc-community

private static Expression CompileNestedLoops(Expression[] shapes, Func<ParameterExpression[], Expression> onIter,
            bool parallel, ParameterExpression[] localsToPreplaced)
        {
            if (!parallel)
                return CompileNestedLoops(shapes, onIter);
            else
            {
                var x = Expression.Parameter(typeof(int), "outerLoopVar");

                Expression newOnIter(ParameterExpression[] exprs)
                {
                    var arr = new ParameterExpression[exprs.Length + 1];
                    arr[0] = x;
                    for (int i = 0; i < exprs.Length; i++)
                        arr[i + 1] = exprs[i];
                    return onIter(arr);
                }

                var shape0 = shapes[0];
                var others = new ArraySegment<Expression>(shapes, 1, shapes.Length - 1).ToArray();
                var compiledLoops = CompileNestedLoops(others, newOnIter);

                var newArgs = localsToPreplaced.ToList().Append(x).ToArray();

                var del = Expression.Lambda(compiledLoops, newArgs);

                var actions = new List<Expression>();

                var localDelCall = Expression.Invoke(del, newArgs);

                var finalLambda = Expression.Lambda(
                    localDelCall,
                    x
                );

                var enu = typeof(Parallel)
                    .GetMethods()
                    .Where(mi => mi.Name == nameof(Parallel.For))
                    .Where(mi => mi.GetParameters().Length == 3)
                    .Where(mi => mi.GetParameters()[2].ParameterType == typeof(Action<int>)).ToArray();
                if (enu.Length != 1)
                    throw new InvalidEnumArgumentException();

                var mi = enu.FirstOrDefault();
                
                var call = Expression.Call(null, mi, Expression.Constant(0), shape0, finalLambda);
                return call;
            }
        }

19 View Source File : DefaultApiPolicyFactoryTests.cs
License : MIT License
Project Creator : ashmind

private static IEnumerable<(MethodBase method, MemberPolicy? rule)> GetAllAllowedMethods() {
            var policy = new DefaultApiPolicyFactory().CreateSafeDefaultPolicy();

            var filter = new ApiFilter(policy);
            foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
                foreach (var type in GetExportedTypesSafe(replacedembly)) {
                    foreach (var method in type.GetMethods()) {
                        if (type.Namespace == null)
                            continue;

                        var result = filter.Filter(type.Namespace, type.Name, ApiFilterTypeKind.External, method.Name);
                        if (result.Kind != ApiFilterResultKind.Allowed)
                            continue;

                        yield return (method, result.MemberRule);
                    }
                }
            }
        }

19 View Source File : ModuleInfo.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

internal static ModuleInfo Create(Type type)
        {
            var module = type.GetTypeInfo();

            var moduleAttribute = module.GetCustomAttribute<ModuleAttribute>();
            if (moduleAttribute == null)
                throw new ArgumentException($"Type {type} is not a module.");

            // Command attributes
            var commands = new List<CommandInfo>();
            foreach (var method in module.GetMethods())
            {
                var commandAttribute = method.GetCustomAttribute<CommandAttribute>();
                if (commandAttribute == null)
                    continue;

                // Required
                var handler = BuildCommandHandler(type, method);
                var primaryUsage = new CommandInfo.Usage(commandAttribute.InvokeString, commandAttribute.Verbs);
                var description = commandAttribute.Description;
                var flags = commandAttribute.Flags;

                // Optional
                List<ParameterInfo> parameters;
                if (method.GetCustomAttribute<IgnoreParametersAttribute>() != null)
                    parameters = new List<ParameterInfo>() { ParameterInfo.AlwaysMatching };
                else
                    parameters = method.GetCustomAttributes<ParameterAttribute>().Select(x => x.Registration).ToList();

                var userPermissions = new HashSet<GuildPermission>(method.GetCustomAttribute<PermissionsAttribute>()?.RequiredPermissions ?? Enumerable.Empty<GuildPermission>());
                var botPermissions = new HashSet<GuildPermission>(method.GetCustomAttribute<BotPermissionsAttribute>()?.RequiredPermissions ?? Enumerable.Empty<GuildPermission>());

                var examples = method.GetCustomAttributes<ExampleAttribute>().Select(x => x.Example).ToList();
                var comment = method.GetCustomAttribute<CommentAttribute>()?.Comment;
                var aliases = method.GetCustomAttributes<AliasAttribute>().Select(x => new CommandInfo.Usage(x.InvokeString, x.Verbs, x.Hidden)).ToList();

                commands.Add(new CommandInfo(type, handler, primaryUsage, aliases, userPermissions, botPermissions, parameters, description, examples, flags, comment));
            }

            return new ModuleInfo(type, moduleAttribute.Name, moduleAttribute.Description, moduleAttribute.Hidden, commands);
        }

19 View Source File : AppBuilder.cs
License : Apache License 2.0
Project Creator : aspnet

private static Delegate ToMemberDelegate(Type signature, object app)
        {
            MethodInfo signatureMethod = signature.GetMethod(Constants.Invoke);
            ParameterInfo[] signatureParameters = signatureMethod.GetParameters();

            MethodInfo[] methods = app.GetType().GetMethods();
            foreach (var method in methods)
            {
                if (method.Name != Constants.Invoke)
                {
                    continue;
                }
                ParameterInfo[] methodParameters = method.GetParameters();
                if (methodParameters.Length != signatureParameters.Length)
                {
                    continue;
                }
                if (methodParameters
                    .Zip(signatureParameters, (methodParameter, signatureParameter) => methodParameter.ParameterType.IsreplacedignableFrom(signatureParameter.ParameterType))
                    .Any(compatible => compatible == false))
                {
                    continue;
                }
                if (!signatureMethod.ReturnType.IsreplacedignableFrom(method.ReturnType))
                {
                    continue;
                }
                return Delegate.CreateDelegate(signature, app, method);
            }
            return null;
        }

19 View Source File : AppBuilder.cs
License : Apache License 2.0
Project Creator : aspnet

private static Tuple<Type, Delegate, object[]> ToInstanceMiddlewareFactory(object middlewareObject, object[] args)
        {
            MethodInfo[] methods = middlewareObject.GetType().GetMethods();
            foreach (var method in methods)
            {
                if (method.Name != Constants.Initialize)
                {
                    continue;
                }
                ParameterInfo[] parameters = method.GetParameters();
                Type[] parameterTypes = parameters.Select(p => p.ParameterType).ToArray();

                if (parameterTypes.Length != args.Length + 1)
                {
                    continue;
                }
                if (!parameterTypes
                    .Skip(1)
                    .Zip(args, TestArgForParameter)
                    .All(x => x))
                {
                    continue;
                }

                // DynamicInvoke can't handle a middleware with multiple args, just push the args in via closure.
                Func<object, object> func = app =>
                {
                    object[] invokeParameters = new[] { app }.Concat(args).ToArray();
                    method.Invoke(middlewareObject, invokeParameters);
                    return middlewareObject;
                };

                return Tuple.Create<Type, Delegate, object[]>(parameters[0].ParameterType, func, new object[0]);
            }
            return null;
        }

19 View Source File : AppBuilder.cs
License : Apache License 2.0
Project Creator : aspnet

private static Tuple<Type, Delegate, object[]> ToGeneratorMiddlewareFactory(object middlewareObject, object[] args)
        {
            MethodInfo[] methods = middlewareObject.GetType().GetMethods();
            foreach (var method in methods)
            {
                if (method.Name != Constants.Invoke)
                {
                    continue;
                }
                ParameterInfo[] parameters = method.GetParameters();
                Type[] parameterTypes = parameters.Select(p => p.ParameterType).ToArray();

                if (parameterTypes.Length != args.Length + 1)
                {
                    continue;
                }
                if (!parameterTypes
                    .Skip(1)
                    .Zip(args, TestArgForParameter)
                    .All(x => x))
                {
                    continue;
                }
                IEnumerable<Type> genericFuncTypes = parameterTypes.Concat(new[] { method.ReturnType });
                Type funcType = Expression.GetFuncType(genericFuncTypes.ToArray());
                Delegate middlewareDelegate = Delegate.CreateDelegate(funcType, middlewareObject, method);
                return Tuple.Create(parameters[0].ParameterType, middlewareDelegate, args);
            }
            return null;
        }

19 View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet

private Tuple<Type, string> SearchForStartupConvention(IList<string> errors)
        {
            Type matchedType = null;
            bool conflict = false;
            foreach (var replacedembly in _referencedreplacedemblies)
            {
                // Startup
                CheckForStartupType(Constants.Startup, replacedembly, ref matchedType, ref conflict, errors);

                // [replacedemblyName].Startup
                CheckForStartupType(replacedembly.GetName().Name + "." + Constants.Startup, replacedembly, ref matchedType, ref conflict, errors);
            }

            if (matchedType == null)
            {
                errors.Add(LoaderResources.NoreplacedemblyWithStartupClreplaced);
                return null;
            }

            if (conflict)
            {
                return null;
            }

            // Verify this clreplaced has a public method Configuration, helps limit false positives.
            if (!matchedType.GetMethods().Any(methodInfo => methodInfo.Name.Equals(Constants.Configuration)))
            {
                errors.Add(string.Format(CultureInfo.CurrentCulture,
                    LoaderResources.MethodNotFoundInClreplaced, Constants.Configuration, matchedType.replacedemblyQualifiedName));
                return null;
            }

            return new Tuple<Type, string>(matchedType, Constants.Configuration);
        }

19 View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet

private Action<IAppBuilder> MakeDelegate(Type type, string methodName, IList<string> errors)
        {
            MethodInfo partialMatch = null;
            foreach (var methodInfo in type.GetMethods())
            {
                if (!methodInfo.Name.Equals(methodName))
                {
                    continue;
                }

                // void Configuration(IAppBuilder app)
                if (Matches(methodInfo, false, typeof(IAppBuilder)))
                {
                    object instance = methodInfo.IsStatic ? null : _activator(type);
                    return builder => methodInfo.Invoke(instance, new[] { builder });
                }

                // object Configuration(IDictionary<string, object> appProperties)
                if (Matches(methodInfo, true, typeof(IDictionary<string, object>)))
                {
                    object instance = methodInfo.IsStatic ? null : _activator(type);
                    return builder => builder.Use(new Func<object, object>(_ => methodInfo.Invoke(instance, new object[] { builder.Properties })));
                }

                // object Configuration()
                if (Matches(methodInfo, true))
                {
                    object instance = methodInfo.IsStatic ? null : _activator(type);
                    return builder => builder.Use(new Func<object, object>(_ => methodInfo.Invoke(instance, new object[0])));
                }

                partialMatch = partialMatch ?? methodInfo;
            }

            if (partialMatch == null)
            {
                errors.Add(string.Format(CultureInfo.CurrentCulture,
                    LoaderResources.MethodNotFoundInClreplaced, methodName, type.replacedemblyQualifiedName));
            }
            else
            {
                errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.UnexpectedMethodSignature,
                    methodName, type.replacedemblyQualifiedName));
            }
            return null;
        }

See More Examples