public static string GetRpcMethodName(MethodInfo mi) { string rpcMethod; string MethodName = mi.Name; Attribute attr = mi.GetCustomAttribute<XmlRpcBeginAttribute>(); if (attr != null) { rpcMethod = ((XmlRpcBeginAttribute)attr).Method; if (rpcMethod == "") { if (!MethodName.StartsWith("Begin") || MethodName.Length <= 5) throw new Exception(String.Format( "method {0} has invalid signature for begin method", MethodName)); rpcMethod = MethodName.Substring(5); } return rpcMethod; } // if no XmlRpcBegin attribute, must have XmlRpcMethod attribute attr = mi.GetCustomAttribute<XmlRpcMethodAttribute>(); if (attr == null) { throw new Exception("missing method attribute"); } XmlRpcMethodAttribute xrmAttr = attr as XmlRpcMethodAttribute; rpcMethod = xrmAttr.Method; if (rpcMethod == "") { rpcMethod = mi.Name; } return rpcMethod; }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="obj">The S# object the method belongs to.</param> /// <param name="method">The CLR method the metadata should be provided for.</param> /// <param name="name">The name of the method; if <c>null</c>, the method's CLR name is used.</param> /// <param name="baseMethod">The overridden base method, if any.</param> internal MethodMetadata(IMetadataObject obj, MethodInfo method, string name = null, MethodMetadata baseMethod = null) { Requires.NotNull(obj, () => obj); Requires.NotNull(method, () => method); Requires.That(name == null || !String.IsNullOrWhiteSpace(name), () => name, "The name must be null or non-whitespace only."); Requires.That(baseMethod == null || method != baseMethod.MethodInfo, "A method cannot override itself."); Requires.That(baseMethod == null || obj == baseMethod._object, "The base method must belong to the same object."); Requires.That(baseMethod == null || baseMethod.OverridingMethod == null, "The base method has already been overridden."); _object = obj; Name = EscapeName(name ?? method.Name); MethodInfo = method; BaseMethod = baseMethod; if (baseMethod != null) baseMethod.OverridingMethod = this; var backingFieldAttribute = MethodInfo.GetCustomAttribute<BackingFieldAttribute>(); if (backingFieldAttribute != null) BackingField = backingFieldAttribute.GetFieldInfo(MethodInfo.DeclaringType); var behaviorAttribute = MethodInfo.GetCustomAttribute<IntendedBehaviorAttribute>(); if (behaviorAttribute != null) IntendedBehavior = behaviorAttribute.GetMethodInfo(MethodInfo.DeclaringType); if (backingFieldAttribute == null && behaviorAttribute == null) IntendedBehavior = MethodInfo; Behaviors = new MethodBehaviorCollection(obj, this); ImplementedMethods = DetermineImplementedInterfaceMethods().ToArray(); _methodBody = new Lazy<MethodBodyMetadata>(InitializeMethodBody); }
private static TestMethod CreateMethod(TypeInfo type, object instance, MethodInfo method) { TestMethod test = new TestMethod(); test.Name = method.Name; if (method.GetCustomAttribute<AsyncTestMethodAttribute>(true) != null) { test.Test = new AsyncTestMethodAsyncAction(instance, method); } else { test.Test = new TestMethodAsyncAction(instance, method); } ExcludeTestAttribute excluded = method.GetCustomAttribute<ExcludeTestAttribute>(true); if (excluded != null) { test.Exclude(excluded.Reason); } if (method.GetCustomAttribute<FunctionalTestAttribute>(true) != null) { test.Tags.Add("Functional"); } test.Tags.Add(type.FullName + "." + method.Name); test.Tags.Add(type.Name + "." + method.Name); foreach (TagAttribute attr in method.GetCustomAttributes<TagAttribute>(true)) { test.Tags.Add(attr.Tag); } return test; }
static HttpMethods GetHttpMethod(MethodInfo m) { var postAttr = m.GetCustomAttribute<HttpPostAttribute>(); var getAttr = m.GetCustomAttribute<HttpGetAttribute>(); var putAttr = m.GetCustomAttribute<HttpPutAttribute>(); var deleteAttr = m.GetCustomAttribute<HttpDeleteAttribute>(); var patchAttr = m.GetCustomAttribute<HttpPatchAttribute>(); if (postAttr != null) return HttpMethods.Post; else if (getAttr != null) return HttpMethods.Get; else if (putAttr != null) return HttpMethods.Put; else if (deleteAttr != null) return HttpMethods.Delete; else if (patchAttr != null) return HttpMethods.Patch; else return HttpMethods.Unknown; }
private static string GetMethodName(MethodInfo methodInfo) { var webMetodAttribute = methodInfo.GetCustomAttribute(typeof(WebMethodAttribute), true) as WebMethodAttribute; var methodCustomName = webMetodAttribute.MessageName; return String.IsNullOrEmpty(methodCustomName) ? methodInfo.Name : methodCustomName; }
/// <summary> /// Returns a value indicating whether or not a server-side dispatcher should be generated for the provided <paramref name="method"/>. /// </summary> /// <param name="containingType"> /// The containing type. /// </param> /// <param name="method"> /// The method. /// </param> /// <returns> /// A value indicating whether or not a server-side dispatcher should be generated for the provided <paramref name="method"/>. /// </returns> public static bool IsVisible(Type containingType, MethodInfo method) { var typeLevelAttribute = method.DeclaringType.GetCustomAttribute<VisibleAttribute>() ?? containingType.GetCustomAttribute<VisibleAttribute>(); var hasTypeOverride = typeLevelAttribute != null && typeLevelAttribute.Visible.HasValue; var typeVisibility = typeLevelAttribute != null && typeLevelAttribute.Visible.HasValue && typeLevelAttribute.Visible.Value; var methodLevelAttribute = method.GetCustomAttribute<VisibleAttribute>(); var hasMethodOverride = methodLevelAttribute != null && methodLevelAttribute.Visible.HasValue; var methodVisibility = methodLevelAttribute != null && methodLevelAttribute.Visible.HasValue && methodLevelAttribute.Visible.Value; if (hasMethodOverride) { return methodVisibility; } if (hasTypeOverride) { return typeVisibility; } return true; }
public bool Discover(MethodInfo publicMethod, OperationMetadata methodMetadata) { var notes = publicMethod.GetCustomAttribute<NotesAttribute>() ?? new NotesAttribute(""); methodMetadata.Notes = notes.Notes; methodMetadata.Notes += "Uri template " + methodMetadata.Uri.Uri; return true; }
public IAction Generate(MethodInfo method) { if (!method.IsPublic) return null; //标记了NoAction的方法跳过 var noAction = method.GetCustomAttribute<NonActionAttribute>(); if (noAction != null) return null; var buildContext = new ActionGenerationContext(method, this.BinderFactory); return Generate(buildContext); }
public static string GetInvocationName(MethodInfo mi) { var result = mi.Name; var attr = mi.GetCustomAttribute(typeof(ActionAttribute), false) as ActionAttribute; if (attr!=null) if (attr.Name.IsNotNullOrWhiteSpace()) result = attr.Name; return result; }
protected FunctionInfoBase(IMetadataProvider metadataProvider, TTypeInfo declaringType, System.Reflection.MethodInfo native) : base(metadataProvider, declaringType, native) { Name = native.Name; Type = ResolveType(native.ReturnType, native); Mutability = native.GetCustomAttribute <ImmutableAttribute>() != null ? Mutability.Immutable : Mutability.Mutable; Permission = Permission.ReadWrite; }
public bool Discover(MethodInfo publicMethod, OperationMetadata methodMetdata) { var responseType = publicMethod.GetCustomAttribute<ResponseTypeIsAttribute>() ?? new ResponseTypeIsAttribute(publicMethod.ReturnType); methodMetdata.ReturnType = responseType.ResponseType; methodMetdata.HandlerType = publicMethod.DeclaringType; return IsTypeMatch(methodMetdata.DesiredReturnType, methodMetdata.ReturnType); }
/// <summary> /// Adds the given test to the session. This test has to be a member of the test class and needs a TestMethod Attribute. /// </summary> public void Add(MethodInfo test) { if (test.GetCustomAttribute<JUUTTestMethodAttribute>() == null) { throw new ArgumentException("Tests to be added to a TestRunner needs a TestMethod-Attribute."); } if (test.DeclaringType != TestClass) { throw new ArgumentException("The given method isn't a member of the test class."); } TestsToRun.Add(test); }
public TestMethodInfo(MethodInfo info) { if (!info.IsPublic) return; var attr = info.GetCustomAttribute(typeof(TestAttribute)) as TestAttribute; if (attr == null) return; var argCount = info.GetParameters().Length; if (argCount != 0) return; this.IsValid = true; this.Description = attr.Description; this.MethodInfo = info; }
public void Initialize(MethodInfo method, object rawTarget, UnityObject unityTarget, int id, BaseGUI gui, EditorRecord prefs) { this.prefs = prefs; this.gui = gui; this.rawTarget = rawTarget; this.unityTarget = unityTarget; this.id = id; if (initialized) return; initialized = true; isCoroutine = method.ReturnType == typeof(IEnumerator); var commentAttr = method.GetCustomAttribute<CommentAttribute>(); if (commentAttr != null) comment = commentAttr.comment; niceName = method.GetNiceName(); if (niceName.IsPrefix("dbg") || niceName.IsPrefix("Dbg")) niceName = niceName.Remove(0, 3); invoke = method.DelegateForCall(); var argInfos = method.GetParameters(); int len = argInfos.Length; argValues = new object[len]; argKeys = new int[len]; argMembers = new EditorMember[len]; for (int iLoop = 0; iLoop < len; iLoop++) { int i = iLoop; var argInfo = argInfos[i]; argKeys[i] = RuntimeHelper.CombineHashCodes(id, argInfo.ParameterType.Name + argInfo.Name); argValues[i] = TryLoad(argInfos[i].ParameterType, argKeys[i]); argMembers[i] = EditorMember.WrapGetSet( @get : () => argValues[i], @set : x => argValues[i] = x, @rawTarget : rawTarget, @unityTarget : unityTarget, @attributes : argInfo.GetCustomAttributes(true) as Attribute[], @name : argInfo.Name, @id : argKeys[i], @dataType : argInfo.ParameterType ); } #if DBG Log("Method drawer init"); #endif }
public bool Discover(MethodInfo publicMethod, OperationMetadata methodMetadata) { var attribute = publicMethod.GetCustomAttribute<NotesAttribute>() ?? new NotesAttribute(""); if(string.IsNullOrEmpty(attribute.Notes)) methodMetadata.Notes += "Uri template " + methodMetadata.Uri.Uri; else methodMetadata.Notes = attribute.Notes; return true; }
public bool Discover(MethodInfo publicMethod, OperationMetadata methodMetdata) { var descriptionAttribute = publicMethod.GetCustomAttribute<DescriptionAttribute>(); methodMetdata.Nickname = publicMethod.Name; methodMetdata.Summary = descriptionAttribute == null ? GetMethodName(publicMethod) : descriptionAttribute.Description; return true; }
public CacheAttribute GetCacheAttribute(MethodInfo method) { var cacheAttribute = method.GetCustomAttribute(typeof(CacheAttribute)); if (cacheAttribute != null) { var typedAttribute = (CacheAttribute)cacheAttribute; return typedAttribute; } return null; }
public string Map(MethodInfo method) { WampRpcMethodAttribute rpcMethodAttribute = method.GetCustomAttribute<WampRpcMethodAttribute>(true); if (rpcMethodAttribute == null) { throw new ArgumentException("Method doesn't have WampRpcMethodAttribute", "method"); } return rpcMethodAttribute.ProcUri; }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="fault">The fault the fault effect belongs to.</param> /// <param name="faultEffect">The CLR method the metadata is provided for.</param> /// <param name="affectedMethod">The CLR method representing the method affected by the fault effect.</param> /// <param name="name">The name of the fault effect; if <c>null</c>, the method's CLR name is used.</param> internal FaultEffectMetadata(Fault fault, MethodInfo faultEffect, MethodInfo affectedMethod, string name = null) : base(fault, faultEffect, name) { Requires.NotNull(fault, () => fault); Requires.NotNull(faultEffect, () => faultEffect); Requires.NotNull(affectedMethod, () => affectedMethod); _affectedMethod = affectedMethod; var priorityAttribute = faultEffect.GetCustomAttribute<PriorityAttribute>(); if (priorityAttribute != null) Priority = priorityAttribute.Priority; }
/// <summary> /// Checks for <see cref="N1QlFunctionAttribute" /> and creates a new <see cref="N1QlFunctionMethodCallTranslator" /> /// if it is found. If not found, returns null. /// </summary> protected virtual IMethodCallTranslator CreateFromN1QlFunctionAttribute(MethodInfo key) { if (key == null) { throw new ArgumentNullException("key"); } var attribute = key.GetCustomAttribute<N1QlFunctionAttribute>(true); return attribute == null ? null : new N1QlFunctionMethodCallTranslator(key, attribute); }
private bool IsIncluded(MethodInfo method, Type controllerType) { var rule = _configuration.InclusionRule; var controllerAttribute = controllerType.GetCustomAttribute<ProxyInclusionAttribute>(); if (controllerAttribute != null) rule = controllerAttribute.InclusionRule; var methodAttribute = method.GetCustomAttribute<ProxyInclusionAttribute>(); if (methodAttribute != null) rule = methodAttribute.InclusionRule; return rule == InclusionRule.IncludeAll; }
/// <summary> /// Creates a new report for the <code>method</code> and it's raised exception or <code>null</code>, if the test passed successfully. /// </summary> /// <param name="method">The info of the runned test method.</param> /// <param name="raisedException">The raised exception or <code>null</code>, if the test passed successfully.</param> public MethodReport(MethodInfo method, Exception raisedException) { if (method == null) { throw new ArgumentException("The method of a report can't be null."); } if (method.GetCustomAttribute<JUUTMethodAttribute>() == null) { throw new ArgumentException("Methods of a MethodReport have to have an attribute of type JUUTMethodAttribute."); } Method = method; Status = ReportStatus.Create(raisedException); RaisedException = raisedException; InitializeTexts(Method, Status, RaisedException); }
private MethodInfo ResolveBestMethodInfo(MethodInfo method) { // If a method has a StateMachineAttribute, then all of the user code will show up // in the symbols associated with the compiler-generated code. So, we need to look // for the 'MoveNext' on the generated type and resolve symbols for that. var attribute = method.GetCustomAttribute<StateMachineAttribute>(); if (attribute?.StateMachineType == null) { return method; } return attribute.StateMachineType.GetMethod( "MoveNext", BindingFlags.Instance | BindingFlags.NonPublic); }
// https://stackoverflow.com/questions/20350397/how-can-i-tell-if-a-c-sharp-method-is-async-await-via-reflection private static bool IsAsyncMethod(System.Type classType, string methodName) { // Obtain the method with the specified name. System.Reflection.MethodInfo method = classType.GetMethod(methodName); System.Type attType = typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute); // Obtain the custom attribute for the method. // The value returned contains the StateMachineType property. // Null is returned if the attribute isn't present for the method. System.Runtime.CompilerServices.AsyncStateMachineAttribute attrib = (System.Runtime.CompilerServices.AsyncStateMachineAttribute) method.GetCustomAttribute(attType); return(attrib != null); }
/// <summary> /// Determine if the specified <paramref name="method"/> conforms to the configured apply method specification. /// </summary> /// <param name="method">The method info for the apply method candidate.</param> protected override Boolean MatchesApplyMethodDefinition(MethodInfo method) { var attribute = method.GetCustomAttribute<ApplyMethodAttribute>(); if (attribute == null) return false; if (method.ReturnParameter == null || method.ReturnParameter.ParameterType != typeof(void)) throw new MappingException(Exceptions.AggregateApplyMethodMustHaveVoidReturn.FormatWith(method.ReflectedType, method.Name)); var parameters = method.GetParameters(); if (parameters.Length != 1 || !parameters[0].ParameterType.DerivesFrom(typeof(Event))) throw new MappingException(Exceptions.AggregateApplyMethodInvalidParameters.FormatWith(typeof(Event), method.ReflectedType, method.Name)); return true; }
/// <summary> /// Gets the <see cref="Statement" /> representing the <paramref name="method" />'s body. /// </summary> /// <param name="obj">The object the method body should be returned for.</param> /// <param name="method">The method the method body should be returned for.</param> public MethodBodyMetadata GetMethodBody(object obj, MethodInfo method) { Requires.NotNull(obj, () => obj); Requires.NotNull(method, () => method); var attribute = method.GetCustomAttribute<MethodBodyMetadataAttribute>(); Requires.That(attribute != null, "Expected the method to be marked with an instance of '{0}'.", GetType().FullName); var bodyMethod = method.DeclaringType.GetMethod(MethodName, BindingFlags.Instance | BindingFlags.NonPublic); Requires.That(bodyMethod != null, "Unable to find the method body initialization method of method '{0}' declared by '{1}'.", method, method.DeclaringType.FullName); Requires.That(bodyMethod.GetParameters().Length == 0, "Expected no parameters on method '{0}' declared by '{1}'.", method, method.DeclaringType.FullName); Requires.That(bodyMethod.ReturnType == typeof(MethodBodyMetadata), "Expected method '{0}' declared by '{1}' to return a '{2}'.", method, method.DeclaringType.FullName, typeof(MethodBodyMetadata).FullName); return (MethodBodyMetadata)bodyMethod.Invoke(obj, null); }
public async Task<object> Invoke(MethodInfo methodInfo, InvokeMethodRequest request, IGrainMethodInvoker invoker) { if (methodInfo.Name == "One" && methodInfo.GetParameters().Length == 0) { return "intercepted one with no args"; } var result = await invoker.Invoke(this, request); // To prove that the MethodInfo is from the implementation and not the interface, // we check for this attribute which is only present on the implementation. This could be // done in a simpler fashion, but this demonstrates a potential usage scenario. var shouldMessWithResult = methodInfo.GetCustomAttribute<MessWithResultAttribute>(); var resultString = result as string; if (shouldMessWithResult != null && resultString !=null) { result = string.Concat(resultString.Reverse()); } return result; }
public RpcMethodInfo(RpcService hService, MethodInfo hMethod) { Method = hMethod; Attribute = hMethod.GetCustomAttribute<ServiceOperation>(); if (Attribute == null) throw new MissingAttributeException("Missing ServiceOperation Attribute on Method " + hMethod.Name); Service = hService; if (Attribute.Type == RpcType.OneWay && hMethod.ReturnType != typeof(void)) throw new Exception("OneWay Rpc's require void return type, check method signature " + hMethod.Name); Request = new RequestCodeGen(this, Service.Pair.ProtocolCounter); Service.Pair.ProtocolCounter++; if (Attribute.Type == RpcType.TwoWay) { Response = new ResponseCodeGen(this, Service.Pair.ProtocolCounter); Service.Pair.ProtocolCounter++; } if (hService.Attribute is ServiceContract && Attribute.Type == RpcType.OneWay) { RequestAction = new RequestActionCodeGen(new OneWayServerReqActionBuilder(), this); } else if (hService.Attribute is ServiceContract) { ResponseAction = new ResponseActionCodeGen(new ServerResActionBuilder(), this); RequestAction = new RequestActionCodeGen(new TwoWayServerReqActionBuilder(), this); } else if (hService.Attribute is CallbackContract && Attribute.Type == RpcType.OneWay) { RequestAction = new RequestActionCodeGen(new OneWayClientReqActionBuilder(), this); } else { ResponseAction = new ResponseActionCodeGen(new ClientResActionBuilder(), this); RequestAction = new RequestActionCodeGen(new TwoWayClientReqActionBuilder(), this); } }
public ActionHandler(object controller, System.Reflection.MethodInfo method, HttpApiServer httpApiServer) { ID = System.Threading.Interlocked.Increment(ref mIdSeed); Remark = ""; Parameters = new List <ParameterBinder>(); mMethod = method; mMethodHandler = new MethodHandler(mMethod); Controller = controller; HttpApiServer = httpApiServer; LoadParameter(); Filters = new List <FilterAttribute>(); Method = "GET"; SingleInstance = true; ControllerType = Controller.GetType(); NoConvert = false; var aname = controller.GetType().Assembly.GetName(); this.AssmblyName = aname.Name; this.Version = aname.Version.ToString(); ThreadQueue = method.GetCustomAttribute <ThreadQueueAttribute>(false); Async = false; }
private TestCase( MethodInfo testMethodInfo, IEnumerable<MethodInfo> testInitializeMethodInfos, IEnumerable<MethodInfo> testCleanUpMethodInfos, AppDomain appDomain) { _testMethodInfo = testMethodInfo; _testInitializeMethodInfos = testInitializeMethodInfos .OrderBy(x => x.DeclaringType.GetInheritanceHierarchyDepth()); _testCleanUpMethodInfos = testCleanUpMethodInfos .OrderBy(x => x.DeclaringType.GetInheritanceHierarchyDepth()); Id = Guid.NewGuid(); AppDomain = appDomain; Categories = _testMethodInfo.GetCustomAttributes<TestCategoryAttribute>().SelectMany(x => x.TestCategories).ToArray(); Name = testMethodInfo.Name; AssemblyName = testMethodInfo.DeclaringType?.Assembly.GetName().Name; TestClassName = testMethodInfo.DeclaringType?.Name; IsIgnored = testMethodInfo.GetCustomAttribute<IgnoreAttribute>() != null; }
// NOTE: 16 parameter max for Expression.GetDelegateType public RegistrationEntry(MethodInfo methodInfo) { MethodInfo = methodInfo; var paramExprs = methodInfo.GetParameters() .Select(pi => Expression.Parameter(pi.ParameterType, pi.Name)) .ToArray(); FunctionLambda = Expression.Lambda(Expression.Call(methodInfo, paramExprs), methodInfo.Name, paramExprs); // Need to make sure we have explicit FunctionAttribute = methodInfo.GetCustomAttribute<ExcelFunctionAttribute>(); if (FunctionAttribute == null) FunctionAttribute = new ExcelFunctionAttribute { Name = methodInfo.Name }; else if (string.IsNullOrEmpty(FunctionAttribute.Name)) FunctionAttribute.Name = methodInfo.Name; ArgumentAttributes = new List<ExcelArgumentAttribute>(); foreach (var pi in methodInfo.GetParameters()) { var argAtt = pi.GetCustomAttribute<ExcelArgumentAttribute>(); if (argAtt == null) argAtt = new ExcelArgumentAttribute { Name = pi.Name }; else if (string.IsNullOrEmpty(argAtt.Name)) argAtt.Name = pi.Name; ArgumentAttributes.Add(argAtt); } // Special check for final Params argument - transform to an ExcelParamsArgumentAttribute // NOTE: This won't work with a custom derived attribute... var lastParam = methodInfo.GetParameters().LastOrDefault(); if (lastParam != null && lastParam.GetCustomAttribute<ParamArrayAttribute>() != null) { var excelParamsAtt = new ExcelParamsArgumentAttribute(ArgumentAttributes.Last()); ArgumentAttributes[ArgumentAttributes.Count - 1] = excelParamsAtt; } }
/// <summary> /// 动态生成方法 /// </summary> /// <param name="methodInfo"></param> void BuildMethod(MethodInfo methodInfo) { string methodName = methodInfo.Name; ParameterInfo[] parameterInfos = methodInfo.GetParameters(); Type returnType = methodInfo.ReturnType; MethodBuilder methodBuilder = _typeBuilder.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Virtual, returnType, parameterInfos.Select(pi => pi.ParameterType).ToArray()); var generator = methodBuilder.GetILGenerator(); Label castPreSuccess = generator.DefineLabel(); Label castPreSuccess1 = generator.DefineLabel(); Label castPostSuccess = generator.DefineLabel(); Label castExSuccess = generator.DefineLabel(); Label castRetSuccess = generator.DefineLabel(); #region 事务实例化 // ICO_AOPEnableAttribute ia = (ICO_AOPEnableAttribute) iType.GetCustomAttribute(typeof(ICO_AOPEnableAttribute), false); AOPTransactionAttribute AOPConfig = (AOPTransactionAttribute) methodInfo.GetCustomAttribute(typeof(AOPTransactionAttribute), false); MethodInfo openTransaction = this._realProxyType.GetMethod("OpenTransaction", new Type[] { }, null); if ( AOPConfig != null && AOPConfig.TransactionEnable && _realProxyType.BaseType != null && openTransaction!=null ) { generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, _realProxyField); generator.Emit(OpCodes.Callvirt, openTransaction); } //if ( _baseType != null ) //{ // generator.Emit(OpCodes.Ldarg_0); // generator.Emit(OpCodes.Ldstr, "OraString"); // MethodInfo oraString = this._baseType.GetMethod("ChangeDatabase", new Type[] { typeof(string) }, null); // generator.Emit(OpCodes.Call, oraString); // generator.Emit(OpCodes.Ldarg_0); // generator.Emit(OpCodes.Ldarg_0); // generator.Emit(OpCodes.Ldfld, _typeBuilder.BaseType.GetField("EF")); // PropertyInfo efDatabase = typeof(System.Data.Entity.DbContext).GetProperty("Database"); // generator.Emit(OpCodes.Callvirt, efDatabase.GetMethod); // MethodInfo beginTransaction = typeof(System.Data.Entity.Database).GetMethod("BeginTransaction", new Type[] { }, null); // generator.Emit(OpCodes.Callvirt, beginTransaction); // generator.Emit(OpCodes.Stfld, _dbContextTransaction); //} #endregion #region 实例化 InvokeContext Type contextType = typeof(InvokeContext); //所有元数据 var contextLocal = generator.DeclareLocal(contextType); generator.Emit(OpCodes.Newobj, contextType.GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Stloc, contextLocal); //设置方法名 generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Ldstr, methodName); generator.Emit(OpCodes.Call, contextType.GetMethod("SetMethod", BindingFlags.Public | BindingFlags.Instance)); //设置类名 generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Ldstr, _realProxyType.FullName); generator.Emit(OpCodes.Call, contextType.GetMethod("SetClassName", BindingFlags.Public | BindingFlags.Instance)); //设置返回类型 generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Ldtoken, methodInfo.ReturnType); generator.Emit(OpCodes.Call, typeof(System.Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(System.RuntimeTypeHandle) })); PropertyInfo ResultType = contextType.GetProperty("ResultType"); generator.Emit(OpCodes.Callvirt, ResultType.SetMethod); #endregion #region 声明 result 初始化 LocalBuilder resultLocal = null; if (returnType != typeof(void)) { resultLocal = generator.DeclareLocal(returnType); if (returnType.IsValueType) { generator.Emit(OpCodes.Ldstr, returnType.FullName); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetType", new Type[] { typeof(string) })); generator.Emit(OpCodes.Call, typeof(Activator).GetMethod("CreateInstance", new Type[] { typeof(Type) })); } else { generator.Emit(OpCodes.Ldnull); } generator.Emit(OpCodes.Stloc, resultLocal); } #endregion #region 声明 Exception 初始化 var exceptionLocal = generator.DeclareLocal(typeof(Exception)); generator.Emit(OpCodes.Ldnull); generator.Emit(OpCodes.Stloc, exceptionLocal); #endregion #region Invoke PreInvoke 方法执行前 #region Set parameter to InvkeContext 为参数元数据特性添加参数 for (int i = 1; i <= parameterInfos.Length; i++) { generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Ldarg, i); if (parameterInfos[i - 1].ParameterType.IsValueType) { generator.Emit(OpCodes.Box, parameterInfos[i - 1].ParameterType); } #warning out 参数作为指针传送无法中途拦截赋值 必须在方法中实现赋值目前有没有找到有效解决方案 //if ( parameterInfos[i - 1].ParameterType.Name.Contains("&") ) //{ // generator.Emit(OpCodes.Box, Type.GetType( parameterInfos[i - 1].ParameterType.FullName.Replace("&",""))); // generator.Emit(OpCodes.Unbox, Type.GetType(parameterInfos[i - 1].ParameterType.FullName.Replace("&", ""))); //} generator.Emit(OpCodes.Call, contextType.GetMethod("SetParameter", BindingFlags.Public | BindingFlags.Instance)); } #endregion /* * C# 代码 * MethodInfo methodInfoLocal = _realProxyField.GetType().GetMethod("methodName"); * PreAspectAttribute preAspectLocal = * (PreAspectAttribute)Attribute.GetCustomAttribute(methodInfoLocal, typeof(PreAspectAttribute)) */ var methodInfoLocal = generator.DeclareLocal(typeof(System.Reflection.MethodInfo)); var preAspectLocal = generator.DeclareLocal(typeof(PreAspectAttribute)); // var boolLocal = generator.DeclareLocal(typeof(bool)); // Label castboolSuccess = generator.DefineLabel(); // generator.Emit(OpCodes.Ldc_I4_1); // generator.Emit(OpCodes.Stloc, boolLocal); var Typeparmeter = generator.DeclareLocal(typeof(Type[])); generator.Emit(OpCodes.Ldc_I4, parameterInfos.Length); generator.Emit(OpCodes.Newarr, typeof(Type)); generator.Emit(OpCodes.Stloc, Typeparmeter); for ( int i = 0; i < parameterInfos.Length; i++ ) { generator.Emit(OpCodes.Ldloc, Typeparmeter); generator.Emit(OpCodes.Ldc_I4, i); //TypeToken typetoken = new TypeToken(); if ( parameterInfos[i].ParameterType.Name.Contains("&") ) { string typstr = parameterInfos[i].ParameterType.FullName.Replace("&", ""); Type typetem = Type.GetType(typstr); generator.Emit(OpCodes.Ldtoken, typetem); } else { generator.Emit(OpCodes.Ldtoken, parameterInfos[i].ParameterType); } generator.Emit(OpCodes.Call, typeof(System.Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(System.RuntimeTypeHandle) })); if ( parameterInfos[i].ParameterType.Name.Contains("&") ) { generator.Emit(OpCodes.Callvirt, typeof(System.Type).GetMethod("MakeByRefType")); } generator.Emit(OpCodes.Stelem_Ref); } //相当于this generator.Emit(OpCodes.Ldarg_0); //构造中实例化的对象 generator.Emit(OpCodes.Ldfld, _realProxyField); generator.Emit(OpCodes.Callvirt, typeof(System.Object).GetMethod("GetType", BindingFlags.Public | BindingFlags.Instance)); generator.Emit(OpCodes.Ldstr, methodName); generator.Emit(OpCodes.Ldloc, Typeparmeter); generator.Emit(OpCodes.Callvirt, typeof(System.Type).GetMethod("GetMethod", new Type[] { typeof(string),typeof(Type[]) })); generator.Emit(OpCodes.Stloc, methodInfoLocal); generator.Emit(OpCodes.Ldloc, methodInfoLocal); //typeof(PreAspectAttribute) generator.Emit(OpCodes.Ldtoken, typeof(PreAspectAttribute)); generator.Emit(OpCodes.Call, typeof(System.Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(System.RuntimeTypeHandle) })); //Attribute.GetCustomAttribute(methodInfoLocal, typeof(PreAspectAttribute)) generator.Emit(OpCodes.Call, typeof(System.Attribute).GetMethod("GetCustomAttribute", new Type[] { typeof(System.Reflection.MethodInfo), typeof(System.Type) })); //(PreAspectAttribute) generator.Emit(OpCodes.Castclass, typeof(PreAspectAttribute)); generator.Emit(OpCodes.Stloc, preAspectLocal); /* * if (preAspectLocal != null) * { * preAspectLocal.Action(contextLocal); * } * */ generator.Emit(OpCodes.Ldloc, preAspectLocal); generator.Emit(OpCodes.Ldnull); generator.Emit(OpCodes.Ceq); generator.Emit(OpCodes.Brtrue_S, castPreSuccess); generator.Emit(OpCodes.Ldloc, preAspectLocal); generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Callvirt, typeof(AspectAttribute).GetMethod("Action", new Type[]{ typeof(InvokeContext) })); generator.Emit(OpCodes.Stloc, contextLocal); generator.MarkLabel(castPreSuccess); // generator.Emit(OpCodes.Ldloc, boolLocal); generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Callvirt, contextType.GetProperty("IsRun").GetMethod); generator.Emit(OpCodes.Ldc_I4_1); generator.Emit(OpCodes.Ceq); generator.Emit(OpCodes.Brtrue_S, castPreSuccess1); if (returnType != typeof(void)) { if (returnType.IsValueType) { generator.Emit(OpCodes.Ldstr, returnType.FullName); generator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetType", new Type[] { typeof(string) })); generator.Emit(OpCodes.Call, typeof(Activator).GetMethod("CreateInstance", new Type[] { typeof(Type) })); } else { generator.Emit(OpCodes.Ldnull); } generator.Emit(OpCodes.Stloc, resultLocal); generator.Emit(OpCodes.Ldloc, resultLocal); } generator.Emit(OpCodes.Ret); generator.MarkLabel(castPreSuccess1); #endregion #region Begin Exception Block 开始异常捕获 //Try Label exLbl = generator.BeginExceptionBlock(); #endregion #region Invoke 反射原方法 generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, _realProxyField); for (int i = 1; i <= parameterInfos.Length; i++) { generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Callvirt, contextType.GetProperty("Parameters").GetMethod); generator.Emit(OpCodes.Ldc_I4, i - 1); generator.Emit(OpCodes.Callvirt, typeof(List<object>).GetMethod("get_Item")); if ( parameterInfos[i - 1].ParameterType.IsValueType ) { generator.Emit(OpCodes.Unbox_Any, parameterInfos[i - 1].ParameterType); } } Type[] parameterInfostypes = new Type[parameterInfos.Length]; for ( int i = 0; i < parameterInfos.Length; i++ ) { parameterInfostypes[i] = parameterInfos[i].ParameterType; } generator.Emit(OpCodes.Call, _realProxyType.GetMethod(methodName,BindingFlags.ExactBinding| BindingFlags.Public | BindingFlags.Instance, null, parameterInfostypes, null)); if (typeof(void) != returnType) { generator.Emit(OpCodes.Stloc, resultLocal); } #endregion #region Invoke PostInovke 原方法执行完 #region Set result to InvkeContext 设置返回元数据 generator.Emit(OpCodes.Ldloc, contextLocal); // load parameter if (typeof(void) != returnType) { generator.Emit(OpCodes.Ldloc, resultLocal); if (returnType.IsValueType) { generator.Emit(OpCodes.Box, returnType); } } else { generator.Emit(OpCodes.Ldnull); } generator.Emit(OpCodes.Call, contextType.GetMethod("SetResult", BindingFlags.Public | BindingFlags.Instance)); #endregion var postAspectLocal = generator.DeclareLocal(typeof(PostAspectAttribute)); // PostAspectAttribute attribute2 = (PostAspectAttribute) Attribute.GetCustomAttribute(method, typeof(PostAspectAttribute)); generator.Emit(OpCodes.Ldloc, methodInfoLocal); generator.Emit(OpCodes.Ldtoken, typeof(PostAspectAttribute)); generator.Emit(OpCodes.Call, typeof(System.Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(System.RuntimeTypeHandle) })); generator.Emit(OpCodes.Call, typeof(System.Attribute).GetMethod("GetCustomAttribute", new Type[] { typeof(System.Reflection.MethodInfo), typeof(System.Type) })); generator.Emit(OpCodes.Castclass, typeof(PostAspectAttribute)); generator.Emit(OpCodes.Stloc, postAspectLocal); // if (attribute2 != null) //{ // attribute2.Action(context); //} generator.Emit(OpCodes.Ldloc, postAspectLocal); generator.Emit(OpCodes.Ldnull); generator.Emit(OpCodes.Ceq); generator.Emit(OpCodes.Brtrue_S, castPostSuccess); generator.Emit(OpCodes.Ldloc, postAspectLocal); generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Callvirt, typeof(AspectAttribute).GetMethod("Action", new Type[] { typeof(InvokeContext) })); generator.Emit(OpCodes.Stloc, contextLocal); //获取拦截的返回值 // IL_0021: ldloc.1 //IL_0022: callvirt instance object MtAop.Context.InvokeContext::get_Result() //IL_0027: call valuetype [mscorlib]System.Decimal [mscorlib]System.Convert::ToDecimal(object) MethodInfo convertMethodInfo = null; Type convertType = null; PropertyInfo Result = contextType.GetProperty("Result"); if ( methodInfo.ReturnType != typeof(void) ) { if ( methodInfo.ReturnType.IsGenericType && methodInfo.ReturnType.IsInterface ) { convertType = typeof(List<>).MakeGenericType(methodInfo.ReturnType.GetGenericArguments()); } //else if ( ( methodInfo.ReturnType.IsGenericType && !methodInfo.ReturnType.IsInterface ) || methodInfo.ReturnType.IsClass ||) else if ( !methodInfo.ReturnType.IsValueType ) { convertType = methodInfo.ReturnType; } else { convertMethodInfo = typeof(System.Convert).GetMethod("To" + methodInfo.ReturnType.Name, new Type[] { typeof(object) }); } // methodInfo.ReturnType.IsValueType generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Callvirt, Result.GetMethod); if ( !methodInfo.ReturnType.IsValueType ) { generator.Emit(OpCodes.Castclass, convertType); } else { generator.Emit(OpCodes.Call, convertMethodInfo); } generator.Emit(OpCodes.Stloc, resultLocal); } generator.MarkLabel(castPostSuccess); if ( AOPConfig != null && AOPConfig.TransactionEnable && _realProxyType.BaseType != null && openTransaction != null ) { generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, _realProxyField); MethodInfo CommitTransaction = this._realProxyType.GetMethod("Commit", new Type[] { }, null); generator.Emit(OpCodes.Callvirt, CommitTransaction); } #endregion #region Catch Block 出现异常处理块 generator.BeginCatchBlock(typeof(Exception)); if ( AOPConfig != null && AOPConfig.TransactionEnable && _realProxyType.BaseType != null && openTransaction != null ) { generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, _realProxyField); MethodInfo RollbackTransaction = this._realProxyType.GetMethod("Rollback", new Type[] { }, null); generator.Emit(OpCodes.Callvirt, RollbackTransaction); } //if ( _baseType != null ) //{ // generator.Emit(OpCodes.Ldarg_0); //this // generator.Emit(OpCodes.Ldfld, _dbContextTransaction); // MethodInfo rollbackTransaction = typeof(System.Data.Entity.DbContextTransaction).GetMethod("Rollback", new Type[] { }, null); // generator.Emit(OpCodes.Callvirt, rollbackTransaction); //} //e = exception1; //context.SetError(e); generator.Emit(OpCodes.Stloc, exceptionLocal); generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Ldloc, exceptionLocal); generator.Emit(OpCodes.Call, contextType.GetMethod("SetError", BindingFlags.Public | BindingFlags.Instance)); var exAspectLocal = generator.DeclareLocal(typeof(ExceptionAspectAttribute)); // PostAspectAttribute attribute3 = (PostAspectAttribute) ((ExceptionAspectAttribute) Attribute.GetCustomAttribute(method, typeof(ExceptionAspectAttribute))); generator.Emit(OpCodes.Ldloc, methodInfoLocal); generator.Emit(OpCodes.Ldtoken, typeof(ExceptionAspectAttribute)); generator.Emit(OpCodes.Call, typeof(System.Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(System.RuntimeTypeHandle) })); generator.Emit(OpCodes.Call, typeof(System.Attribute).GetMethod("GetCustomAttribute", new Type[] { typeof(System.Reflection.MethodInfo), typeof(System.Type) })); generator.Emit(OpCodes.Castclass, typeof(ExceptionAspectAttribute)); generator.Emit(OpCodes.Stloc, exAspectLocal); //if (attribute3 != null) //{ // attribute3.Action(context); //} generator.Emit(OpCodes.Ldloc, exAspectLocal); generator.Emit(OpCodes.Ldnull); generator.Emit(OpCodes.Ceq); generator.Emit(OpCodes.Brtrue_S, castExSuccess); generator.Emit(OpCodes.Ldloc, exAspectLocal); generator.Emit(OpCodes.Ldloc, contextLocal); generator.Emit(OpCodes.Callvirt, typeof(AspectAttribute).GetMethod("Action", new Type[] { typeof(InvokeContext) })); generator.Emit(OpCodes.Stloc, contextLocal); //获取拦截的返回值 if ( methodInfo.ReturnType != typeof(void) ) { generator.Emit(OpCodes.Ldloc, contextLocal); // PropertyInfo ResultType = contextType.GetProperty("ResultType"); generator.Emit(OpCodes.Callvirt, Result.GetMethod); if ( !methodInfo.ReturnType.IsValueType ) { generator.Emit(OpCodes.Castclass, convertType); } else { generator.Emit(OpCodes.Call, convertMethodInfo); } generator.Emit(OpCodes.Stloc, resultLocal); } generator.Emit(OpCodes.Leave_S, castRetSuccess); generator.MarkLabel(castExSuccess); generator.Emit(OpCodes.Ldloc, exceptionLocal); generator.Emit(OpCodes.Throw); #endregion #region End Exception Block generator.EndExceptionBlock(); #endregion generator.MarkLabel(castRetSuccess); //if ( _baseType != null ) //{ // generator.Emit(OpCodes.Ldarg_0); // generator.Emit(OpCodes.Ldfld, _dbContextTransaction); // MethodInfo commitTransaction = typeof(System.Data.Entity.DbContextTransaction).GetMethod("Commit", new Type[] { }, null); // generator.Emit(OpCodes.Callvirt, commitTransaction); //} if (typeof(void) != returnType) { generator.Emit(OpCodes.Ldloc, resultLocal); } generator.Emit(OpCodes.Ret); }
private void LoadParameter() { DescriptionAttribute da = mMethod.GetCustomAttribute <DescriptionAttribute>(false); if (da != null) { this.Remark = da.Description; } foreach (System.Reflection.ParameterInfo pi in mMethod.GetParameters()) { ParameterBinder pb = new DefaultParameter(); ParameterBinder[] customPB = (ParameterBinder[])pi.GetCustomAttributes(typeof(ParameterBinder), false); if (customPB != null && customPB.Length > 0) { pb = customPB[0]; } else if (pi.ParameterType == typeof(Boolean)) { pb = new BooleanParameter(); } else if (pi.ParameterType == typeof(string)) { pb = new StringParameter(); } else if (pi.ParameterType == typeof(DateTime)) { pb = new DateTimeParameter(); } else if (pi.ParameterType == typeof(Decimal)) { pb = new DecimalParameter(); } else if (pi.ParameterType == typeof(float)) { pb = new FloatParameter(); } else if (pi.ParameterType == typeof(double)) { pb = new DoubleParameter(); } else if (pi.ParameterType == typeof(short)) { pb = new ShortParameter(); } else if (pi.ParameterType == typeof(int)) { pb = new IntParameter(); } else if (pi.ParameterType == typeof(long)) { pb = new LongParameter(); } else if (pi.ParameterType == typeof(ushort)) { pb = new UShortParameter(); } else if (pi.ParameterType == typeof(uint)) { pb = new UIntParameter(); } else if (pi.ParameterType == typeof(ulong)) { pb = new ULongParameter(); } else if (pi.ParameterType == typeof(HttpRequest)) { pb = new RequestParameter(); } else if (pi.ParameterType == typeof(IHttpContext)) { pb = new HttpContextParameter(); } else if (pi.ParameterType == typeof(IDataContext)) { pb = new DataContextParameter(); } else if (pi.ParameterType == typeof(HttpApiServer)) { pb = new HttpApiServerParameter(); } else if (pi.ParameterType == typeof(HttpResponse)) { pb = new ResponseParameter(); } else { pb = new DefaultParameter(); } pb.Name = pi.Name; pb.Type = pi.ParameterType; Parameters.Add(pb); } }
internal CommandHandlerInfo(MethodInfo method) { Method = method; Attribute = method.GetCustomAttribute<CommandHandlerAttribute>(); Debug.Assert(Attribute != null); Parameters = (from e in method.GetParameters() select new CommandParameterInfo(e)).ToArray(); }