How to call Action<string, bool> from il generator - c#

In this example code i am trying to invoke a anonymous action from il generator. I am not sure if and how i can load the reference to the delegate and how to call it.
I can do it if the OnFunctionCall is a static method not property.
public delegate void TestDelegate();
public static class ExampleOne
{
public static Action<string, bool> OnFunctionCall
=> (message, flag) => Console.WriteLine("Example");
}
public static class ExampleTwo
{
public static TType CreateDelegate<TType>(Action<string, bool> onFunctionCall)
where TType : class
{
var method = new DynamicMethod($"{Guid.NewGuid()}", typeof(void), Type.EmptyTypes, typeof(TType), true);
ILGenerator il = method.GetILGenerator();
// Emit some code that invoke unmanaged function ...
// loading the first string argument
il.Emit(OpCodes.Ldstr, method.Name);
// not sure here how to load boolean value to the stack
il.Emit(OpCodes.Ldc_I4_0);
// this line doesn't work
// example two has no idea about ExampleOne
// is it possible to load the reference of the Action<string, bool> to the stack and call it ?
il.Emit(OpCodes.Call, onFunctionCall.Method);
il.Emit(OpCodes.Ret);
return method.CreateDelegate(typeof(TestDelegate)) as TType;
}
}
public class Program
{
public static void Main(string[] args)
=> ExampleTwo
.CreateDelegate<TestDelegate>(ExampleOne.OnFunctionCall)
.Invoke();
}

You have to pass the information where the delegate you want to invoke is stored. The convenience way is to accept a MemberExpression, otherwise accepting a MemberInfowould work too. Have a look at your modified code:
public delegate void TestDelegate();
public static class ExampleOne
{
public static Action<string, bool> OnFunctionCall
=> (message, flag) => Console.WriteLine("OnFunctionCall");
public static Action<string, bool> OnFunctionCallField
= (message, flag) => Console.WriteLine("OnFunctionCallField");
}
public static class ExampleTwo
{
public static TType CreateDelegate<TType>(Expression<Func<object>> expression)
where TType : class
{
var body = expression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException(nameof(expression));
}
var method = new DynamicMethod($"{Guid.NewGuid()}", typeof(void), Type.EmptyTypes, typeof(TType), true);
ILGenerator il = method.GetILGenerator();
// Get typed invoke method and
// call getter or load field
MethodInfo invoke;
if (body.Member is PropertyInfo pi)
{
invoke = pi.PropertyType.GetMethod("Invoke");
il.Emit(OpCodes.Call, pi.GetGetMethod());
}
else if (body.Member is FieldInfo fi)
{
invoke = fi.FieldType.GetMethod("Invoke");
il.Emit(OpCodes.Ldsfld, fi);
}
else
{
throw new ArgumentException(nameof(expression));
}
il.Emit(OpCodes.Ldstr, method.Name);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Callvirt, invoke);
il.Emit(OpCodes.Ret);
return method.CreateDelegate(typeof(TestDelegate)) as TType;
}
}
public class Program
{
public static void Main(string[] args)
{
ExampleTwo
.CreateDelegate<TestDelegate>(() => ExampleOne.OnFunctionCall)
.Invoke();
ExampleTwo
.CreateDelegate<TestDelegate>(() => ExampleOne.OnFunctionCallField)
.Invoke();
Console.ReadLine();
}
}
The code is running on .Net Core 2.0.

Related

How to create delegate of Func<a,b> when a's method has parameters

I am trying to call a method that takes in a function, but using relection. I've gotten it to work when the method is parameterless but I can't figure out how to invoke it when there are arguments. This is a contrived simplified example, but this boils down the problem. I will not know the arguments to Add until runtime.
Any pointers? Do I have to use expression trees? Is there an easier way to do this?
public void Main()
{
//works
CallFunction(typeof (Processor), "Count");
//I don't understand what I need to modify to make add work
CallFunction(typeof (Processor), "Add");
}
public void CallFunction(Type type, string methodToCall)
{
var targetMethod = type.GetMethod(methodToCall);
var constructedType = typeof (MethodCaller<>).MakeGenericType(type);
dynamic target = Activator.CreateInstance(constructedType);
var method = constructedType.GetMethod("Do").MakeGenericMethod(targetMethod.ReturnType);
var func = typeof (Func<,>).MakeGenericType(type, targetMethod.ReturnType);
var toCall = Delegate.CreateDelegate(func, targetMethod);
method.Invoke(target, new object[] { toCall });
}
public class Processor
{
public int Count()
{
return 1;
}
public int Add(int toAdd)
{
return 1 + toAdd;
}
}
public class MethodCaller<TParm> where TParm : new()
{
public TResult Do<TResult>(Func<TParm, TResult> func)
{
return func(new TParm());
}
}
Like type.InvokeMember(method_name, System.Reflection.BindingFlags.InvokeMethod, null, type_instance, new object[] { param1, param2, param3 }); ?
https://msdn.microsoft.com/en-us/library/66btctbe(v=vs.110).aspx
Actually whole CallFunction method can be simplified like this:
public void CallFunction(Type type, string methodToCall, params object[] args)
{
// Why this part is so complex? Do I miss something?
//var constructedType = typeof (MethodCaller<>).MakeGenericType(type);
//dynamic target = Activator.CreateInstance(constructedType);
var target = Activator.CreateInstance(type);
var result = type.InvokeMember(method_name, System.Reflection.BindingFlags.InvokeMethod, null, target, args);
// ... do something with result if you need ...
}
If you need MethodCaller.Do, but can sacrifice types on signature (or some performance on boxing/unboxing for DoTyped)
public void CallFunction(Type type, string methodToCall, params object[] args)
{
var delegate_wrapper = new Func<object, object>(
instance => type.InvokeMember(methodToCall, BindingFlags.InvokeMethod, null, instance, args)
);
var target_method = type.GetMethod(methodToCall);
var mc_custom_type = typeof (MethodCaller<>).MakeGenericType(type);
var mc_instance = Activator.CreateInstance(mc_custom_type);
var mc_custom_method = mc_custom_type.GetMethod("Do").MakeGenericMethod(target_method.ReturnType);
mc_custom_method.Invoke(mc_instance, new object[] { delegate_wrapper });
}
public class MethodCaller<TParm> where TParm : new()
{
public TResult DoTyped<TResult>(Func<TParm, TResult> func)
{
return Do<TResult>(oinstance=>func((TParm)oinstance));
}
public TResult Do<TResult>(Func<object, object> func)
{
Console.WriteLine("I AM DO");
return (TResult)func(new TParm());
}
}
Have you tried looking at Impromptu framework. It is primarily for duck typing but the library provide rather slick api to access methods and pass arguments.
https://github.com/ekonbenefits/impromptu-interface/wiki/UsageReallyLateBinding

