Here are the examples of the csharp api System.Type.GetMethods(System.Reflection.BindingFlags) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1213 Examples
19
Source : Frontend.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public override void Init(CelesteNetServerModuleWrapper wrapper) {
base.Init(wrapper);
Logger.Log(LogLevel.VVV, "frontend", "Scanning for endpoints");
foreach (Type t in CelesteNetUtils.GetTypes()) {
foreach (MethodInfo m in t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) {
foreach (RCEndpointAttribute epa in m.GetCustomAttributes(typeof(RCEndpointAttribute), false)) {
RCEndpoint ep = epa.Data;
Logger.Log(LogLevel.VVV, "frontend", $"Found endpoint: {ep.Path} - {ep.Name} ({m.Name}::{t.FullName})");
ep.Handle = (f, c) => m.Invoke(null, new object[] { f, c });
EndPoints.Add(ep);
}
}
}
Server.OnConnect += OnConnect;
Server.OnSessionStart += OnSessionStart;
using (Server.ConLock.R())
foreach (CelesteNetPlayerSession session in Server.Sessions)
session.OnEnd += OnSessionEnd;
Server.OnDisconnect += OnDisconnect;
Server.Channels.OnBroadcastList += OnBroadcastChannels;
ChatModule chat = Server.Get<ChatModule>();
chat.OnReceive += OnChatReceive;
chat.OnForceSend += OnForceSend;
}
19
Source : XnaToFnaUtil.Processor.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public void SetupHooks() {
// To use XnaToFnaGame properly, the actual game override needs to call XnaToFnaGame::.ctor as "base" instead.
Modder.RelinkMap["System.Void Microsoft.Xna.Framework.Game::.ctor()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaGame", "System.Void .ctor()");
Modder.ForceCallMap["System.Void XnaToFna.XnaToFnaGame::.ctor()"] = OpCodes.Call;
foreach (MethodInfo method in typeof(XnaToFnaGame).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
Modder.RelinkMap[method.GetFindableID(type: "Microsoft.Xna.Framework.Game")] =
new RelinkMapEntry("XnaToFna.XnaToFnaGame", method.GetFindableID(withType: false));
Modder.ForceCallMap[method.GetFindableID(withType: true)] = OpCodes.Call;
}
// XNA games expect a WinForms handle. Give it a "proxy" handle instead.
if (HookCompat) {
Modder.RelinkMap["System.IntPtr Microsoft.Xna.Framework.GameWindow::get_Handle()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.IntPtr GetProxyFormHandle(Microsoft.Xna.Framework.GameWindow)");
}
// X360 games can be larger than the screen. Allow the user to "fix" this by forcing a display resolution via env vars.
if (HookHacks) {
Modder.RelinkMap["System.Void Microsoft.Xna.Framework.GraphicsDeviceManager::ApplyChanges()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.Void ApplyChanges(Microsoft.Xna.Framework.GraphicsDeviceManager)");
}
// Let's just completely wreck everything.
foreach (Type type in typeof(Form).replacedembly.GetTypes()) {
string name = type.FullName;
// Subsreplacedute WinForms for ProxyForms
if (HookCompat && name.StartsWith("XnaToFna.ProxyForms."))
Modder.RelinkMap["System.Windows.Forms." + name.Substring(9 + 11)] = name;
// Subsreplacedute common Drawing clreplacedes (f.e. Rectangle) with our own for Drawing-less environments (f.e. Android)
else if (HookCompat && name.StartsWith("XnaToFna.ProxyDrawing."))
Modder.RelinkMap["System.Drawing." + name.Substring(9 + 13)] = name;
// Some XNA games use DInput... let's just subsreplacedute all DInput references with our ProxyDInput.
else if (name.StartsWith("XnaToFna.ProxyDInput."))
Modder.RelinkMap[/* no namespace */ name.Substring(9 + 12)] = name;
// Some X360 games use Microsoft.Xna.Framework.Xdk; let's just stub whatever's required in XTF.
else if (name.StartsWith("XnaToFna.StubXDK.")) {
string nameXDK = "Microsoft.Xna.Framework." + name.Substring(9 + 8);
Modder.RelinkMap[nameXDK] = name;
// Unfortunately, the signatures refer to GamerServices, while XnaToFna itself can't refer to that.
// Let's abuse the MonoModHook attribtue.
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) {
MonoModHook hook = method.GetCustomAttribute<MonoModHook>();
if (hook != null) {
Modder.RelinkMap[hook.FindableID] = new RelinkMapEntry(name, method.GetFindableID(withType: false));
}
}
foreach (ConstructorInfo ctor in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) {
MonoModHook hook = ctor.GetCustomAttribute<MonoModHook>();
if (hook != null) {
Modder.RelinkMap[hook.FindableID] = new RelinkMapEntry(name, ctor.GetFindableID(withType: false));
}
}
}
}
if (HookHacks)
Modder.RelinkMap["System.Boolean Microsoft.Xna.Framework.GamerServices.Guide::get_IsTrialMode()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.IntPtr get_IsTrialMode()");
if (HookBinaryFormatter) {
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::.ctor()"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Create()");
// The longest relink mapping ever seen...
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::.ctor(System.Runtime.Serialization.ISurrogateSelector,System.Runtime.Serialization.StreamingContext)"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Create(System.Runtime.Serialization.ISurrogateSelector,System.Runtime.Serialization.StreamingContext)");
Modder.RelinkMap["System.Runtime.Serialization.SerializationBinder System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::get_Binder()"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.SerializationBinder get_Binder(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter)");
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::set_Binder(System.Runtime.Serialization.SerializationBinder)"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Void set_Binder(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,System.Runtime.Serialization.SerializationBinder)");
}
if (HookReflection) {
Modder.RelinkMap["System.Reflection.FieldInfo System.Type::GetField(System.String,System.Reflection.BindingFlags)"] =
new RelinkMapEntry("XnaToFna.ProxyReflection.FieldInfoHelper", "System.Reflection.FieldInfo GetField(System.Type,System.String,System.Reflection.BindingFlags)");
Modder.RelinkMap["System.Reflection.FieldInfo System.Type::GetField(System.String)"] =
new RelinkMapEntry("XnaToFna.ProxyReflection.FieldInfoHelper", "System.Reflection.FieldInfo GetField(System.Type,System.String)");
}
// X360 uses the ".NET Compact Framework", which actually ships with some additional stuff...
Modder.RelinkMap["System.Void System.Threading.Thread::SetProcessorAffinity(System.Int32[])"] =
new RelinkMapEntry("XnaToFna.X360Helper", "System.Void SetProcessorAffinity(System.Threading.Thread,System.Int32[])");
}
19
Source : MethodJitter.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
static IEnumerable<MethodBase> GetMethods(Type type) {
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
foreach (var c in type.GetConstructors(flags))
yield return c;
foreach (var m in type.GetMethods(flags))
yield return m;
}
19
Source : ControllerResolver.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
private void LoadControllers()
{
ControllerFeature controllerFeature = new ControllerFeature();
_partManager.PopulateFeature(controllerFeature);
foreach (TypeInfo item2 in controllerFeature.Controllers.ToList())
{
if (item2.IsAbstract)
{
continue;
}
ControllerDescriptor controllerDescriptor = new ControllerDescriptor
{
Name = item2.Name.Replace("Controller", ""),
Description = _attributeHelper.GetDescription(item2),
Actions = new List<ActionDescriptor>(),
TypeInfo = item2
};
AreaAttribute areaAttribute = (AreaAttribute)Attribute.GetCustomAttribute(item2, typeof(AreaAttribute));
if (areaAttribute != null)
{
controllerDescriptor.Area = areaAttribute.RouteValue;
}
MethodInfo[] methods = item2.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
foreach (MethodInfo methodInfo in methods)
{
if (methodInfo.CustomAttributes.Any(m => m.AttributeType == typeof(HttpGetAttribute) || m.AttributeType == typeof(HttpPostAttribute) || m.AttributeType == typeof(HttpPutAttribute) || m.AttributeType == typeof(HttpOptionsAttribute) || m.AttributeType == typeof(HttpHeadAttribute) || m.AttributeType == typeof(HttpPatchAttribute) || m.AttributeType == typeof(HttpDeleteAttribute)))
{
ActionDescriptor item = new ActionDescriptor
{
Name = methodInfo.Name,
MethodInfo = methodInfo
};
controllerDescriptor.Actions.Add(item);
}
}
Controllers.Add(controllerDescriptor);
}
}
19
Source : TypeExtension.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static IEnumerable<MethodInfo> GetApis(this Type type)
{
var addMethods = type.GetEvents().Select(_event => _event.GetAddMethod());
var removeMethods = type.GetEvents().Select(_event => _event.GetRemoveMethod());
var getMethods = type.GetProperties().Select(_propety => _propety.GetGetMethod());
var setMethods = type.GetProperties().Select(_propety => _propety.GetSetMethod());
var enumerable = addMethods
.Concat(removeMethods)
.Concat(getMethods)
.Concat(setMethods)
.Where(_method=>_method != null)
.Select(_method => _method.Name);
var methods = enumerable.ToList();
methods.Add("Dispose");
return type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(_method=> !methods.Contains(_method.Name));
}
19
Source : DynamicProxy.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
{
if (type == null) return null;
var typeCSharpName = type.DisplayCsharp();
if (type.IsNotPublic)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
return null;
}
var matchedMemberInfos = new List<MemberInfo>();
var matchedAttributes = new List<DynamicProxyAttribute>();
var matchedAttributesFromServices = new List<FieldInfo[]>();
var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
var methodOverrideSb = new StringBuilder();
var sb = methodOverrideSb;
#region Common Code
Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
{
var sbt = new StringBuilder();
for (var a = attrsIndex; a < matchedAttributes.Count; a++)
{
sbt.Append($@"{(proxyMethodName == "Before" ? $@"
var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
__DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
{(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
{(proxyMethodName == "Before" ?
$@"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
}}" :
$"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
}
return sbt.ToString();
};
Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
{
var sbt = new StringBuilder();
var taskType = returnType.ReturnTypeWithoutTask();
sbt.Append($@"
{(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
(taskType.IsValueType || taskType.IsGenericParameter ?
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
) :
(returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
return sbt.ToString();
};
Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
{
return $@"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
};
#endregion
#region Methods
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => method));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
if (method.IsVirtual == false || method.IsFinal)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
continue;
}
#if net40
var returnType = method.ReturnType;
var methodIsAsync = false;
#else
var returnType = method.ReturnType.ReturnTypeWithoutTask();
var methodIsAsync = method.ReturnType.IsTask();
//if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
// attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
//{
//}
#endif
var baseInvoke = type.IsInterface == false ? $@"
try
{{
if (__DP_ARG___is_return == false)
{{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
{(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}" : "";
sb.Append($@"
{(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
}}");
}
#endregion
var propertyOverrideSb = new StringBuilder();
sb = propertyOverrideSb;
#region Property
var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
foreach (var prop2 in props)
{
var getMethod = prop2.GetGetMethod(false);
var setMethod = prop2.GetSetMethod(false);
if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
{
if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
continue;
}
}
var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
var prop2AttributeAny = attrs.Any();
var getMethodAttributeAny = prop2AttributeAny;
var setMethodAttributeAny = prop2AttributeAny;
if (attrs.Any() == false && getMethod?.IsVirtual == true)
{
attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
getMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false && setMethod?.IsVirtual == true)
{
attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
setMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => prop2));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();
var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
if (propSetModification == propModification) propSetModification = "";
if (propGetModification == propModification) propGetModification = "";
//if (getMethod.IsAbstract) sb.Append("abstract ");
sb.Append($@"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append($@"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append($@"
{propGetModification} get
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
}}");
}
if (setMethod != null)
{
if (setMethodAttributeAny == false) sb.Append($@"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append($@"
{propSetModification} set
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
__DP_ARG___parameters.Add(""value"", value);
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false)
{{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
base.{prop2.Name} = value;
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
}}");
}
sb.Append($@"
}}");
}
#endregion
string proxyCscode = "";
replacedembly proxyreplacedembly = null;
Type proxyType = null;
if (matchedMemberInfos.Any())
{
#region Constructors
sb = new StringBuilder();
var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append($@"
{(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
(ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => $@"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append($@"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public clreplaced {clreplacedName} : {typeCSharpName}
{{
private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));
//这里要注释掉,如果重写的基类没有无参构造函数,会报错
//public {clreplacedName}({_metaName} meta)
//{{
// __DP_Meta = meta;
//}}
{sb.ToString()}
{methodOverrideSb.ToString()}
{propertyOverrideSb.ToString()}
}}";
proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
}
methodOverrideSb.Clear();
propertyOverrideSb.Clear();
sb.Clear();
return new DynamicProxyMeta(
type, ctors,
matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
}
19
Source : SurrogateSerializer.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static bool HasCast(TypeModel model, Type type, Type from, Type to, out MethodInfo op)
{
#if WINRT || PROFILE259
System.Collections.Generic.List<MethodInfo> list = new System.Collections.Generic.List<MethodInfo>();
foreach (var item in type.GetRuntimeMethods())
{
if (item.IsStatic) list.Add(item);
}
MethodInfo[] found = list.ToArray();
#else
const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
MethodInfo[] found = type.GetMethods(flags);
#endif
ParameterInfo[] paramTypes;
Type convertAttributeType = null;
for (int i = 0; i < found.Length; i++)
{
MethodInfo m = found[i];
if (m.ReturnType != to) continue;
paramTypes = m.GetParameters();
if(paramTypes.Length == 1 && paramTypes[0].ParameterType == from)
{
if (convertAttributeType == null)
{
convertAttributeType = model.MapType(typeof(ProtoConverterAttribute), false);
if (convertAttributeType == null)
{ // attribute isn't defined in the source replacedembly: stop looking
break;
}
}
if (m.IsDefined(convertAttributeType, true))
{
op = m;
return true;
}
}
}
for(int i = 0 ; i < found.Length ; i++)
{
MethodInfo m = found[i];
if ((m.Name != "op_Implicit" && m.Name != "op_Explicit") || m.ReturnType != to)
{
continue;
}
paramTypes = m.GetParameters();
if(paramTypes.Length == 1 && paramTypes[0].ParameterType == from)
{
op = m;
return true;
}
}
op = null;
return false;
}
19
Source : Server.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
private void RegisterRoutes() {
if (registeredRoutes == null) {
registeredRoutes = new List<RouteAttribute>();
foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
foreach (Type type in replacedembly.GetTypes()) {
// FIXME add support for non-static methods (FindObjectByType?)
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
RouteAttribute[] attrs = method.GetCustomAttributes(typeof(RouteAttribute), true) as RouteAttribute[];
if (attrs.Length == 0)
continue;
RouteAttribute.Callback cbm = Delegate.CreateDelegate(typeof(RouteAttribute.Callback), method, false) as RouteAttribute.Callback;
if (cbm == null) {
Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console route.", type, method.Name));
continue;
}
// try with a bare action
foreach (RouteAttribute route in attrs) {
if (route.m_route == null) {
Debug.LogError(string.Format("Method {0}.{1} needs a valid route regexp.", type, method.Name));
continue;
}
route.m_callback = cbm;
registeredRoutes.Add(route);
}
}
}
}
RegisterFileHandlers();
}
}
19
Source : Proxy.cs
with MIT License
from 71
with MIT License
from 71
public bool TryInvoke(string name, object[] args, out object result)
{
object obj = Object;
// Compute key, and try to find an already computed delegate
int key = Combine(Combine(ObjectTypeHash, name.GetHashCode()), args.Length.GetHashCode());
var objType = obj.GetType();
if (data.Invokers.TryGetValue(key, out var del))
{
result = del(obj, args);
return true;
}
// Nothing already computed, compute it now
MethodInfo mi = FindMatchingMethod(objType.GetMethods(ALL), name, args) as MethodInfo;
if (mi == null)
{
result = null;
return false;
}
result = mi.Invoke(obj, args);
return true;
// TODO: Fix this. I can't get it to work.
//data.Invokers[key] = del = Helpers.MakeDelegate<Func<object, object[], object>>(name, il =>
//{
// bool isStatic = mi.IsStatic;
// if (!isStatic)
// {
// Type declaringType = mi.DeclaringType;
// il.Emit(OpCodes.Ldarg_0);
// if (declaringType.GetTypeInfo().IsValueType)
// {
// LocalBuilder loc = il.DeclareLocal(declaringType, false);
// il.Emit(OpCodes.Unbox_Any, declaringType);
// il.Emit(OpCodes.Stloc, loc);
// il.Emit(OpCodes.Ldloca, loc);
// }
// else // Who the f proxies object? if (declaringType != typeof(object))
// {
// il.Emit(OpCodes.Castclreplaced, declaringType);
// }
// }
// for (int j = 0; j < parameters.Length; j++)
// {
// Type type = parameters[j].ParameterType;
// il.Emit(OpCodes.Ldarg_1);
// il.Emit(OpCodes.Ldc_I4, j);
// il.Emit(OpCodes.Ldelem_Ref);
// if (type.GetTypeInfo().IsValueType)
// il.Emit(OpCodes.Unbox_Any, type);
// else if (type != typeof(object))
// il.Emit(OpCodes.Castclreplaced, type);
// }
// il.Emit(isStatic || mi.DeclaringType.GetTypeInfo().IsValueType ? OpCodes.Call : OpCodes.Callvirt, mi);
// if (mi.ReturnType.GetTypeInfo().IsValueType)
// {
// il.Emit(OpCodes.Box, mi.ReturnType);
// }
// else if (mi.ReturnType == typeof(void))
// {
// il.Emit(OpCodes.Ldnull);
// }
// il.Emit(OpCodes.Ret);
//}, mi.DeclaringType);
//result = del(obj, args);
//return true;
}
19
Source : Visitor.Expressions.cs
with MIT License
from 71
with MIT License
from 71
public override Expression VisitInvocationExpression(InvocationExpressionSyntax node)
{
if (node.Expression is MemberAccessExpressionSyntax access)
{
var syntaxArgs = node.ArgumentList.Arguments;
Expression[] arguments = new Expression[syntaxArgs.Count];
Expression expr = access.Expression.Accept(this);
GenericNameSyntax generic = access.Name as GenericNameSyntax;
bool isGeneric = generic != null;
Type[] genericTypes = null;
string name = access.Name.Identifier.Text;
bool isStatic = expr is TypeExpression;
bool FindGenericMethod(MethodInfo match)
{
if (genericTypes == null)
genericTypes = generic.TypeArgumentList.Arguments.Select(AsType);
return match.IsGenericMethod
&& match.IsStatic == isStatic
&& match.GetParameters().Length == arguments.Length
&& match.GetGenericArguments().Length == genericTypes.Length;
}
bool FindMethod(MethodInfo match)
{
return match.IsStatic == isStatic
&& !match.IsGenericMethod
&& match.GetParameters().Length == arguments.Length;
}
MethodInfo method = isGeneric
? expr.Type.GetTypeInfo()
.GetMethods(name).First(FindGenericMethod)
: expr.Type.GetTypeInfo()
.GetMethods(name).First(FindMethod);
if (isGeneric)
method = method.MakeGenericMethod(genericTypes);
ParameterInfo[] parameters = method.GetParameters();
for (int i = 0; i < arguments.Length; i++)
{
arguments[i] = Convert(syntaxArgs[i].Accept(this), parameters[i].ParameterType);
}
return Expression.Call(expr is TypeExpression ? null : expr, method, arguments);
}
return node.Expression.Accept(this);
}
19
Source : Shell.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
private void RegisterAttributes() {
#if !NETFX_CORE
foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
// HACK: IL2CPP crashes if you attempt to get the methods of some clreplacedes in these replacedemblies.
if (replacedembly.FullName.StartsWith("System") || replacedembly.FullName.StartsWith("mscorlib")) {
continue;
}
foreach (Type type in replacedembly.GetTypes()) {
// FIXME add support for non-static methods (FindObjectByType?)
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
CommandAttribute[] attrs = method.GetCustomAttributes(typeof(CommandAttribute), true) as CommandAttribute[];
if (attrs.Length == 0)
continue;
CommandAttribute.Callback cb = Delegate.CreateDelegate(typeof(CommandAttribute.Callback), method, false) as CommandAttribute.Callback;
if (cb == null) {
CommandAttribute.CallbackSimple cbs = Delegate.CreateDelegate(typeof(CommandAttribute.CallbackSimple), method, false) as CommandAttribute.CallbackSimple;
if (cbs != null) {
cb = delegate (string[] args) {
cbs();
};
}
}
if (cb == null) {
Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console command.", type, method.Name));
continue;
}
// try with a bare action
foreach (CommandAttribute cmd in attrs) {
if (string.IsNullOrEmpty(cmd.m_command)) {
Debug.LogError(string.Format("Method {0}.{1} needs a valid command name.", type, method.Name));
continue;
}
cmd.m_callback = cb;
m_commands.Add(cmd);
}
}
}
}
#endif
}
19
Source : SourceSymbolFactory.cs
with MIT License
from 71
with MIT License
from 71
private static object Invoke(int key, Type type, string methodName, params object[] args)
{
if (CachedFuncs.TryGetValue(key, out var func))
return func(args);
// ReSharper disable once CoVariantArrayConversion
MethodInfo method = (MethodInfo)Proxy.FindMatchingMethod(type.GetMethods(Proxy.ALL), methodName, args);
ParameterInfo[] parameters = method.GetParameters();
func = Helpers.MakeDelegate<Func<object[], object>>(methodName, il =>
{
for (int i = 0; i < parameters.Length; i++)
{
Type paramType = parameters[i].ParameterType;
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldelem_Ref);
if (paramType == typeof(object))
continue;
il.Emit(paramType.GetTypeInfo().IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclreplaced, paramType);
}
il.Emit(OpCodes.Call, method);
il.Emit(OpCodes.Castclreplaced, method.ReturnType);
il.Emit(OpCodes.Ret);
}, type);
CachedFuncs.Add(key, func);
return func(args);
}
19
Source : CometaryExtensions.cs
with MIT License
from 71
with MIT License
from 71
public static MethodBase GetCorrespondingMethod(this IMethodSymbol symbol)
{
if (symbol == null)
throw new ArgumentNullException(nameof(symbol));
Type declaringType = symbol.ContainingType.GetCorrespondingType();
if (declaringType == null)
return null;
BindingFlags flags = symbol.GetCorrespondingBindingFlags();
IEnumerable<MethodBase> possibleMethods;
switch (symbol.MethodKind)
{
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
possibleMethods = declaringType.GetConstructors(flags);
break;
default:
possibleMethods = declaringType.GetMethods(flags);
break;
}
ImmutableArray<IParameterSymbol> symbolParameters = symbol.Parameters;
foreach (MethodBase method in possibleMethods)
{
if (method.Name != symbol.Name)
continue;
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != symbolParameters.Length)
continue;
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType != symbolParameters[i].Type.GetCorrespondingType())
goto Continue;
}
return method;
Continue:;
}
return null;
}
19
Source : HelpersTests.cs
with MIT License
from 71
with MIT License
from 71
[Fact]
public void TestUninitializedMethods()
{
bool IsValidMethod(MethodInfo method)
{
if (method.IsAbstract)
return false;
if (!method.IsStatic && method.DeclaringType.GetTypeInfo().IsAbstract)
return false;
return !method.ContainsGenericParameters;
}
// We're testing LINQ expressions here, cuz there are (instance / static) and (public / non-public) methods,
// properties, and most methods are independant. Last time I checked, running this step checks
// 193 different methods.
foreach (var method in typeof(Expression).GetMethods(BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic)
.Where(IsValidMethod)
.GroupBy(x => x.Name)
.Select(Enumerable.First))
{
// Find non-jitted start
IntPtr start = method.GetRuntimeMethodHandle().GetMethodStart();
// Compile method (should work on this platform)
Helpers.TryPrepareMethod(method, method.GetRuntimeMethodHandle()).ShouldBeTrue();
// Find freshly jitted start
IntPtr newStart = method.GetRuntimeMethodHandle().GetMethodStart();
// start != newStart => it wasn't jitted before: Fixup should be good
start.HasBeenCompiled().ShouldBe(start == newStart);
// In any case, the new method shouldn't be a fixup
newStart.HasBeenCompiled().ShouldBeTrue();
}
}
19
Source : MacroExpander.cs
with MIT License
from 71
with MIT License
from 71
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
IOperation operation = semanticModel.GetOperation(node, cancellationToken);
if (operation == null || !operation.IsInvalid)
return base.VisitMemberAccessExpression(node);
// Expression is invalid, might be a late-bound object
IOperation expression = semanticModel.GetOperation(node.Expression, cancellationToken);
if (expression.IsInvalid)
return base.VisitMemberAccessExpression(node);
// Find out if it is a late-bound object...
INamedTypeSymbol type = expression.Type as INamedTypeSymbol;
if (type == null)
return base.VisitMemberAccessExpression(node);
// ... by finding its Bind method
object[] arguments = null;
bool IsValidBindMethod(MethodInfo mi)
{
if (!mi.IsStatic || mi.IsAbstract || mi.Name != "Bind")
return false;
if (!typeof(ExpressionSyntax).IsreplacedignableFrom(mi.ReturnType))
return false;
ParameterInfo[] parameters = mi.GetParameters();
object[] args = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
Type paramType = parameters[i].ParameterType;
if (paramType.IsreplacedignableFrom(typeof(MemberAccessExpressionSyntax)))
args[i] = node;
else if (paramType == typeof(IOperation))
args[i] = expression;
else
return false;
}
arguments = args;
return true;
}
Type correspondingType = type.GetCorrespondingType();
if (correspondingType == null)
return base.VisitMemberAccessExpression(node);
MethodInfo bindMethod = correspondingType
.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.FirstOrDefault(IsValidBindMethod);
if (bindMethod == null)
return base.VisitMemberAccessExpression(node);
// We do have a binder!
// Call the method
try
{
ExpressionSyntax result = bindMethod.Invoke(null, arguments) as ExpressionSyntax;
return result == null
? SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)
: base.Visit(result);
}
catch (Exception e)
{
throw new DiagnosticException("Error thrown by binding method.", e, node.GetLocation());
}
}
19
Source : ReflectionCache.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static List<MethodInfo> GetMethods(Type t, Operation op)
{
if (BehaviourMethodCache.TryGetValue(t, out var props))
{
if (props.TryGetValue(op, out var res))
return res;
else
return null;
}
var handle_methods = t.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(HandleAttribute), true).Any());
Dictionary<Operation, List<MethodInfo>> opbind = new Dictionary<Operation, List<MethodInfo>>();
foreach (var m in handle_methods)
{
var ops = m.GetCustomAttributes(typeof(HandleAttribute), true).OfType<HandleAttribute>().Select(x=>x.handleType);//.FirstOrDefault().handleType;
foreach(var p_op in ops)
{
if (opbind.TryGetValue(p_op, out var list))
{
list.Add(m);
}
else
{
opbind.Add(p_op, new List<MethodInfo> { m });
}
}
}
BehaviourMethodCache.Add(t, opbind);
if (BehaviourMethodCache.TryGetValue(t, out var props2))
{
if (props2.TryGetValue(op, out var res2))
return res2;
else
return null;
}
else
return null;
}
19
Source : ReaderCache.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
private static MethodInfo GetOperator(Type from, Type to)
{
if (to == null) return null;
MethodInfo[] fromMethods, toMethods;
return ResolveOperator(fromMethods = from.GetMethods(BindingFlags.Static | BindingFlags.Public), from, to, "op_Implicit")
?? ResolveOperator(toMethods = to.GetMethods(BindingFlags.Static | BindingFlags.Public), from, to, "op_Implicit")
?? ResolveOperator(fromMethods, from, to, "op_Explicit")
?? ResolveOperator(toMethods, from, to, "op_Explicit");
}
19
Source : Runner.cs
with MIT License
from actions
with MIT License
from actions
public async Task<int> ExecuteCommand(CommandSettings command)
{
try
{
VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);
_inConfigStage = true;
_completedCommand.Reset();
_term.CancelKeyPress += CtrlCHandler;
//register a SIGTERM handler
HostContext.Unloading += Runner_Unloading;
// TODO Unit test to cover this logic
Trace.Info(nameof(ExecuteCommand));
var configManager = HostContext.GetService<IConfigurationManager>();
// command is not required, if no command it just starts if configured
// TODO: Invalid config prints usage
if (command.Help)
{
PrintUsage(command);
return Constants.Runner.ReturnCode.Success;
}
if (command.Version)
{
_term.WriteLine(BuildConstants.RunnerPackage.Version);
return Constants.Runner.ReturnCode.Success;
}
if (command.Commit)
{
_term.WriteLine(BuildConstants.Source.CommitHash);
return Constants.Runner.ReturnCode.Success;
}
if (command.Check)
{
var url = command.GetUrl();
var pat = command.GetGitHubPersonalAccessToken(required: true);
var checkExtensions = HostContext.GetService<IExtensionManager>().GetExtensions<ICheckExtension>();
var sortedChecks = checkExtensions.OrderBy(x => x.Order);
foreach (var check in sortedChecks)
{
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Check: {check.CheckName}");
_term.WriteLine($"** Description: {check.CheckDescription}");
_term.WriteLine($"**********************************************************************************************************************");
var result = await check.RunCheck(url, pat);
if (!result)
{
_term.WriteLine($"** **");
_term.WriteLine($"** F A I L **");
_term.WriteLine($"** **");
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Log: {check.CheckLog}");
_term.WriteLine($"** Help Doc: {check.HelpLink}");
_term.WriteLine($"**********************************************************************************************************************");
}
else
{
_term.WriteLine($"** **");
_term.WriteLine($"** P A S S **");
_term.WriteLine($"** **");
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Log: {check.CheckLog}");
_term.WriteLine($"**********************************************************************************************************************");
}
_term.WriteLine();
_term.WriteLine();
}
return Constants.Runner.ReturnCode.Success;
}
// Configure runner prompt for args if not supplied
// Unattended configure mode will not prompt for args if not supplied and error on any missing or invalid value.
if (command.Configure)
{
try
{
await configManager.ConfigureAsync(command);
return Constants.Runner.ReturnCode.Success;
}
catch (Exception ex)
{
Trace.Error(ex);
_term.WriteError(ex.Message);
return Constants.Runner.ReturnCode.TerminatedError;
}
}
// remove config files, remove service, and exit
if (command.Remove)
{
try
{
await configManager.UnconfigureAsync(command);
return Constants.Runner.ReturnCode.Success;
}
catch (Exception ex)
{
Trace.Error(ex);
_term.WriteError(ex.Message);
return Constants.Runner.ReturnCode.TerminatedError;
}
}
_inConfigStage = false;
// warmup runner process (JIT/CLR)
// In scenarios where the runner is single use (used and then thrown away), the system provisioning the runner can call `Runner.Listener --warmup` before the machine is made available to the pool for use.
// this will optimizes the runner process startup time.
if (command.Warmup)
{
var binDir = HostContext.GetDirectory(WellKnownDirectory.Bin);
foreach (var replacedemblyFile in Directory.EnumerateFiles(binDir, "*.dll"))
{
try
{
Trace.Info($"Load replacedembly: {replacedemblyFile}.");
var replacedembly = replacedembly.LoadFrom(replacedemblyFile);
var types = replacedembly.GetTypes();
foreach (Type loadedType in types)
{
try
{
Trace.Info($"Load methods: {loadedType.FullName}.");
var methods = loadedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var method in methods)
{
if (!method.IsAbstract && !method.ContainsGenericParameters)
{
Trace.Verbose($"Prepare method: {method.Name}.");
RuntimeHelpers.PrepareMethod(method.MethodHandle);
}
}
}
catch (Exception ex)
{
Trace.Error(ex);
}
}
}
catch (Exception ex)
{
Trace.Error(ex);
}
}
return Constants.Runner.ReturnCode.Success;
}
RunnerSettings settings = configManager.LoadSettings();
var store = HostContext.GetService<IConfigurationStore>();
bool configuredreplacedervice = store.IsServiceConfigured();
// Run runner
if (command.Run) // this line is current break machine provisioner.
{
// Error if runner not configured.
if (!configManager.IsConfigured())
{
_term.WriteError("Runner is not configured.");
PrintUsage(command);
return Constants.Runner.ReturnCode.TerminatedError;
}
Trace.Verbose($"Configured as service: '{configuredreplacedervice}'");
//Get the startup type of the runner i.e., autostartup, service, manual
StartupType startType;
var startupTypereplacedtring = command.GetStartupType();
if (string.IsNullOrEmpty(startupTypereplacedtring) && configuredreplacedervice)
{
// We need try our best to make the startup type accurate
// The problem is coming from runner autoupgrade, which result an old version service host binary but a newer version runner binary
// At that time the servicehost won't preplaced --startuptype to Runner.Listener while the runner is actually running as service.
// We will guess the startup type only when the runner is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
Trace.Info($"Try determine runner startup type base on console redirects.");
startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
}
else
{
if (!Enum.TryParse(startupTypereplacedtring, true, out startType))
{
Trace.Info($"Could not parse the argument value '{startupTypereplacedtring}' for StartupType. Defaulting to {StartupType.Manual}");
startType = StartupType.Manual;
}
}
Trace.Info($"Set runner startup type - {startType}");
HostContext.StartupType = startType;
if (command.RunOnce)
{
_term.WriteLine("Warning: '--once' is going to be deprecated in the future, please consider using '--ephemeral' during runner registration.", ConsoleColor.Yellow);
_term.WriteLine("https://docs.github.com/en/actions/hosting-your-own-runners/autoscaling-with-self-hosted-runners#using-ephemeral-runners-for-autoscaling", ConsoleColor.Yellow);
}
// Run the runner interactively or as service
return await RunAsync(settings, command.RunOnce || settings.Ephemeral);
}
else
{
PrintUsage(command);
return Constants.Runner.ReturnCode.Success;
}
}
finally
{
_term.CancelKeyPress -= CtrlCHandler;
HostContext.Unloading -= Runner_Unloading;
_completedCommand.Set();
}
}
19
Source : TypeHelpers.cs
with MIT License
from adrianoc
with MIT License
from adrianoc
public static MethodInfo ResolveGenericMethod(string replacedemblyName, string declaringTypeName, string methodName, BindingFlags bindingFlags, IEnumerable<string> typeArguments,
IEnumerable<ParamData> paramTypes)
{
var containingreplacedembly = replacedembly.Load(replacedemblyName);
var declaringType = containingreplacedembly.GetType(declaringTypeName);
var typeArgumentsCount = typeArguments.Count();
var methods = declaringType.GetMethods(bindingFlags)
.Where(c => c.Name == methodName
&& c.IsGenericMethodDefinition
&& c.GetParameters().Length == paramTypes.Count()
&& typeArgumentsCount == c.GetGenericArguments().Length);
if (methods == null)
{
throw new MissingMethodException(declaringTypeName, methodName);
}
var paramTypesArray = paramTypes.ToArray();
foreach (var mc in methods)
{
var parameters = mc.GetParameters();
var found = true;
for (var i = 0; i < parameters.Length; i++)
{
if (!CompareParameters(parameters[i], paramTypesArray[i]))
{
found = false;
break;
}
}
if (found)
{
return mc.MakeGenericMethod(typeArguments.Select(Type.GetType).ToArray());
}
}
return null;
}
19
Source : Ldftn.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
public void Load(DarksVMContext ctx, out ExecutionState state)
{
var sp = ctx.Registers[DarksVMConstants.REG_SP].U4;
var methodSlot = ctx.Stack[sp--];
var objectSlot = ctx.Stack[sp];
if(objectSlot.O != null)
{
var method = (MethodInfo) ctx.Instance.Data.LookupReference(methodSlot.U4);
var type = objectSlot.O.GetType();
var baseTypes = new List<Type>();
do
{
baseTypes.Add(type);
type = type.BaseType;
} while(type != null && type != method.DeclaringType);
baseTypes.Reverse();
var found = method;
const BindingFlags fl = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
foreach(var baseType in baseTypes)
foreach(var m in baseType.GetMethods(fl))
if(m.GetBaseDefinition() == found)
{
found = m;
break;
}
ctx.Stack[sp] = new DarksVMSlot {U8 = (ulong) found.MethodHandle.GetFunctionPointer()};
}
if(objectSlot.U8 != 0)
{
// intra linking
var entryKey = ctx.Stack[--sp].U4;
var codeAdr = methodSlot.U8;
var sig = ctx.Instance.Data.LookupExport(objectSlot.U4).Signature;
var ptr = DarksVMTrampoline.CreateTrampoline(ctx.Instance.Data.Module, codeAdr, entryKey, sig, objectSlot.U4);
ctx.Stack[sp] = new DarksVMSlot {U8 = (ulong) ptr};
}
else
{
var method = (MethodBase) ctx.Instance.Data.LookupReference(methodSlot.U4);
ctx.Stack[sp] = new DarksVMSlot {U8 = (ulong) method.MethodHandle.GetFunctionPointer()};
}
ctx.Stack.SetTopPosition(sp);
ctx.Registers[DarksVMConstants.REG_SP].U4 = sp;
state = ExecutionState.Next;
}
19
Source : ZeroDiscover.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private void FindApi(Type type, bool onlyDoc)
{
if (type.IsAbstract)
return;
StationDoreplacedent station;
var sa = type.GetCustomAttribute<StationAttribute>();
if (sa != null)
{
if (!StationInfo.TryGetValue(sa.Name, out station))
{
StationInfo.Add(sa.Name, station = new StationDoreplacedent
{
Name = sa.Name
});
}
}
else
{
station = _defStation;
}
//station.Copy(XmlMember.Find(type));
string routeHead = null;
var attrib = type.GetCustomAttribute<RouteAttribute>();
if (attrib != null)
{
routeHead = attrib.Name;
}
else
{
var attrib2 = type.GetCustomAttribute<RoutePrefixAttribute>();
if (attrib2 != null)
{
routeHead = attrib2.Name;
}
}
if (string.IsNullOrWhiteSpace(routeHead))
routeHead = null;
else
routeHead = routeHead.Trim(' ', '\t', '\r', '\n', '/') + "/";
var methods = type.GetMethods(BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic);
var xdoc = XmlMember.Find(type);
foreach (var method in methods)
{
var route = method.GetCustomAttribute<RouteAttribute>();
if (route == null)
{
//ZeroTrace.WriteError("ApiDiscover", "exclude", station.Name, type.Name, method.Name);
continue;
}
if (method.Name.Length > 4 && (method.Name.IndexOf("get_") == 0 || method.Name.IndexOf("set_") == 0))
continue;
if (method.GetParameters().Length > 1)
{
//ZeroTrace.WriteError("ApiDiscover", "argument size must 0 or 1", station.Name, type.Name, method.Name);
continue;
}
var name = route?.Name == null
? $"{routeHead}{method.Name}"
: $"{routeHead}{route.Name.Trim(' ', '\t', '\r', '\n', '/')}";
var accessOption = method.GetCustomAttribute<ApiAccessOptionFilterAttribute>();
var ca = method.GetAttribute<CategoryAttribute>();
var api = new ApiActionInfo
{
Name = method.Name,
ApiName= route?.Name ?? method.Name,
RouteName = name,
Category = ca?.Category ?? xdoc?.Caption,
AccessOption = accessOption?.Option ?? ApiAccessOption.Public | ApiAccessOption.ArgumentCanNil,
ResultInfo = ReadEnreplacedy(method.ReturnType, "result")
};
var doc = XmlMember.Find(type, method.Name, "M");
api.Copy(doc);
var arg = method.GetParameters().FirstOrDefault();
api.HaseArgument = arg != null;
//动态生成并编译
if (api.HaseArgument)
{
api.ArgumentInfo = ReadEnreplacedy(arg.ParameterType, "argument") ?? new TypeDoreplacedent();
api.ArgumentInfo.Name = arg.Name;
if (doc != null)
api.ArgumentInfo.Caption = doc.Arguments.Values.FirstOrDefault();
if (!onlyDoc)
{
api.ArgumenType = arg.ParameterType;
api.ArgumentAction = CreateFunc<IApiArgument, IApiResult>(type.GetTypeInfo(),
method.Name,
arg.ParameterType.GetTypeInfo(),
method.ReturnType.GetTypeInfo());
}
}
else if (!onlyDoc)
{
api.Action = CreateFunc<IApiResult>(type.GetTypeInfo(), method.Name, method.ReturnType.GetTypeInfo());
}
station.Aips.Add(api.RouteName, api);
}
}
19
Source : MissionMapBuilder.cs
with MIT License
from ahydrax
with MIT License
from ahydrax
private static IEnumerable<Mission> LookupForMission(Type[] targetTypes)
{
foreach (var targetType in targetTypes)
{
var missionLauncherAttribute = targetType.GetCustomAttribute<MissionLauncherAttribute>();
var suitableMethods = targetType
.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)
.Where(x => x.GetCustomAttribute<MissionAttribute>() != null)
.ToArray();
foreach (var suitableMethod in suitableMethods)
{
var missionAttribute = suitableMethod.GetCustomAttribute<MissionAttribute>();
yield return new Mission(missionLauncherAttribute, missionAttribute, suitableMethod);
}
}
}
19
Source : JsonServiceScript.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private string GenerateFunctions()
{
///? exclude parameters of RawRequestAttribute, RawResponseAttribute, RawParametersAttribute
StringBuilder sb = new StringBuilder();
var ms = _svc.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach(MethodInfo mi in ms)
{
sb.AppendFormat(@"this.{0} = function (p, onResult, onError) {{ return this.implement('{0}', p, onResult, onError); }};", mi.Name);
sb.AppendLine();
var ps = new List<string>();
foreach (var p in mi.GetParameters())
ps.Add(p.Name + ":''");
sb.AppendFormat(@"this.{0}.params = {{ {1} }};", mi.Name, string.Join(",", ps.ToArray()));
sb.AppendLine();
}
return sb.ToString();
}
19
Source : ScriptEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string GenerateFunctions(object svc)
{
///> exclude parameters of RawRequestAttribute, RawResponseAttribute, RawParametersAttribute
StringBuilder sb = new StringBuilder();
var ms = svc.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach(MethodInfo mi in ms)
{
sb.AppendFormat(@"this.{0} = function (p, onResult, onError) {{ return this.implement('{0}', p, onResult, onError); }};", mi.Name);
sb.AppendLine();
var ps = new List<string>();
foreach (var p in mi.GetParameters())
ps.Add(p.Name + ":''");
sb.AppendFormat(@"this.{0}.params = {{ {1} }};", mi.Name, string.Join(",", ps.ToArray()));
sb.AppendLine();
}
return sb.ToString();
}
19
Source : OptionsBuilder.cs
with MIT License
from aivascu
with MIT License
from aivascu
public virtual object Build(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (!typeof(DbContext).IsreplacedignableFrom(type) || type.IsAbstract)
{
throw new ArgumentException(Invariant($"The context type should be a non-abstract clreplaced inherited from {typeof(DbContext)}"), nameof(type));
}
var methods = this.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
var genericConfigureMethod = Array
.Find(methods, m => m.Name == nameof(Build) && m.IsGenericMethodDefinition)
.MakeGenericMethod(type);
return genericConfigureMethod.Invoke(this, Array.Empty<object>());
}
19
Source : DefaultContractResolver.cs
with MIT License
from akaskela
with MIT License
from akaskela
private void GetCallbackMethodsForType(Type type, out List<SerializationCallback> onSerializing, out List<SerializationCallback> onSerialized, out List<SerializationCallback> onDeserializing, out List<SerializationCallback> onDeserialized, out List<SerializationErrorCallback> onError)
{
onSerializing = null;
onSerialized = null;
onDeserializing = null;
onDeserialized = null;
onError = null;
foreach (Type baseType in GetClreplacedHierarchyForType(type))
{
// while we allow more than one OnSerialized total, only one can be defined per clreplaced
MethodInfo currentOnSerializing = null;
MethodInfo currentOnSerialized = null;
MethodInfo currentOnDeserializing = null;
MethodInfo currentOnDeserialized = null;
MethodInfo currentOnError = null;
bool skipSerializing = ShouldSkipSerializing(baseType);
bool skipDeserialized = ShouldSkipDeserialized(baseType);
foreach (MethodInfo method in baseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
// compact framework errors when getting parameters for a generic method
// lame, but generic methods should not be callbacks anyway
if (method.ContainsGenericParameters)
{
continue;
}
Type prevAttributeType = null;
ParameterInfo[] parameters = method.GetParameters();
if (!skipSerializing && IsValidCallback(method, parameters, typeof(OnSerializingAttribute), currentOnSerializing, ref prevAttributeType))
{
onSerializing = onSerializing ?? new List<SerializationCallback>();
onSerializing.Add(JsonContract.CreateSerializationCallback(method));
currentOnSerializing = method;
}
if (IsValidCallback(method, parameters, typeof(OnSerializedAttribute), currentOnSerialized, ref prevAttributeType))
{
onSerialized = onSerialized ?? new List<SerializationCallback>();
onSerialized.Add(JsonContract.CreateSerializationCallback(method));
currentOnSerialized = method;
}
if (IsValidCallback(method, parameters, typeof(OnDeserializingAttribute), currentOnDeserializing, ref prevAttributeType))
{
onDeserializing = onDeserializing ?? new List<SerializationCallback>();
onDeserializing.Add(JsonContract.CreateSerializationCallback(method));
currentOnDeserializing = method;
}
if (!skipDeserialized && IsValidCallback(method, parameters, typeof(OnDeserializedAttribute), currentOnDeserialized, ref prevAttributeType))
{
onDeserialized = onDeserialized ?? new List<SerializationCallback>();
onDeserialized.Add(JsonContract.CreateSerializationCallback(method));
currentOnDeserialized = method;
}
if (IsValidCallback(method, parameters, typeof(OnErrorAttribute), currentOnError, ref prevAttributeType))
{
onError = onError ?? new List<SerializationErrorCallback>();
onError.Add(JsonContract.CreateSerializationErrorCallback(method));
currentOnError = method;
}
}
}
}
19
Source : ReflectionUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method)
{
bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Any(info =>
info.Name == method &&
// check that the method overrides the original on DynamicObjectProxy
info.DeclaringType != methodDeclaringType
&& info.GetBaseDefinition().DeclaringType == methodDeclaringType
);
return isMethodOverriden;
}
19
Source : NodeEditorReflection.cs
with MIT License
from aksyr
with MIT License
from aksyr
public static KeyValuePair<ContextMenu, MethodInfo>[] GetContextMenuMethods(object obj) {
Type type = obj.GetType();
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
List<KeyValuePair<ContextMenu, MethodInfo>> kvp = new List<KeyValuePair<ContextMenu, MethodInfo>>();
for (int i = 0; i < methods.Length; i++) {
ContextMenu[] attribs = methods[i].GetCustomAttributes(typeof(ContextMenu), true).Select(x => x as ContextMenu).ToArray();
if (attribs == null || attribs.Length == 0) continue;
if (methods[i].GetParameters().Length != 0) {
Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name + " has parameters and cannot be used for context menu commands.");
continue;
}
if (methods[i].IsStatic) {
Debug.LogWarning("Method " + methods[i].DeclaringType.Name + "." + methods[i].Name + " is static and cannot be used for context menu commands.");
continue;
}
for (int k = 0; k < attribs.Length; k++) {
kvp.Add(new KeyValuePair<ContextMenu, MethodInfo>(attribs[k], methods[i]));
}
}
#if UNITY_5_5_OR_NEWER
//Sort menu items
kvp.Sort((x, y) => x.Key.priority.CompareTo(y.Key.priority));
#endif
return kvp.ToArray();
}
19
Source : NodeEditorUtilities.cs
with MIT License
from aksyr
with MIT License
from aksyr
public static bool IsCastableTo(this Type from, Type to) {
if (to.IsreplacedignableFrom(from)) return true;
var methods = from.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(
m => m.ReturnType == to &&
(m.Name == "op_Implicit" ||
m.Name == "op_Explicit")
);
return methods.Count() > 0;
}
19
Source : BaseNode.cs
with MIT License
from alelievr
with MIT License
from alelievr
void InitializeCustomPortTypeMethods()
{
MethodInfo[] methods = new MethodInfo[0];
Type baseType = GetType();
while (true)
{
methods = baseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var method in methods)
{
var typeBehaviors = method.GetCustomAttributes<CustomPortTypeBehavior>().ToArray();
if (typeBehaviors.Length == 0)
continue;
CustomPortTypeBehaviorDelegate deleg = null;
try
{
deleg = Delegate.CreateDelegate(typeof(CustomPortTypeBehaviorDelegate), this, method) as CustomPortTypeBehaviorDelegate;
} catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Cannot convert method {method} to a delegate of type {typeof(CustomPortTypeBehaviorDelegate)}");
}
foreach (var typeBehavior in typeBehaviors)
customPortTypeBehaviorMap[typeBehavior.type] = deleg;
}
// Try to also find private methods in the base clreplaced
baseType = baseType.BaseType;
if (baseType == null)
break;
}
}
19
Source : NodeProvider.cs
with MIT License
from alelievr
with MIT License
from alelievr
static bool IsNodeSpecificToGraph(Type nodeType)
{
var isCompatibleWithGraphMethods = nodeType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Where(m => m.GetCustomAttribute<IsCompatibleWithGraph>() != null);
var nodeMenuAttributes = nodeType.GetCustomAttributes<NodeMenuItemAttribute>();
List<Type> compatibleGraphTypes = nodeMenuAttributes.Where(n => n.onlyCompatibleWithGraph != null).Select(a => a.onlyCompatibleWithGraph).ToList();
List<MethodInfo> compatibleMethods = new List<MethodInfo>();
foreach (var method in isCompatibleWithGraphMethods)
{
// Check if the method is static and have the correct prototype
var p = method.GetParameters();
if (method.ReturnType != typeof(bool) || p.Count() != 1 || p[0].ParameterType != typeof(BaseGraph))
Debug.LogError($"The function '{method.Name}' marked with the IsCompatibleWithGraph attribute either doesn't return a boolean or doesn't take one parameter of BaseGraph type.");
else
compatibleMethods.Add(method);
}
if (compatibleMethods.Count > 0 || compatibleGraphTypes.Count > 0)
{
// We still need to add the element in specificNode even without specific graph
if (compatibleGraphTypes.Count == 0)
compatibleGraphTypes.Add(null);
foreach (var graphType in compatibleGraphTypes)
{
specificNodes.Add(new NodeSpecificToGraph{
nodeType = nodeType,
isCompatibleWithGraph = compatibleMethods,
compatibleWithGraphType = graphType
});
}
return true;
}
return false;
}
19
Source : BaseNode.cs
with MIT License
from alelievr
with MIT License
from alelievr
void InitializeInOutDatas()
{
var fields = GetNodeFields();
var methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var field in fields)
{
var inputAttribute = field.GetCustomAttribute< InputAttribute >();
var outputAttribute = field.GetCustomAttribute< OutputAttribute >();
var tooltipAttribute = field.GetCustomAttribute< TooltipAttribute >();
var showInInspector = field.GetCustomAttribute< ShowInInspector >();
var vertical = field.GetCustomAttribute< VerticalAttribute >();
bool isMultiple = false;
bool input = false;
string name = field.Name;
string tooltip = null;
if (showInInspector != null)
_needsInspector = true;
if (inputAttribute == null && outputAttribute == null)
continue ;
//check if field is a collection type
isMultiple = (inputAttribute != null) ? inputAttribute.allowMultiple : (outputAttribute.allowMultiple);
input = inputAttribute != null;
tooltip = tooltipAttribute?.tooltip;
if (!String.IsNullOrEmpty(inputAttribute?.name))
name = inputAttribute.name;
if (!String.IsNullOrEmpty(outputAttribute?.name))
name = outputAttribute.name;
// By default we set the behavior to null, if the field have a custom behavior, it will be set in the loop just below
nodeFields[field.Name] = new NodeFieldInformation(field, name, input, isMultiple, tooltip, vertical != null, null);
}
foreach (var method in methods)
{
var customPortBehaviorAttribute = method.GetCustomAttribute< CustomPortBehaviorAttribute >();
CustomPortBehaviorDelegate behavior = null;
if (customPortBehaviorAttribute == null)
continue ;
// Check if custom port behavior function is valid
try {
var referenceType = typeof(CustomPortBehaviorDelegate);
behavior = (CustomPortBehaviorDelegate)Delegate.CreateDelegate(referenceType, this, method, true);
} catch {
Debug.LogError("The function " + method + " cannot be converted to the required delegate format: " + typeof(CustomPortBehaviorDelegate));
}
if (nodeFields.ContainsKey(customPortBehaviorAttribute.fieldName))
nodeFields[customPortBehaviorAttribute.fieldName].behavior = behavior;
else
Debug.LogError("Invalid field name for custom port behavior: " + method + ", " + customPortBehaviorAttribute.fieldName);
}
}
19
Source : TypeAdapter.cs
with MIT License
from alelievr
with MIT License
from alelievr
static void LoadAllAdapters()
{
foreach (Type type in AppDomain.CurrentDomain.GetAllTypes())
{
if (typeof(ITypeAdapter).IsreplacedignableFrom(type))
{
if (type.IsAbstract)
continue;
var adapter = Activator.CreateInstance(type) as ITypeAdapter;
if (adapter != null)
{
foreach (var types in adapter.GetIncompatibleTypes())
{
incompatibleTypes.Add((types.Item1, types.Item2));
incompatibleTypes.Add((types.Item2, types.Item1));
}
}
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
if (method.GetParameters().Length != 1)
{
Debug.LogError($"Ignoring convertion method {method} because it does not have exactly one parameter");
continue;
}
if (method.ReturnType == typeof(void))
{
Debug.LogError($"Ignoring convertion method {method} because it does not returns anything");
continue;
}
Type from = method.GetParameters()[0].ParameterType;
Type to = method.ReturnType;
try {
#if ENABLE_IL2CPP
// IL2CPP doesn't suport calling generic functions via reflection (AOT can't generate templated code)
Func<object, object> r = (object param) => { return (object)method.Invoke(null, new object[]{ param }); };
#else
MethodInfo genericHelper = typeof(TypeAdapter).GetMethod("ConvertTypeMethodHelper",
BindingFlags.Static | BindingFlags.NonPublic);
// Now supply the type arguments
MethodInfo constructedHelper = genericHelper.MakeGenericMethod(from, to);
object ret = constructedHelper.Invoke(null, new object[] {method});
var r = (Func<object, object>) ret;
#endif
adapters.Add((method.GetParameters()[0].ParameterType, method.ReturnType), r);
adapterMethods.Add((method.GetParameters()[0].ParameterType, method.ReturnType), method);
} catch (Exception e) {
Debug.LogError($"Failed to load the type convertion method: {method}\n{e}");
}
}
}
}
// Ensure that the dictionary contains all the convertions in both ways
// ex: float to vector but no vector to float
foreach (var kp in adapters)
{
if (!adapters.ContainsKey((kp.Key.to, kp.Key.from)))
Debug.LogError($"Missing convertion method. There is one for {kp.Key.from} to {kp.Key.to} but not for {kp.Key.to} to {kp.Key.from}");
}
adaptersLoaded = true;
}
19
Source : InvokeWrapperInspectorDrawer.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
public static DrawerInfo GetDrawerMethod( Type type )
{
DrawerInfo drawerInfo;
if ( !m_drawerMethodsCache.TryGetValue( type, out drawerInfo ) ) {
drawerInfo = new DrawerInfo() { Drawer = null, CopyOp = null, IsNullable = false };
foreach ( var drawerClreplaced in m_drawerClreplacedes ) {
var methods = drawerClreplaced.GetMethods( BindingFlags.Public | BindingFlags.Static );
foreach ( var method in methods ) {
if ( method.GetCustomAttributes<InspectorDrawerAttribute>().FirstOrDefault( attribute => attribute.Match( type ) ) != null ) {
drawerInfo.Drawer = method;
FindDrawerResult( ref drawerInfo, drawerClreplaced );
m_drawerMethodsCache.Add( type, drawerInfo );
break;
}
}
if ( drawerInfo.Drawer != null )
break;
}
}
return drawerInfo;
}
19
Source : FrameworkTest.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
[DataRow("Object extension methods", typeof(ObjectIsExtensions), typeof(ObjectIsNotExtensions), typeof(ObjectCannotExtensions), typeof(ObjectMustExtensions), typeof(ObjectWhenExtensions), typeof(ObjectWhenNotExtensions), new string[] { "Is=>Be", "Does=>" })]
[DataRow("Collection extension methods", typeof(CollectionIsExtensions), typeof(CollectionIsNotExtensions), typeof(CollectionCannotExtensions), typeof(CollectionMustExtensions), typeof(CollectionWhenExtensions), typeof(CollectionWhenNotExtensions), new string[] { "Is=>Be", "Contains=>Contain" })]
[DataRow("File system extension methods", typeof(FileIsExtensions), typeof(FileIsNotExtensions), typeof(FileCannotExtensions), typeof(FileMustExtensions), typeof(FileWhenExtensions), typeof(FileWhenNotExtensions), new string[] { "Is=>Be", "Does=>" })]
[DataTestMethod]
public void TestNamingConvention(string name, Type isExtensions, Type isNotExtensions, Type cannotExtensions, Type mustExtensions, Type whenExtensions, Type whenNotExtensions, string[] prefixes)
{
Dictionary<string, string> prefixes2 = prefixes.ToDictionary(x => x.Split(new string[] { "=>" }, StringSplitOptions.None)[0], x => x.Split(new string[] { "=>" }, StringSplitOptions.None)[1]);
// check if clreplacedes are static
this.TestClreplaced(isExtensions);
this.TestClreplaced(isNotExtensions);
this.TestClreplaced(cannotExtensions);
this.TestClreplaced(mustExtensions);
this.TestClreplaced(whenExtensions);
this.TestClreplaced(whenNotExtensions);
Debug.WriteLine(string.Empty);
Debug.WriteLine($"### {name}:");
Debug.WriteLine($"|is|is not|must|cannot|when|when not|");
Debug.WriteLine($"|--|--|--|--|--|--|");
foreach (MethodInfo method in isExtensions.GetMethods(BindingFlags.Public |
BindingFlags.Static |
BindingFlags.DeclaredOnly)
.OrderBy(x => x.Name))
{
string prefix = prefixes2.First(x => method.Name.StartsWith(x.Key)).Key;
string suffix = method.Name.Substring(prefix.Length);
string subsreplacedute = prefixes2[prefix];
string isNotMethodName = $"{prefix}Not{suffix}";
string cannotMethodName = $"Cannot{subsreplacedute}{suffix}";
string mustMethodName = $"Must{subsreplacedute}{suffix}";
string whenMethodName = $"When{prefix}{suffix}";
string whenNotMethodName = $"When{prefix}Not{suffix}";
if (method.Name == "IsMatch")
{
cannotMethodName = nameof(ObjectCannotExtensions.CannotMatch);
mustMethodName = nameof(ObjectMustExtensions.MustMatch);
whenMethodName = nameof(ObjectWhenExtensions.WhenDoesMatch);
whenNotMethodName = nameof(ObjectWhenNotExtensions.WhenDoesNotMatch);
}
// check if naming convention
this.TestMethodName(isExtensions, method.Name);
this.TestMethodName(isNotExtensions, isNotMethodName);
this.TestMethodName(cannotExtensions, cannotMethodName);
this.TestMethodName(mustExtensions, mustMethodName);
this.TestMethodName(whenExtensions, whenMethodName);
this.TestMethodName(whenNotExtensions, whenNotMethodName);
// check parameters
this.TestParameters(method, isNotExtensions.GetMethod(isNotMethodName), false, false);
this.TestParameters(method, cannotExtensions.GetMethod(cannotMethodName), false, name != "Object extension methods" || method.Name != nameof(ObjectIsExtensions.IsOneOf));
this.TestParameters(method, mustExtensions.GetMethod(mustMethodName), false, name != "Object extension methods" || method.Name != nameof(ObjectIsExtensions.IsOneOf));
this.TestParameters(method, whenExtensions.GetMethod(whenMethodName), true, false);
this.TestParameters(method, whenNotExtensions.GetMethod(whenNotMethodName), true, false);
// check return types
this.TestReturnType(method, typeof(bool));
this.TestReturnType(isNotExtensions.GetMethod(isNotMethodName), method.ReturnType);
this.TestReturnType(cannotExtensions.GetMethod(cannotMethodName), method.GetParameters()[0].ParameterType);
this.TestReturnType(mustExtensions.GetMethod(mustMethodName), method.GetParameters()[0].ParameterType);
this.TestReturnType(whenExtensions.GetMethod(whenMethodName), method.GetParameters()[0].ParameterType);
this.TestReturnType(whenNotExtensions.GetMethod(whenNotMethodName), method.GetParameters()[0].ParameterType);
Debug.WriteLine($"|{method.Name}|{isNotMethodName}|{mustMethodName}|{cannotMethodName}|{whenMethodName}|{whenNotMethodName}|");
}
// check if method count equals
this.TestMethodCount(isExtensions, isNotExtensions);
this.TestMethodCount(isExtensions, cannotExtensions);
this.TestMethodCount(isExtensions, mustExtensions);
this.TestMethodCount(isExtensions, whenExtensions);
this.TestMethodCount(isExtensions, whenNotExtensions);
}
19
Source : FrameworkTest.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
private void TestMethodCount(Type type1, Type type2)
{
if (type1.GetMethods(BindingFlags.DeclaredOnly).Length != type2.GetMethods(BindingFlags.DeclaredOnly).Length)
{
replacedert.Fail($"Method count in {type1} does not match method count in {type2}");
}
}
19
Source : ActionDispatcher.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
public static List<string> FindAmbiguousActions(Type targetType) {
List<string> actions = new List<string>();
System.Reflection.MethodInfo[] allMethods = targetType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
HashSet<string> methodNames = new HashSet<string>();
foreach (var method in allMethods) {
methodNames.Add(method.Name);
}
foreach (var methodName in methodNames) {
try {
Dictionary<string, object> act = new Dictionary<string, object>();
act["action"] = methodName;
DynamicServerAction dynamicServerAction = new DynamicServerAction(act);
MethodInfo m = getDispatchMethod(targetType, dynamicServerAction);
} catch (AmbiguousActionException) {
actions.Add(methodName);
}
}
return actions;
}
19
Source : ActionDispatcher.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
private static MethodInfo[] getMethods(Type targetType) {
if (!methodCache.ContainsKey(targetType)) {
var methods = new List<MethodInfo>();
foreach (MethodInfo mi in targetType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) {
if (mi.ReturnType == typeof(void)) {
methods.Add(mi);
}
}
methodCache[targetType] = methods.ToArray();
}
return methodCache[targetType];
}
19
Source : JemBenchmark.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static int GetBenchmarkMethodCount<TBench>() where TBench : JemBenchmark<TData, TParam>
{
return typeof(TBench).GenericTypeArguments.First().GetMethods(BindingFlags.Public).Count();
}
19
Source : EditorUI.cs
with MIT License
from allenwp
with MIT License
from allenwp
private static unsafe void SubmitInvokeWindow()
{
ImGui.Begin("Invoke");
if (ImGui.BeginTabBar("replacedemblies Tab Bar", ImGuiTabBarFlags.None))
{
if (ImGui.BeginTabItem("Selected Object"))
{
ImGui.InputText("Filter", ref invokeFilter, 500);
invokeFilter = invokeFilter.ToLower();
bool doInvoke = ImGui.Button("Invoke");
ImGui.Separator();
ImGui.BeginChild("scrolling", Vector2.Zero, false, ImGuiWindowFlags.HorizontalScrollbar);
// TODO: for selected object, do similar to the other replacedemblies
ImGui.Text("(Selected Ojbect not yet implemented. Implement when needed.)");
ImGui.EndChild();
ImGui.EndTabItem();
}
foreach (var replacedemblyPair in replacedemblies)
{
if (ImGui.BeginTabItem(replacedemblyPair.Key))
{
ImGui.InputText("Filter", ref invokeFilter, 500);
invokeFilter = invokeFilter.ToLower();
bool doInvoke = ImGui.Button("Invoke"); // TODO: allow input of parameters.
ImGui.Separator();
ImGui.BeginChild("scrolling", Vector2.Zero, false, ImGuiWindowFlags.HorizontalScrollbar);
var names = (from type in replacedemblyPair.Value.GetTypes()
from method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
select (Type: type, Method: method, DisplayName: type.FullName + ":" + method.Name)).Where(a => a.Method.GetParameters().Length < 1).ToList();
for (int i = 0; i < names.Count; i++)
{
if (names[i].DisplayName.ToLower().Contains(invokeFilter))
{
if (names[i].Method.IsPrivate)
{
ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(0.5f, 0.5f, 0.5f, 1f));
}
StringBuilder sb = new StringBuilder();
sb.Append('(');
foreach (var param in names[i].Method.GetParameters())
{
sb.Append(param.ParameterType.Name);
sb.Append(' ');
sb.Append(param.Name);
}
sb.Append(')');
var text = $"{names[i].DisplayName}{sb}";
if (ImGui.Selectable(text, invokeSelectedIndex == i))
{
invokeSelectedIndex = i;
}
if (names[i].Method.IsPrivate)
{
ImGui.PopStyleColor();
}
}
}
if (doInvoke && names.Count > invokeSelectedIndex)
{
try
{
names[invokeSelectedIndex].Method.Invoke(null, null);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
ImGui.EndChild();
ImGui.EndTabItem();
}
}
ImGui.EndTabBar();
}
ImGui.End();
}
19
Source : FilesSelfTest.cs
with Apache License 2.0
from aloneguid
with Apache License 2.0
from aloneguid
private List<Tuple<string, Func<Task>>> FindTestMethods()
{
var r = new List<Tuple<string, Func<Task>>>();
foreach(MethodInfo mi in GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
Attribute ta = mi.GetCustomAttribute(typeof(TestAttribute));
if(ta != null)
{
// validate
if(mi.ReturnType != typeof(Task))
throw new ApplicationException($"{mi.Name}: return type must be Task");
if(mi.GetParameters().Length > 0)
throw new ApplicationException($"{mi.Name}: parameters are not supported");
r.Add(new Tuple<string, Func<Task>>(mi.Name, () => (Task)mi.Invoke(this, new object[0])));
}
}
return r;
}
19
Source : TypeExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static MethodInfo GetMethodBySignature([NotNull] this Type @this, MethodInfo method)
{
var methods = @this.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.Name.Equals(method.Name))
.ToArray();
var parameterTypes = method.GetParameters().Select(x => x.ParameterType).ToArray();
if (method.ContainsGenericParameters)
{
foreach (var info in methods)
{
var innerParams = info.GetParameters();
if (innerParams.Length != parameterTypes.Length)
{
continue;
}
var idx = 0;
foreach (var param in innerParams)
{
if (!param.ParameterType.IsGenericParameter
&& !parameterTypes[idx].IsGenericParameter
&& param.ParameterType != parameterTypes[idx]
)
{
break;
}
idx++;
}
if (idx < parameterTypes.Length)
{
continue;
}
return info;
}
return null;
}
var baseMethod = @this.GetMethod(method.Name, parameterTypes);
return baseMethod;
}
19
Source : TypeExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static MethodInfo[] GetMethods<T>([NotNull] this T @this, BindingFlags bindingAttr)
=> @this.GetType().GetMethods(bindingAttr);
19
Source : BaseTypeObject.cs
with MIT License
from Alprog
with MIT License
from Alprog
public override string AutoCompleteMember(string startText)
{
// fields
foreach (var field in Type.GetFields(Flags))
{
if (!field.IsSpecialName && field.Name.StartsWith(startText))
{
return field.Name;
}
}
// methods
if (!Type.IsEnum)
{
foreach (var method in Type.GetMethods(Flags))
{
if (!method.IsSpecialName && !method.IsGenericMethod && method.Name.StartsWith(startText))
{
return method.Name;
}
}
}
// properties
foreach (var propetry in Type.GetProperties(Flags))
{
if (!propetry.IsSpecialName && propetry.Name.StartsWith(startText))
{
return propetry.Name;
}
}
return null;
}
19
Source : ReflectionExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static MethodInfo GetMethodBySignature(this Type type, MethodInfo method)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.Name.Equals(method.Name))
.ToArray();
var parameterTypes = method.GetParameters().Select(x => x.ParameterType).ToArray();
if (method.ContainsGenericParameters)
{
foreach (var info in methods)
{
var innerParams = info.GetParameters();
if (innerParams.Length != parameterTypes.Length)
{
continue;
}
//if (info.GetGenericArguments().Length != genericArguments.Length)
//{
// continue;
//}
var idx = 0;
foreach (var param in innerParams)
{
if (!param.ParameterType.IsGenericParameter
&& !parameterTypes[idx].IsGenericParameter
&& param.ParameterType != parameterTypes[idx]
)
{
break;
}
idx++;
}
if (idx < parameterTypes.Length)
{
continue;
}
return info;
}
return null;
}
var baseMethod = type.GetMethod(method.Name, parameterTypes);
return baseMethod;
}
19
Source : ReflectionExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static MethodInfo[] GetMethods<T>([NotNull] this T @this, BindingFlags bindingAttr)
{
return @this.GetType().GetMethods(bindingAttr);
}
19
Source : ShaderGenerator.cs
with MIT License
from Aminator
with MIT License
from Aminator
public static void GetEntryPoints(ShaderGeneratorResult result, Type shaderType, BindingFlags bindingFlags = DefaultBindingFlagsWithContract)
{
foreach (MethodInfo shaderMethodInfo in shaderType.GetMethods(bindingFlags)
.Where(m => m.IsDefined(typeof(ShaderAttribute)))
.OrderBy(m => m.GetCustomAttribute<ShaderMemberAttribute>()?.Order))
{
ShaderAttribute shaderAttribute = shaderMethodInfo.GetCustomAttribute<ShaderAttribute>();
result.EntryPoints[shaderAttribute.Name] = shaderMethodInfo.Name;
}
}
19
Source : DynamicInvoker.cs
with MIT License
from amolines
with MIT License
from amolines
private static MethodInfo GetMember(Type type, string name, Type[] argtypes)
{
while (true)
{
var methods = type.GetMethods(bindingFlags).Where(m => m.Name == name).ToArray();
var member = methods.FirstOrDefault(m => m.GetParameters().Select(p => p.ParameterType).SequenceEqual(argtypes)) ??
methods.FirstOrDefault(m => m.GetParameters().Select(p => p.ParameterType).ToArray().Matches(argtypes));
if (member != null)
{
return member;
}
var t = type.GetTypeInfo().BaseType;
if (t == null)
{
return null;
}
type = t;
}
}
19
Source : ControlExample.cs
with MIT License
from amwx
with MIT License
from amwx
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == TargetTypeProperty)
{
var str = change.NewValue.GetValueOrDefault<string>();
if (!string.IsNullOrEmpty(str))
{
var type = Type.GetType($"FluentAvalonia.UI.Controls.{str}, FluentAvalonia") ??
Type.GetType($"FluentAvalonia.UI.Controls.Primitives.{str}, FluentAvalonia");
if (type != null)
{
properties.Clear();
properties.Add(new ClreplacedItemViewModel(type));
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
properties.AddRange(
props
.Where(x => x.DeclaringType.replacedembly == type.replacedembly)
.Select(x => new PropertyItemViewModel(x, type)));
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);
properties.AddRange(
methods
.Where(x => x.DeclaringType.replacedembly == type.replacedembly && !x.IsSpecialName && x.GetBaseDefinition() == x)
.Select(x => new MethodItemViewModel(x, type)));
var events = type.GetEvents(BindingFlags.Public | BindingFlags.Instance);
properties.AddRange(
events
.Where(x => x.DeclaringType.replacedembly == type.replacedembly)
.Select(x => new EvenreplacedemViewModel(x)));
}
}
}
else if (change.Property == DynamicXamlTargetProperty)
{
if (change.OldValue.GetValueOrDefault() is IControl cOld)
{
cOld.PropertyChanged -= OnTargetAvPropertyChanged;
}
if (change.NewValue.GetValueOrDefault() is IControl cNew)
{
availProps = AvaloniaPropertyRegistry.Instance.GetRegistered(cNew)
.Union(AvaloniaPropertyRegistry.Instance.GetRegisteredAttached(cNew.GetType())).ToArray();
cNew.PropertyChanged += OnTargetAvPropertyChanged;
}
}
else if (change.Property == DynamicXamlPropertiesProperty)
{
if (dynamicProps == null)
dynamicProps = new Dictionary<string, string>();
else
dynamicProps.Clear();
if (change.NewValue.GetValueOrDefault() is string s)
{
var chrRd = new CharacterReader(s.replacedpan());
while (!chrRd.End)
{
var token = chrRd.TakeUntil(';');
var index = token.IndexOf(',');
if (index != -1)
{
var name = token.Slice(0, index);
var staticValue = token.Slice(index+1);
dynamicProps.Add(name.ToString(), staticValue.ToString());
}
else
{
dynamicProps.Add(token.ToString(), string.Empty);
}
chrRd.Skip(1);
}
}
UpdateXamlSource();
}
}
19
Source : ClientMessageBus.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
private static Dictionary<uint, MethodInfo> GetHandlers(IMessageBusHandler handler)
{
Dictionary<uint, MethodInfo> handlers = new Dictionary<uint, MethodInfo>();
Type handlerType = handler.GetType();
foreach (MethodInfo methodInfo in handlerType.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
{
MessageHandlerAttribute attribute = methodInfo.GetCustomAttribute<MessageHandlerAttribute>();
if (attribute != null)
{
handlers[attribute.Message] = methodInfo;
}
}
return handlers;
}
See More Examples