Code Emit and Expressions

I am using Code Emit for dynamic code generation.
I would like to set a field using an external factory method.
Here is my (reduced) code:
Defines:
Func<object> fact = () => new B();
var mi = fact.GetMethodInfo();
var t = typeof(B);
Emit code:
ILGenerator ilg;
var tb = _mb.DefineType("myProxy", TypeAttributes.Public | TypeAttributes.Class, typeof(object));
var fieldBuilder = tb.DefineField("proxy", t, FieldAttributes.Private);
var ctorBuilder = tb.DefineConstructor(...);
ilg = ctorBuilder.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Callvirt, mi);
ilg.Emit(OpCodes.Castclass, t);
ilg.Emit(OpCodes.Stfld, fieldBuilder);
ilg.Emit(OpCodes.Ret);
Create an instace:
Activator.CreateInstance(tb.CreateType());
TargetInvocationException is thrown
{"Method not found: \"?\"."}
Here is what I am looking forward to generate:
public class A
{
private B _proxy;
public A(Func<object> factory)
{
_proxy = (B)factory();
}
}
BUT the factory Method is fixed and not provided as parameter...
public class A
{
private B _proxy;
public A()
{
_proxy = (B) //[GENERATE ME] () => new B();
}
}
Any Suggestions?
You have to invoke delegate via "Invoke" method but you need to give factory delegate to your proxy. You can add a parameter to your proxy constructor.
public class B
{
}
static internal class Metadata<T> //Avoid lock & string metadata description
{
static public readonly Type Type = typeof(T);
static public FieldInfo Field<X>(Expression<Func<T, X>> expression)
{
return (expression.Body as MemberExpression).Member as FieldInfo;
}
static public PropertyInfo Property<X>(Expression<Func<T, X>> expression)
{
return (expression.Body as MemberExpression).Member as PropertyInfo;
}
static public MethodInfo Method(Expression<Action<T>> expression)
{
return (expression.Body as MethodCallExpression).Method;
}
static public MethodInfo Method<X>(Expression<Func<T, X>> expression)
{
return (expression.Body as MethodCallExpression).Method;
}
}
class Program
{
static void Main(string[] args)
{
var _Factory = new Func<object>(() => new B());
TypeBuilder _TypeBuilder = null;// = ...;
var _Parameters = new Type[] { Metadata<Func<object>>.Type };
var _Constructor = _TypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, _Parameters);
var _Body = _Constructor.GetILGenerator();
//...
_Body.Emit(OpCodes.Ldarg_1);
_Body.Emit(OpCodes.Call, Metadata<Func<object>>.Method(_Func => _Func.Invoke()));
//...
var _Type = _TypeBuilder.CreateType();
var _Parameter = Expression.Parameter(Metadata<Func<object>>.Type);
var _New = Expression.Lambda<Func<Func<object>, object>>(Expression.New(_Type.GetConstructor(_Parameters), _Parameter), _Parameter).Compile();
var _Instance = _New(_Factory);
}
}

How to know when any method is called in my application code?

Just for fun, I want to write an aspect such as say logging, tracing or instrumentation/profiling. But I don't want to use any of the available AOP frameworks already available.
I've used PostSharp in the past and now that ASP.NET MVC introduces action filters, which are very similar to aspect/advise injection, and .NET 4 has CodeContracts, which are also very similar to aspects, I have a pretty good idea of what I want my aspect API to look like.
The only thing I haven't figured out yet, and I believe that it is central to building an AOP library, is how to know when a method is being invoked?
What, do I keep watching the callstack? Do I look up the main UI thread and its synchronization context to see if it has been assigned some work, i.e. been given a method to enter into? What is the way to know if a method is going to be called?
There are two ways to know if a method is going to be called.
You can inherit from ContextBoundObject but you lose the only chance of base class. You can check this
You can inherit your class and override your methods. New methods can call a interceptor before calling base method. Fortunately, this derived class can be constructed in run time. Actually, this is what Castle's DynamicProxy does. In detail you build a type that inherits your class to be intercepted in run time and instantiate this derived class. You Emit IL code into methods of newly generated class.
I do not know if pasting long codes are allowed but here is a little version of DynamicProxy that I wrote. The only library it depends on is System. You can use it like this.
// typeof obj: public class TestClassProxy : TestClass, IInterface1, IIterface2
var obj = Proxy.Of<TestClass>(new CallHandler(), typeof(IInterface1), typeof(IInterface2));
obj.MethodVoid();
Console.WriteLine(obj.PublicSquare(3));
Console.WriteLine(obj.MethodString());
A handler method is triggered:
Before calling a method (BeforeMethodCall)
After calling a method (AfterMethodCall)
If an exception occured in method (OnError)
All these methods accepts the parameters, object that has the method, MethodInfo of the current method and aguments passed to method. Addtionally AfterMethodCall takes return value and OnError takes the exception that has thrown.
Here is the magic Proxy class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace emit
{
public class Proxy
{
#region static
private static readonly AssemblyBuilder AssemblyBuilder;
private static readonly ModuleBuilder ModuleBuilder;
private static readonly object LockObj = new Object();
private static readonly Dictionary<string, Type> TypeCache = new Dictionary<string, Type>();
static Proxy()
{
lock (LockObj)
{
AssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("Taga.Proxies"),
AssemblyBuilderAccess.Run);
var assemblyName = AssemblyBuilder.GetName().Name;
ModuleBuilder = AssemblyBuilder.DefineDynamicModule(assemblyName);
}
}
private static Type GetImplementedType(Type baseType, Type[] interfaceTypes)
{
var key = GetTypeKey(baseType, interfaceTypes);
return TypeCache.ContainsKey(key) ? TypeCache[key] : null;
}
private static void AddImplementation(Type baseType, Type[] interfaceTypes, Type implementationType)
{
var key = GetTypeKey(baseType, interfaceTypes);
TypeCache.Add(key, implementationType);
}
private static string GetTypeKey(Type baseType, Type[] interfaceTypes)
{
var key = String.Empty;
key += baseType.FullName;
key = interfaceTypes.Aggregate(key, (current, interfaceType) => current + interfaceType);
return key;
}
public static TBase Of<TBase>(ICallHandler callHandler, params Type[] interfaceTypes) where TBase : class
{
var builder = new Proxy(typeof(TBase), interfaceTypes);
var type = builder.GetProxyType();
return (TBase)Activator.CreateInstance(type, callHandler);
}
public static object Of(ICallHandler callHandler, Type[] interfaceTypes)
{
if (interfaceTypes == null || interfaceTypes.Length == 0)
throw new InvalidOperationException("No interface type specified");
return Of<object>(callHandler, interfaceTypes);
}
#endregion
#region Proxy
private TypeBuilder _typeBuilder;
private FieldBuilder _callHandlerFieldBuilder;
private readonly Type _baseClassType;
private readonly Type[] _interfaceTypes;
private Proxy(Type baseClassType, Type[] interfaceTypes)
{
if (interfaceTypes == null || !interfaceTypes.Any())
_interfaceTypes = Type.EmptyTypes;
else if (interfaceTypes.Any(it => !it.IsInterface || !it.IsPublic || it.IsGenericType))
throw new InvalidOperationException("Interface Types must be public and non generic");
else
_interfaceTypes = interfaceTypes;
if (baseClassType == null)
_baseClassType = typeof(object);
else if (!baseClassType.IsClass || baseClassType.IsAbstract || baseClassType.IsGenericType || baseClassType.IsSealed || !baseClassType.IsPublic || !baseClassType.HasDefaultConstructor())
throw new InvalidOperationException("Base Class Type must be a public, non-sealed, non-abstract, non-generic class with a public default constructor");
else
_baseClassType = baseClassType;
}
private string _typeName;
private string TypeName
{
get { return _typeName ?? (_typeName = BuildTypeName()); }
}
private string BuildTypeName()
{
var typeName = "__";
if (_baseClassType != null)
typeName += _baseClassType.Name + "__";
foreach (var interfaceType in _interfaceTypes)
typeName += interfaceType.Name + "__";
return typeName + "Proxy__";
}
private Type GetProxyType()
{
var type = GetImplementedType(_baseClassType, _interfaceTypes);
if (type != null)
return type;
type = BuildType();
AddImplementation(_baseClassType, _interfaceTypes, type);
return type;
}
private Type BuildType()
{
InitTypeBuilder();
DefineCallHandlerField();
BuildConstructor();
ExtendBase();
ImplementInterfaces();
return _typeBuilder.CreateType();
}
private void InitTypeBuilder()
{
// public class __BaseClass__Interface1__Interface2__Proxy__ : BaseClass, Interface1, Interface2
_typeBuilder = ModuleBuilder.DefineType(
TypeName,
TypeAttributes.Public | TypeAttributes.Class,
_baseClassType,
_interfaceTypes);
}
private void DefineCallHandlerField()
{
// private ICallHandler _callHandler;
_callHandlerFieldBuilder = _typeBuilder.DefineField("_callHandler", typeof(ICallHandler), FieldAttributes.Private);
}
private void BuildConstructor()
{
var constructorBuilder = DeclareContsructor(); // public ProxyClass(ICallHandler callHandler)
ImplementConstructor(constructorBuilder); // : base() { this._callHandler = callHandler; }
}
private void ExtendBase()
{
foreach (var mi in _baseClassType.GetVirtualMethods())
BuildMethod(mi);
}
private void ImplementInterfaces()
{
foreach (var methodInfo in _interfaceTypes.SelectMany(interfaceType => interfaceType.GetMethods()))
BuildMethod(methodInfo);
}
private ConstructorBuilder DeclareContsructor()
{
var constructorBuilder = _typeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.HasThis,
new[] { typeof(ICallHandler) });
return constructorBuilder;
}
private void ImplementConstructor(ConstructorBuilder constructorBuilder)
{
var baseCtor = _baseClassType.GetConstructor(Type.EmptyTypes);
var il = constructorBuilder.GetILGenerator();
// call base ctor
il.Emit(OpCodes.Ldarg_0); // push this
il.Emit(OpCodes.Call, baseCtor); // Call base constructor this.base(); pops this
// set _callHandler
il.Emit(OpCodes.Ldarg_0); // push this
il.Emit(OpCodes.Ldarg_1); // push callHandler argument
il.Emit(OpCodes.Stfld, _callHandlerFieldBuilder); // this._callHandler = callHandler, pop this, pop callhandler argument
il.Emit(OpCodes.Ret); // exit ctor
}
private void BuildMethod(MethodInfo mi)
{
var methodBuilder = CallHandlerMethodBuilder.GetInstance(_typeBuilder, mi, _callHandlerFieldBuilder);
methodBuilder.Build();
}
#endregion
}
class CallHandlerMethodImplementor : CallHandlerMethodBuilder
{
internal CallHandlerMethodImplementor(TypeBuilder typeBuilder, MethodInfo methodInfo, FieldBuilder callHandlerFieldBuilder)
: base(typeBuilder, methodInfo, callHandlerFieldBuilder)
{
}
protected override void SetReturnValue()
{
// object res = returnValue;
ReturnValue = IL.DeclareLocal(typeof(object));
if (MethodInfo.ReturnType != typeof(void))
IL.Emit(OpCodes.Stloc, ReturnValue); // pop return value of BeforeCall into res
else
IL.Emit(OpCodes.Pop); // pop return value of BeforeCall
}
}
class CallHandlerMethodOverrider : CallHandlerMethodBuilder
{
internal CallHandlerMethodOverrider(TypeBuilder typeBuilder, MethodInfo methodInfo, FieldBuilder callHandlerFieldBuilder)
: base(typeBuilder, methodInfo, callHandlerFieldBuilder)
{
}
protected override void SetReturnValue()
{
// ReturnValue = base.Method(args...)
CallBaseMethod();
// stack'ta base'den dönen değer var
SetReturnValueFromBase();
}
private void CallBaseMethod()
{
IL.Emit(OpCodes.Pop); // pop return value of BeforeCall
// base'den Method'u çağır
// returnValue = base.Method(params...)
IL.Emit(OpCodes.Ldarg_0); // push this
for (var i = 0; i < ParameterCount; i++) // metoda gelen parametreleri stack'e at
IL.Emit(OpCodes.Ldarg_S, i + 1);// push params[i]
IL.Emit(OpCodes.Call, MethodInfo); // base.Method(params) pop this, pop params push return value
}
private void SetReturnValueFromBase()
{
ReturnValue = IL.DeclareLocal(typeof(object));
if (MethodInfo.ReturnType == typeof(void))
return;
// unbox returnValue if required
if (MethodInfo.ReturnType.IsValueType)
IL.Emit(OpCodes.Box, MethodInfo.ReturnType);
IL.Emit(OpCodes.Stloc, ReturnValue); // pop return value into res
}
}
abstract class CallHandlerMethodBuilder
{
private ParameterInfo[] _parameters;
private MethodBuilder _methodBuilder;
private readonly TypeBuilder _typeBuilder;
private readonly FieldBuilder _callHandlerFieldBuilder;
protected readonly MethodInfo MethodInfo;
protected ILGenerator IL { get; private set; }
protected int ParameterCount { get; private set; }
private MethodInfo _beforeCall;
private MethodInfo BeforeCall
{
get
{
return _beforeCall ?? (_beforeCall = typeof(ICallHandler).GetMethods().First(m => m.Name == "BeforeMethodCall"));
}
}
private MethodInfo _afterCall;
private MethodInfo AfterCall
{
get
{
return _afterCall ?? (_afterCall = typeof(ICallHandler).GetMethods().First(m => m.Name == "AfterMethodCall"));
}
}
private MethodInfo _onError;
private MethodInfo OnError
{
get
{
return _onError ?? (_onError = typeof(ICallHandler).GetMethods().First(m => m.Name == "OnError"));
}
}
protected CallHandlerMethodBuilder(TypeBuilder typeBuilder, MethodInfo methodInfo, FieldBuilder callHandlerFieldBuilder)
{
_typeBuilder = typeBuilder;
MethodInfo = methodInfo;
_callHandlerFieldBuilder = callHandlerFieldBuilder;
}
private void Declare()
{
// public override? ReturnType Method(arguments...)
_methodBuilder = _typeBuilder.DefineMethod(MethodInfo.Name,
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual,
MethodInfo.ReturnType,
MethodInfo.GetParameterTypes());
IL = _methodBuilder.GetILGenerator();
_parameters = MethodInfo.GetParameters();
ParameterCount = _parameters.Length;
}
private LocalBuilder _objParameter;
private void SetObjectParameter()
{
// CallHandlera verilecek object obj
_objParameter = IL.DeclareLocal(typeof(object)); // object obj;
IL.Emit(OpCodes.Ldarg_0); // push this
IL.Emit(OpCodes.Stloc, _objParameter); // obj = this; pops this
}
private LocalBuilder _methodInfoParameter;
private void SetMethodInfoParameter()
{
// CallHandlera verilecek MethodInfo methodInfo
_methodInfoParameter = IL.DeclareLocal(typeof(MethodInfo)); // MethodInfo methodInfo;
IL.Emit(OpCodes.Ldtoken, MethodInfo);
IL.Emit(OpCodes.Call, typeof(MethodBase).GetMethod(
"GetMethodFromHandle", new[] { typeof(RuntimeMethodHandle) })); // MethodBase.GetMethodFromHandle(new RuntimeMethodHandle());
IL.Emit(OpCodes.Stloc, _methodInfoParameter);
}
private LocalBuilder _argsParameter;
private void SetArgsParameters()
{
// CallHandlera verilecek object[] args
_argsParameter = IL.DeclareLocal(typeof(object[])); // object[] args;
IL.Emit(OpCodes.Ldc_I4, ParameterCount); // push parameterCount as Int32
IL.Emit(OpCodes.Newarr, typeof(object)); // push new object[parameterCount]; pops parameterCount
IL.Emit(OpCodes.Stloc, _argsParameter); // args = new object[ParameterCount]; pops new object[parameterCount]
// Metoda gelen parametreleri args'a doldur
for (var i = 0; i < ParameterCount; i++)
{
var parameterInfo = _parameters[i];
IL.Emit(OpCodes.Ldloc, _argsParameter); // push args
IL.Emit(OpCodes.Ldc_I4, i); // push i
IL.Emit(OpCodes.Ldarg_S, i + 1); // push params[i]; pops i; metoda gelen parametrelerin i'incisi. 0'ıncı parametre this olduğu için "+1" var
if (parameterInfo.ParameterType.IsPrimitive || parameterInfo.ParameterType.IsValueType)
IL.Emit(OpCodes.Box, parameterInfo.ParameterType); // (object)params[i]
IL.Emit(OpCodes.Stelem_Ref); // args[i] = (object)params[i]; pops params[i]
}
}
private void Try()
{
IL.BeginExceptionBlock(); // try {
}
private void InvokeBeforeMethodCall()
{
// this._callHandler.BeforeCall(obj, methodInfo, args);
IL.Emit(OpCodes.Ldarg_0); // push this
IL.Emit(OpCodes.Ldfld, _callHandlerFieldBuilder); // push _callHandler; pops this
IL.Emit(OpCodes.Ldloc, _objParameter); // push obj
IL.Emit(OpCodes.Ldloc, _methodInfoParameter); // push methodInfo
IL.Emit(OpCodes.Ldloc, _argsParameter); // push args
IL.Emit(OpCodes.Call, BeforeCall); // _callHandler.BeforeCall(obj, methodInfo, args); push return value
}
protected LocalBuilder ReturnValue;
protected abstract void SetReturnValue();
private void InvokeAfterMethodCall()
{
// this._callHandler.AfterCall(obj, methodInfo, args, returnValue);
IL.Emit(OpCodes.Ldarg_0); // push this
IL.Emit(OpCodes.Ldfld, _callHandlerFieldBuilder); // push _callHandler; pops this
IL.Emit(OpCodes.Ldloc, _objParameter); // push obj
IL.Emit(OpCodes.Ldloc, _methodInfoParameter); // push methodInfo
IL.Emit(OpCodes.Ldloc, _argsParameter); // push args
IL.Emit(OpCodes.Ldloc, ReturnValue); // push res
IL.Emit(OpCodes.Call, AfterCall); // _callHandler.AfterCall(obj, methodInfo, args, returnValue); push return value (void değilse)
}
private void Catch()
{
var ex = IL.DeclareLocal(typeof(Exception));
IL.BeginCatchBlock(typeof(Exception)); // catch
IL.Emit(OpCodes.Stloc_S, ex); // (Exception ex) {
InvokeOnError(ex); // _callHandler.AfterCall(obj, methodInfo, args);
IL.EndExceptionBlock(); // }
}
private void InvokeOnError(LocalBuilder exception)
{
// this._callHandler.OnError(obj, methodInfo, args);
IL.Emit(OpCodes.Ldarg_0); // push this
IL.Emit(OpCodes.Ldfld, _callHandlerFieldBuilder); // push _callHandler; pops this
IL.Emit(OpCodes.Ldloc, _objParameter); // push obj
IL.Emit(OpCodes.Ldloc, _methodInfoParameter); // push methodInfo
IL.Emit(OpCodes.Ldloc, _argsParameter); // push args
IL.Emit(OpCodes.Ldloc, exception); // push ex
IL.Emit(OpCodes.Call, OnError); // _callHandler.AfterCall(obj, methodInfo, args);
}
private void Return()
{
if (MethodInfo.ReturnType != typeof(void))
{
IL.Emit(OpCodes.Ldloc, ReturnValue); // push returnValue
IL.Emit(OpCodes.Unbox_Any, MethodInfo.ReturnType); // (ReturnType)returnValue
}
IL.Emit(OpCodes.Ret); // returns the value on the stack, if ReturnType is void stack should be empty
}
internal void Build()
{
Declare(); // public override? ReturnType Method(arguments...) {
SetObjectParameter(); // object obj = this;
SetMethodInfoParameter(); // MethodInfo methodInfo = MethodBase.GetMethodFromHandle(new RuntimeMethodHandle());
SetArgsParameters(); // object[] args = arguments;
Try(); // try {
InvokeBeforeMethodCall(); // object returnValue = _callHandler.BeforeMethodCall(obj, methodInfo, args);
SetReturnValue(); // !IsAbstract => returnValue = (object)base.Method(arguments);
InvokeAfterMethodCall(); // _callHandler.AfterMethodCall(obj, methodInfo, args, returnValue);
Catch(); // } catch (Exception ex) { _callHandler.OnError(obj, methodInfo, args, ex); }
Return(); // IsVoid ? (return;) : return (ReturnType)returnValue; }
}
internal static CallHandlerMethodBuilder GetInstance(TypeBuilder typeBuilder, MethodInfo methodInfo, FieldBuilder callHandlerFieldBuilder)
{
if (methodInfo.IsAbstract)
return new CallHandlerMethodImplementor(typeBuilder, methodInfo, callHandlerFieldBuilder);
return new CallHandlerMethodOverrider(typeBuilder, methodInfo, callHandlerFieldBuilder);
}
}
public interface ICallHandler
{
object BeforeMethodCall (object obj, MethodInfo mi, object[] args);
void AfterMethodCall (object obj, MethodInfo mi, object[] args, object returnValue);
void OnError (object obj, MethodInfo mi, object[] args, Exception exception);
}
static class ReflectionExtensions
{
public static bool HasDefaultConstructor(this Type type)
{
return type.GetConstructors(BindingFlags.Public | BindingFlags.Instance).Any(ctor => !ctor.GetParameters().Any());
}
public static Type[] GetParameterTypes(this MethodInfo methodInfo)
{
return methodInfo.GetParameters().Select(pi => pi.ParameterType).ToArray();
}
public static MethodBuilder GetMethodBuilder(this TypeBuilder typeBuilder, MethodInfo mi)
{
// MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual
return typeBuilder.DefineMethod(mi.Name, mi.Attributes, mi.ReturnType, mi.GetParameterTypes());
}
public static MethodInfo[] GetVirtualMethods(this Type type)
{
return type.GetMethods().Where(mi => mi.IsVirtual).ToArray();
}
public static object GetDefaultValue(this Type t)
{
return typeof(ReflectionExtensions).GetMethod("Default").MakeGenericMethod(t).Invoke(null, null);
}
public static T Default<T>()
{
return default(T);
}
}
}
And here is the test code
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Threading;
namespace emit
{
public class Program
{
private static void Main()
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");
try
{
TestProxy();
Console.WriteLine("OK");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
private static void TestProxy()
{
var obj = Proxy.Of<TestClass>(new CallHandler(), typeof(IInterface1), typeof(IInterface2));
obj.MethodVoid();
Console.WriteLine();
Console.WriteLine(obj.PublicSquare(3));
Console.WriteLine();
Console.WriteLine(obj.MethodString());
Console.WriteLine();
Console.WriteLine(obj.MethodInt());
Console.WriteLine();
Console.WriteLine(obj.MethodComplex(45, " Deneme ", new Ogrenci { Name = "Ali" }).Name);
Console.WriteLine();
obj.PropInt = 78;
Console.WriteLine();
Console.WriteLine(obj.PropInt);
Console.WriteLine();
var int1 = obj as IInterface1;
int1.Name = "Interface";
Console.WriteLine();
Console.WriteLine("Got: " + int1.Name);
Console.WriteLine();
int1.Name = "Interface333";
Console.WriteLine();
Console.WriteLine("Got3: " + int1.Name);
Console.WriteLine();
Console.WriteLine(int1.MethodString(34, "Par", new Ogrenci { Name = "Veli" }));
var int2 = obj as IInterface2;
int2.Value = 14;
Console.WriteLine();
Console.WriteLine("Got: " + int2.Value);
Console.WriteLine();
int2.Value = 333;
Console.WriteLine();
Console.WriteLine("Got3: " + int2.Value);
Console.WriteLine();
Console.WriteLine(int2.MethodInt(34, "Par", new Ogrenci { Name = "Veli" }));
Console.WriteLine();
obj.ThrowException();
}
}
public class CallHandler : ICallHandler
{
private readonly SortedDictionary<string, object> _propertyValues = new SortedDictionary<string, object>();
public object BeforeMethodCall(object obj, MethodInfo mi, object[] args)
{
WriteParameterInfo(mi, args);
return SetReturnValue(mi, args);
}
public void AfterMethodCall(object obj, MethodInfo mi, object[] args, object returnValue)
{
if (mi.ReturnType == typeof(void))
Console.WriteLine(mi.Name + " returns [void]");
else
Console.WriteLine(mi.Name + " returns [" + (returnValue ?? "null") + "]");
}
public void OnError(object obj, MethodInfo mi, object[] args, Exception exception)
{
Console.WriteLine("Exception Handled: " + exception.Message);
throw new ApplicationException(exception.Message, exception);
}
private object SetReturnValue(MethodInfo mi, object[] args)
{
object res = null;
if (mi.Name.StartsWith("get_"))
{
var propName = mi.Name.Replace("get_", "");
if (_propertyValues.ContainsKey(propName))
res = _propertyValues[propName];
}
else if (mi.Name.StartsWith("set_"))
{
var propName = mi.Name.Replace("set_", "");
if (!_propertyValues.ContainsKey(propName))
_propertyValues.Add(propName, args[0]);
else
_propertyValues[propName] = args[0];
}
else if (mi.IsAbstract && mi.ReturnType != typeof(void))
{
res = mi.ReturnType.GetDefaultValue();
var methodName = mi.Name;
if (!_propertyValues.ContainsKey(methodName))
_propertyValues.Add(methodName, res);
else
_propertyValues[methodName] = res;
}
if (mi.ReturnType == typeof(void))
Console.WriteLine(mi.Name + " should return [void]");
else
Console.WriteLine(mi.Name + " should return [" + res + "]");
return res;
}
private void WriteParameterInfo(MethodInfo mi, object[] args)
{
Console.Write(mi.Name + " takes ");
if (args.Length == 0)
{
Console.WriteLine("no parameter");
}
else
{
Console.WriteLine("{0} parameter(s)", args.Length);
var paramInfos = mi.GetParameters();
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("\t[{0} {1}: '{2}']", paramInfos[i].ParameterType.Name, paramInfos[i].Name, args[i]);
}
}
}
}
public interface IInterface1
{
string Name { get; set; }
string MethodString(int i, string s, object o);
}
public interface IInterface2
{
int Value { get; set; }
int MethodInt(int i, string s, Ogrenci o);
}
public class TestClass
{
public virtual int PropInt { get; set; }
public virtual void ThrowException()
{
throw new Exception("Custom Error");
}
protected virtual double ProtectedSquare(int x)
{
Console.WriteLine("Executing Method ProtectedSquare");
return x * x;
}
public virtual double PublicSquare(int x)
{
Console.WriteLine("Executing Method PublicSquare");
return ProtectedSquare(x);
}
public virtual string MethodString()
{
Console.WriteLine("Executing String Method");
return "Hele";
}
public virtual int MethodInt()
{
Console.WriteLine("Executing Int Method");
return 985;
}
public virtual void MethodVoid()
{
Console.WriteLine("Executing Void Method");
}
public virtual Ogrenci MethodComplex(int x, string f, Ogrenci o)
{
Console.WriteLine("Executing Parameter Method");
return new Ogrenci { Name = o.Name + x + f };
}
}
public class Ogrenci
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
}
Put a breakpoint and the method that you want to see if it's getting called
If just placing a breakpoint every time does not suffice:
As you said, watch the Call Stack. Just place a breakpoint when you see fit.
In Visual Studio it's pretty easy.. just run the program and when you want a breakpoint, set it in the middle of debugging in a line you know that's about to happen.
Third option is to call Console.WriteLineMSDN even if it's not a console application.
You'll see the result in the Output Window (Ctrl + W, O) instead.
You can also use System.Diagnostics.TraceMSDN for writing in the Output window.
Above tricks are also good,
You can also put alert box of JavaScript in your method. so you will know that the method called.
If you want to maintain the log you can have log table in your database and put the insert query with the system time in log time column in your log table. so by this you will now when in past your method called.

CreateDelegate instead of Reflection for SetValue

I tried to implement Jon Skeet's solution for this question posted on this blog post to substitute the SetValue method with a non-reflection method using delegates.
The difference from the solution in the blog post is that SetValue is void, and I get the The type 'System.Void' may not be used as a type argument. exception at the line MethodInfo miConstructedHelper = miGenericHelper.MakeGenericMethod(typeof(G), pMethod.GetParameters()[0].ParameterType, pMethod.ReturnType);.
Here's my implementation of the MagicMethod:
public class Instantiator<T> where T : new()
{
private T instance;
private IDictionary<string, PropertyInfo> properties;
private Func<PropertyInfo, object, object> _fncSetValue;
public Instantiator()
{
Type type = typeof(T);
properties = type.GetProperties().GroupBy(p => p.Name).ToDictionary(g => g.Key, g => g.ToList().First());
MethodInfo miSetValue = typeof(PropertyInfo).GetMethod("SetValue", new Type[] { typeof(object), typeof(object), typeof(object[]) });
_fncSetValue = SetValueMethod<PropertyInfo>(miSetValue);
}
public void CreateNewInstance()
{
instance = new T();
}
public void SetValue(string pPropertyName, object pValue)
{
if (pPropertyName == null) return;
PropertyInfo property;
if (!properties.TryGetValue(pPropertyName, out property)) return;
TypeConverter tc = TypeDescriptor.GetConverter(property.PropertyType);
//substitute this line
//property.SetValue(instance, tc.ConvertTo(pValue, property.PropertyType), null);
//with this line
_fncSetValue(property, new object[] { instance, tc.ConvertTo(pValue, property.PropertyType), null });
}
public T GetInstance()
{
return instance;
}
private static Func<G, object, object> SetValueMethod<G>(MethodInfo pMethod) where G : class
{
MethodInfo miGenericHelper = typeof(Instantiator<T>).GetMethod("SetValueMethodHelper", BindingFlags.Static | BindingFlags.NonPublic);
MethodInfo miConstructedHelper = miGenericHelper.MakeGenericMethod(typeof(G), pMethod.GetParameters()[0].ParameterType, pMethod.ReturnType);
object retVal = miConstructedHelper.Invoke(null, new object[] { pMethod });
return (Func<G, object, object>) retVal;
}
private static Func<TTarget, object, object> SetValueMethodHelper<TTarget, TParam, TReturn>(MethodInfo pMethod) where TTarget : class
{
Func<TTarget, TParam, TReturn> func = (Func<TTarget, TParam, TReturn>)Delegate.CreateDelegate(typeof(Func<TTarget, TParam, TReturn>), pMethod);
Func<TTarget, object, object> retVal = (TTarget target, object param) => func(target, (TParam) param);
return retVal;
}
}
You are using Func in your code. Func is for methods that have a return type. For methods that return void you need to use Action.
Your code needs to look like this:
public class Instantiator<T> where T : new()
{
private T instance;
private IDictionary<string, PropertyInfo> properties;
private Action<PropertyInfo, object, object, object> _fncSetValue;
public Instantiator()
{
Type type = typeof(T);
properties = type.GetProperties()
.GroupBy(p => p.Name)
.ToDictionary(g => g.Key, g => g.ToList().First());
var types = new Type[] { typeof(object), typeof(object),
typeof(object[]) };
var miSetValue = typeof(PropertyInfo).GetMethod("SetValue", types);
_fncSetValue = SetValueMethod<PropertyInfo>(miSetValue);
}
public void CreateNewInstance()
{
instance = new T();
}
public void SetValue(string pPropertyName, object pValue)
{
if (pPropertyName == null) return;
PropertyInfo property;
if (!properties.TryGetValue(pPropertyName, out property)) return;
TypeConverter tc = TypeDescriptor.GetConverter(property.PropertyType);
var value = tc.ConvertTo(pValue, property.PropertyType);
_fncSetValue(property, instance, value, null);
}
public T GetInstance()
{
return instance;
}
private static Action<G, object, object, object> SetValueMethod<G>(MethodInfo pMethod) where G : class
{
var miGenericHelper =
typeof(Instantiator<T>).GetMethod("SetValueMethodHelper",
BindingFlags.Static |
BindingFlags.NonPublic);
var parameters = pMethod.GetParameters();
var miConstructedHelper = miGenericHelper.MakeGenericMethod(typeof(G),
parameters[0].ParameterType,
parameters[1].ParameterType,
parameters[2].ParameterType);
var retVal = miConstructedHelper.Invoke(null, new object[] { pMethod });
return (Action<G, object, object, object>) retVal;
}
private static Action<TTarget, object, object, object> SetValueMethodHelper<TTarget, TParam1, TParam2, TParam3>(MethodInfo pMethod) where TTarget : class
{
var func = (Action<TTarget, TParam1, TParam2, TParam3>)Delegate.CreateDelegate(typeof(Action<TTarget, TParam1, TParam2, TParam3>), pMethod);
Action<TTarget, object, object, object> retVal =
(target, param1, param2, param3) =>
func(target, (TParam1) param1, (TParam2) param2, (TParam3) param3);
return retVal;
}
}
As you don't want to call arbitrary methods like Jon Skeet, you can simplify your code a lot. There is no need for a call to MethodInfo.Invoke in your code and because of this there is no need for the delegates. You can simply call SetValue directly on the returned PropertyInfo. There is no need to use the detour of a delegate that in turn calls exactly that method anyway. Additionally, the type conversion is not necessary as SetValue requires an object anyway.
Your code could be as simple as this:
public class SimpleInstantiator<T> where T : new()
{
private T instance;
private IDictionary<string, PropertyInfo> properties;
public SimpleInstantiator()
{
Type type = typeof(T);
properties = type.GetProperties()
.GroupBy(p => p.Name)
.ToDictionary(g => g.Key, g => g.ToList().First());
}
public void CreateNewInstance()
{
instance = new T();
}
public void SetValue(string pPropertyName, object pValue)
{
if (pPropertyName == null) return;
PropertyInfo property;
if (!properties.TryGetValue(pPropertyName, out property)) return;
property.SetValue(instance, pValue, null);
}
public T GetInstance()
{
return instance;
}
}
Performance tests show that this version takes only about 50% of the previous one.
A tiny increase in performance is due to the fact that we avoid two unnecessary delegates in our call chain. However, the vast majority of the speed improvement lays in the fact that we removed the type conversion.

Why is Ldvirtftn unverifiable?

Can anyone explain when using an anonymously hosted dynamic method why I get an unverifiable exception by ldvirtftn for a public virtual method on a public class? I set the following assembly level attributes as well:
[assembly: SecurityTransparent]
[assembly: SecurityRules(SecurityRuleSet.Level2,SkipVerificationInFullTrust=true)]
Here is the example code:
public class Program
{
public virtual void Foo() {}
public static void Main(string[] args)
{
Action<ILGenerator> genfunc = il => il
.newobj<Program>()
.ldvirtftn(typeof(Program).GetMethod("Foo"))
.ret();
try
{
Console.WriteLine(CodeGen.CreateDelegate<Func<IntPtr>>(genfunc).Invoke());
}
catch (System.Security.VerificationException) { }
Console.WriteLine(CodeGen.CreateDelegate<Func<IntPtr>>(genfunc,owner:typeof(Program)).Invoke());
}
}
If the method is owned, then it does not throw an exception.
Even more curious is that if I change the code like so then both methods compile and run without issue:
public class Program
{
public virtual void Foo() {}
public static void Main(string[] args)
{
Action<ILGenerator> genfunc = il => il
.newobj<Program>()
.dup()
.ldvirtftn(typeof(Program).GetMethod("Foo"))
.newobj<Action>(typeof(object),typeof(IntPtr))
.ret();
try
{
Console.WriteLine(CodeGen.CreateDelegate<Func<Action>>(genfunc).Invoke());
}
catch (System.Security.VerificationException) { }
Console.WriteLine(CodeGen.CreateDelegate<Func<Action>>(genfunc,owner:typeof(Program)).Invoke());
}
}
This code was written with the reflective library.
CodeGen.CreateDelegate simply uses the type parameter to determine the signature of the dynamic method. Here is the method::
public static TDelegate CreateDelegate<TDelegate>(
Action<ILGenerator> genfunc, string name = "", object target = null, Type owner = null, bool skipVisibility = false)
where TDelegate : class
{
var invokeMethod = typeof(TDelegate).GetMethod("Invoke");
var parameters = invokeMethod.GetParameters();
var paramTypes = new Type[parameters.Length + 1];
paramTypes[0] = typeof(object);
parameters.Select(p => p.ParameterType).ToArray().CopyTo(paramTypes, 1);
var method = owner != null ?
new DynamicMethod(name, invokeMethod.ReturnType, paramTypes, owner, skipVisibility) :
new DynamicMethod(name, invokeMethod.ReturnType, paramTypes, skipVisibility);
genfunc(method.GetILGenerator());
return method.CreateDelegate(typeof(TDelegate), target) as TDelegate;
}
Short answer
The code that you're trying to emit is unverifiable, and anonymously hosted dynamic methods can never contain unverifiable IL. Since dynamic methods associated with a type or module can contain unverifiable IL (subject to appropriate security checks), your code is usable from those dynamic methods.
Mode details
Despite MSDN's documentation, the ldvirtftn does not load a native int onto the stack; it loads a method pointer. Just as treating an object reference as a native int is valid but unverifiable, treating a method pointer as a native int is also valid but unverifiable. The easiest way to see this is to create an assembly on disk with the same IL instructions (e.g. by using System.Reflection.Emit or ilasm) and run PEVerify on it.
I believe that the only verifiable uses of method pointers are:
Constructing a delegate using the dup; ldvirtftn; newobj or ldftn; newobj patterns to create a new delegate of a compatible delegate type
Using calli with compatible arguments to make an indirect call through the method pointer
This explains why your other code can be called through an anonymously hosted dynamic method: the delegate creation pattern you are using is one of the few verifiable uses of a method pointer.
ldvirtfn loads a native int onto the stack. I think you need to convert that to IntPtr first before returning.
Strange behaviour (IntPtr != IntPtr):
//work normal
public static void F_Ldvirtftn_Action()
{
Action<ILGenerator> genfunc = il =>
{
il.Emit(OpCodes.Newobj, typeof(Program).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Ldvirtftn, typeof(Program).GetMethod("Foo2"));
il.Emit(OpCodes.Newobj, typeof(Action).GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
il.Emit(OpCodes.Ret);
};
Console.WriteLine(CreateDelegate<Func<object>>(genfunc).Invoke());
}
// failed: VerificationException: Operation could destabilize the runtime
public static void F_IntPtr_Action()
{
Action<ILGenerator> genfunc = il =>
{
il.Emit(OpCodes.Newobj, typeof(Program).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Call, typeof(Program).GetMethod("Ptr"));
il.Emit(OpCodes.Newobj, typeof(Action).GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
il.Emit(OpCodes.Ret);
};
Console.WriteLine(CreateDelegate<Func<object>>(genfunc).Invoke());
}
// failed: VerificationException: Operation could destabilize the runtime
public static void F_Ldvirtftn_MyAction()
{
Action<ILGenerator> genfunc = il =>
{
il.Emit(OpCodes.Newobj, typeof(Program).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Ldvirtftn, typeof(Program).GetMethod("Foo2"));
il.Emit(OpCodes.Newobj, typeof(MyAction).GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
il.Emit(OpCodes.Ret);
};
Console.WriteLine(CreateDelegate<Func<object>>(genfunc).Invoke());
}
//work normal
public static void F_IntPtr_MyAction()
{
Action<ILGenerator> genfunc = il =>
{
il.Emit(OpCodes.Newobj, typeof(Program).GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Call, typeof(Program).GetMethod("Ptr"));
il.Emit(OpCodes.Newobj, typeof(MyAction).GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
il.Emit(OpCodes.Ret);
};
Console.WriteLine(CreateDelegate<Func<object>>(genfunc).Invoke());
}
public static IntPtr Ptr(object z)
{
return IntPtr.Zero;
}
public class MyAction
{
public MyAction(object z, IntPtr adr) { }
}

Categories

Resources