public void TestRefOutMethods()
        {
            IDynamicMethod refMethod = DynamicMethod.Create(typeof(MethodTarget).GetMethod("MethodWithRefParameter"));

            MethodTarget target = new MethodTarget();

            object[] args = new object[] { "aleks", 5 };
            refMethod.Invoke(target, args);
            Assert.AreEqual("ALEKS", args[0]);
            Assert.AreEqual(25, args[1]);

            IDynamicMethod outMethod = DynamicMethod.Create(typeof(MethodTarget).GetMethod("MethodWithOutParameter"));

            args = new object[] { "aleks", null };
            outMethod.Invoke(target, args);
            Assert.AreEqual("ALEKS", args[1]);

            IDynamicMethod   refOutMethod = DynamicMethod.Create(typeof(RefOutTestObject).GetMethod("DoIt"));
            RefOutTestObject refOutTarget = new RefOutTestObject();

            args = new object[] { 0, 1, null };
            refOutMethod.Invoke(refOutTarget, args);
            Assert.AreEqual(2, args[1]);
            Assert.AreEqual("done", args[2]);
            refOutMethod.Invoke(refOutTarget, args);
            Assert.AreEqual(3, args[1]);
            Assert.AreEqual("done", args[2]);

            int    count = 0;
            string done;

            target.DoItCaller(0, ref count, out done);
            Assert.AreEqual(1, count);
            Assert.AreEqual("done", done);
        }
        public void PassNullableArguments()
        {
            IDynamicMethod dm = DynamicMethod.Create(typeof(TestMethods).GetMethod("PassNullableArgumentStatic"));
            DateTime       dt = DateTime.Now;

            Assert.AreEqual(dt, dm.Invoke(null, dt));
        }
Exemple #3
0
        public ClassDecl CreateClass(JSValue nsValue, string typename, Type type, IDynamicMethod dynamicMethod)
        {
            var       nameAtom = GetAtom(typename);
            JSContext ctx      = _context;
            var       protoVal = JSApi.JS_NewObject(ctx);
            var       type_id  = RegisterType(type, protoVal);
            var       ctorVal  = _db.NewDynamicConstructor(nameAtom, dynamicMethod);
            var       decl     = new ClassDecl(this, ctorVal, protoVal, type);

            JSApi.JS_SetConstructor(ctx, ctorVal, protoVal);
            JSApi.JSB_SetBridgeType(ctx, ctorVal, GetAtom(Values.KeyForCSharpTypeID), type_id);
            JSApi.JSB_SetBridgeType(ctx, protoVal, GetAtom(Values.KeyForCSharpTypeID), type_id);
            if (!nsValue.IsNullish())
            {
                JSApi.JS_DefinePropertyValue(ctx, nsValue, nameAtom, ctorVal, JSPropFlags.JS_PROP_ENUMERABLE | JSPropFlags.JS_PROP_CONFIGURABLE);
            }
            else
            {
                JSApi.JS_FreeValue(ctx, ctorVal);
            }
            // Debug.LogFormat("define class {0}: {1}", type, protoVal);
            JSApi.JS_FreeValue(ctx, protoVal);
            _pendingClasses.Add(decl);
            return(decl);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="objectType"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        public static IDynamicMethod GetDynamicMethod(Type objectType, string methodName, params object[] parameters)
        {
            MethodCacheKey key           = MethodCacheKey.Create(objectType, methodName, parameters);
            IDynamicMethod dynamicMethod = null;

            if (!_dynamicMethods.TryGetValue(key, out dynamicMethod))
            {
                lock (_dynamicMethods)
                {
                    if (!_dynamicMethods.TryGetValue(key, out dynamicMethod))
                    {
                        MethodInfo methodInfo = GetMethod(objectType, methodName, parameters);
                        if (methodInfo != null)
                        {
                            dynamicMethod = DynamicMethod.Create(methodInfo);
                            if (dynamicMethod != null)
                            {
                                _dynamicMethods.Add(key, dynamicMethod);
                            }
                        }
                    }
                }
            }

            return(dynamicMethod);
        }
        private void CanCreateWithRestrictedPermissionsImpl()
        {
            MethodInfo     method = this.GetType().GetMethod("RespectsPermissionsPublicMethod");
            IDynamicMethod m      = DynamicMethod.Create(method);

            m.Invoke(this, null);
        }
Exemple #6
0
        /// <summary>
        /// Uses reflection to dynamically invoke a method,
        /// throwing an exception if it is not
        /// implemented on the target object.
        /// </summary>
        /// <param name="obj">
        /// Object containing method.
        /// </param>
        /// <param name="method">
        /// Name of the method.
        /// </param>
        /// <param name="parameters">
        /// Parameters to pass to method.
        /// </param>
        public static object CallMethod(object obj, string method, params object[] parameters)
        {
            Guard.ArgumentNotNull(obj, "obj");
            Guard.ArgumentNotNullOrEmpty(method, "method");

            IDynamicMethod dynamicMethod = DynamicMethodCache.GetDynamicMethod(obj.GetType(), method, parameters);

            if (dynamicMethod == null)
            {
                ThrowHelper.ThrowNotImplementedException(
                    ReflectionSR.MethodNotImplemented, obj.GetType().FullName, method, TypeHelper.GetTypesString(parameters));
            }

            object result = null;

            try
            {
                result = dynamicMethod.Invoke(obj, parameters);
            }
            catch (Exception ex)
            {
                throw new CallMethodException(
                          string.Format(ReflectionSR.Culture, ReflectionSR.MethodCallFailed, obj.GetType().FullName, method), ex);
            }

            return(result);
        }
        public void TestStaticMethods()
        {
            IDynamicMethod isNullOrEmpty = DynamicMethod.Create(typeof(StringUtils).GetMethod("IsNullOrEmpty"));

            Assert.IsTrue((bool)isNullOrEmpty.Invoke(null, new object[] { null }));
            Assert.IsTrue((bool)isNullOrEmpty.Invoke(null, new object[] { String.Empty }));
            Assert.IsFalse((bool)isNullOrEmpty.Invoke(null, new object[] { "Ana Maria" }));
        }
        public void CanAcceptImplicitlyConvertedTypesAsSubstitutesForArguments()
        {
            IDynamicMethod method = DynamicMethod.Create(typeof(TheClassWithMethod).GetMethod("TheMethod"));

            bool ret = (bool)(method.Invoke(new TheClassWithMethod(), new object[] { new TheClassDerivedFromTheArgumentClass() }));

            Assert.IsTrue(ret);
        }
Exemple #9
0
 public MethodCaller(IDynamicMethod dynamicMethod, IDeployPath deployPath, IOperationRetryIgnore operationRetryIgnore, IMethodOverrides methodOverrides, ResourceReference method)
 {
     _method               = method;
     _dynamicMethod        = dynamicMethod;
     _operationRetryIgnore = operationRetryIgnore;
     _deployPath           = (method.RootType == ReferenceRoot.SR) ?
                             deployPath.GetDeployPath(methodOverrides.GetOverride(method)) : deployPath.GetDeployPath(method);
 }
Exemple #10
0
        public void AddMethod(bool bStatic, string name, IDynamicMethod method)
        {
            var nameAtom = _register.GetAtom(name);
            var db       = _register.GetTypeDB();
            var funcVal  = db.NewDynamicMethod(nameAtom, method);

            JSApi.JS_DefinePropertyValue(_context, bStatic ? _ctor : _proto, nameAtom, funcVal, JSPropFlags.DEFAULT);
        }
Exemple #11
0
 /// <summary>
 /// Creates a new instance of the safe method wrapper.
 /// </summary>
 /// <param name="method">Method to wrap.</param>
 public SafeMethod(MethodInfo method)
 {
     this.methodInfo = method;
     if (method.IsPublic &&
         ReflectionUtils.IsTypeVisible(method.DeclaringType, DynamicReflectionManager.ASSEMBLY_NAME))
     {
         this.dynamicMethod = DynamicMethod.Create(method);
         this.isOptimized   = true;
     }
 }
Exemple #12
0
 /// <summary>
 /// Returns dynamic method if one exists.
 /// </summary>
 /// <param name="method">Method to look up.</param>
 /// <param name="createCallback">callback function that will be called to create the dynamic method</param>
 /// <returns>An <see cref="IDynamicMethod"/> for the given method.</returns>
 internal static IDynamicMethod GetDynamicMethod(MethodInfo method, CreateMethodCallback createCallback)
 {
     lock (methodCache.SyncRoot)
     {
         IDynamicMethod dynamicMethod = (IDynamicMethod)methodCache[method];
         if (dynamicMethod == null)
         {
             dynamicMethod       = createCallback(method);
             methodCache[method] = dynamicMethod;
         }
         return(dynamicMethod);
     }
 }
Exemple #13
0
 public JSValue NewDynamicConstructor(JSAtom name, IDynamicMethod method)
 {
     if (method == null)
     {
         var funValue = JSApi.JSB_NewCFunctionMagic(_context, JSApi.class_private_ctor, name, 0, JSCFunctionEnum.JS_CFUNC_constructor_magic, 0);
         return(funValue);
     }
     else
     {
         var magic    = _dynamicMethods.Count;
         var funValue = JSApi.JSB_NewCFunctionMagic(_context, JSApi._DynamicMethodInvoke, name, 0, JSCFunctionEnum.JS_CFUNC_constructor_magic, magic);
         _dynamicMethods.Add(method);
         return(funValue);
     }
 }
        public void TestInstanceMethods()
        {
            IDynamicMethod getAge = DynamicMethod.Create(typeof(Inventor).GetMethod("GetAge"));

            Assert.AreEqual(tesla.GetAge(DateTime.Today), getAge.Invoke(tesla, new object[] { DateTime.Today }));

            MethodTarget   target = new MethodTarget();
            IDynamicMethod test   = DynamicMethod.Create(typeof(MethodTarget).GetMethod("MethodReturningString"));

            Assert.AreEqual(tesla.Name, test.Invoke(target, new object[] { 5, DateTime.Today, new String[] { "xyz", "abc" }, tesla }));

            ArrayList      list     = new ArrayList(new string[] { "one", "two", "three" });
            IDynamicMethod removeAt = DynamicMethod.Create(typeof(ArrayList).GetMethod("RemoveAt"));

            removeAt.Invoke(list, new object[] { 1 });
            Assert.AreEqual(2, list.Count);
            Assert.AreEqual("three", list[1]);
        }
        public void PassInvalidNumberOfArguments()
        {
            IDynamicMethod dm = DynamicMethod.Create(typeof(TestMethods).GetMethod("PassReferenceArgumentStatic"));
            DateTime       dt = DateTime.Now;

            Assert.IsNull(dm.Invoke(null, null)); // this is ok
            try
            {
                dm.Invoke(null); // this is not ok
                Assert.Fail();
            }
            catch (ArgumentException) { }
            try
            {
                dm.Invoke(null, null, null); // this is not ok
                Assert.Fail();
            }
            catch (ArgumentException) { }
        }
        private void CanCreatePrivateMethodButThrowsOnInvokeImpl()
        {
            MethodInfo     privateMethod = this.GetType().GetMethod("RespectsPermissionsPrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
            IDynamicMethod m             = DynamicMethod.Create(privateMethod);

            try
            {
                object result = m.Invoke(this, null);
                if (SystemUtils.MonoRuntime)
                {
                    Assert.AreEqual("Result", result);
                }
                else
                {
                    Assert.Fail("shoud throw a security exception");
                }
            }
            catch (MethodAccessException)
            { }
        }
        //[Test]
        public void PerformanceTests()
        {
            int    n = 10000000;
            object x = null;

            // tesla.GetAge
            start = DateTime.Now;
            for (int i = 0; i < n; i++)
            {
                x = tesla.GetAge(DateTime.Today);
            }
            stop = DateTime.Now;
            PrintTest("tesla.GetAge (direct)", n, Elapsed);

            start = DateTime.Now;
            IDynamicMethod getAge = DynamicMethod.Create(typeof(Inventor).GetMethod("GetAge"));

            for (int i = 0; i < n; i++)
            {
                object[] args = new object[] { DateTime.Today };
                x = getAge.Invoke(tesla, args);
            }
            stop = DateTime.Now;
            PrintTest("tesla.GetAge (dynamic reflection)", n, Elapsed);

            start = DateTime.Now;
            MethodInfo getAgeMi = typeof(Inventor).GetMethod("GetAge");

            for (int i = 0; i < n; i++)
            {
                object[] args = new object[] { DateTime.Today };
                x = getAgeMi.Invoke(tesla, args);
            }
            stop = DateTime.Now;
            PrintTest("tesla.GetAge (standard reflection)", n, Elapsed);
        }
        public void TestArgumentTypeCasts()
        {
            IDynamicMethod sqrt   = DynamicMethod.Create(typeof(Math).GetMethod("Sqrt"));
            object         result = sqrt.Invoke(null, new object[] { 4 });

            Assert.AreEqual(Math.Sqrt(4), result);

            try
            {
                sqrt.Invoke(null, new object[] { null });
                Assert.Fail();
            }
            catch (InvalidCastException)
            {
            }

            try
            {
                sqrt.Invoke(null, new object[] { "4" });
                Assert.Fail();
            }
            catch (InvalidCastException)
            { }
        }
Exemple #19
0
        static void Main(string[] args)
        {
            IExecutorService executorService = Executors.NewFixedThreadPool(THREAD_POOL_SIZE);

            IFuture <int>    f1 = executorService.Submit <int>(GenerateNumbers);
            IFuture <string> f2 = executorService.Submit <string>(PrintCharacters);
            IFuture <int>    f3 = executorService.Submit <int>(PrintArray);

            Console.WriteLine("Numbers generated till {0}", f1.GetResult());
            Console.WriteLine("Original String {0}", f2.GetResult());
            Console.WriteLine("Array Count {0}", f3.GetResult());


            Console.WriteLine("---------");

            Console.WriteLine("Calculating sums...");

            var futures = new List <IFuture <long> >();

            // Call without method arguments
            for (int i = 0; i < 20000; i++)
            {
                SumNumbers     sumNumbers = new SumNumbers(100 + i);
                IFuture <long> submit     = executorService.Submit <long>(sumNumbers.CalculateSum);
                futures.Add(submit);
            }

            long sum = 0;

            foreach (var future in futures)
            {
                sum += future.GetResult();
            }
            Console.WriteLine("Sum = " + sum);

            futures.Clear();

            Console.WriteLine("---------");

            Console.WriteLine("Calculating sums...");

            // Call with method arguments
            for (int i = 0; i < 20000; i++)
            {
                SumNumbers2    sumNumbers2 = new SumNumbers2();
                int            i1          = i; // copy to local variable for closure.
                IFuture <long> submit      =
                    executorService.Submit(() => sumNumbers2.CalculateSumWithArgsAndReturnValue(100 + i1));
                futures.Add(submit);
            }



            sum = 0;
            foreach (var future in futures)
            {
                sum += future.GetResult();
            }
            Console.WriteLine("Sum = " + sum);


            //Say this was created at runtime and we don't know the type or parameter values at compile time.
            object obj = new SumNumbers2();

            object[] parameters = new object[] { 100 };

            //Find the method we want to invoke
            MethodInfo methodInfo = ReflectionUtils.GetMethod(obj.GetType(),
                                                              "CalculateSumWithArgsAndReturnValue",
                                                              ReflectionUtils.GetTypes(parameters));


            //Use expression trees to generate code to invoke method and assign to a delegate.
            LateBoundMethod methodCallback = DelegateFactory.Create(methodInfo);

            IFuture <object> futureLong = executorService.Submit(() => methodCallback(obj, parameters));
            var result = futureLong.GetResult();

            Console.WriteLine("LateBoundMethod Style : Result = " + result);

            ///Use Spring's IL generation to invoke method dynamically.
            IDynamicMethod method = DynamicMethod.Create(methodInfo);

            IFuture <object> futureLongViaDM = executorService.Submit(() => method.Invoke(obj, parameters));
            var resultViaDM = futureLongViaDM.GetResult();

            Console.WriteLine("Spring's IDynamicMethod Style: Result = " + resultViaDM);


            // This will make the executor accept no new threads
            // and finish all existing threads in the queue
            executorService.Shutdown();


            Console.WriteLine("Hit return to exit");
            Console.ReadLine();
        }
Exemple #20
0
 public void RegisterOperator(Type type, string op, IDynamicMethod func)
 {
     RegisterOperator(type, op, _db.NewDynamicMethod(GetAtom(op), func));
 }
Exemple #21
0
 public void RegisterOperator(Type type, string op, IDynamicMethod func, bool left, Type sideType)
 {
     RegisterOperator(type, op, _db.NewDynamicMethod(GetAtom(op), func), left, sideType);
 }
Exemple #22
0
 public void AddLeftOperator(string op, IDynamicMethod func, Type type)
 {
     _register.RegisterOperator(_type, op, func, true, type);
 }
Exemple #23
0
 public ClassDecl CreateClass(string typename, Type type, IDynamicMethod dynamicMethod)
 {
     return(CreateClass(JSApi.JS_UNDEFINED, typename, type, dynamicMethod));
 }
Exemple #24
0
 public DynamicMethodImpl(MethodInfo methodInfo, IDynamicMethod generatedMethod)
 {
     this.nullArguments = new object[methodInfo.GetParameters().Length];
     this.methodInfo    = methodInfo;
     this.method        = generatedMethod;
 }
 /// <summary>
 /// Creates a new instance of the safe method wrapper.
 /// </summary>
 /// <param name="method">Method to wrap.</param>
 public SafeMethod(MethodInfo method)
 {
     this.methodInfo = method;
     if (method.IsPublic && 
         ReflectionUtils.IsTypeVisible(method.DeclaringType, DynamicReflectionManager.ASSEMBLY_NAME))
     {
         this.dynamicMethod = DynamicMethod.Create(method);
         this.isOptimized = true;
     }
 }
Exemple #26
0
 public void AddRightOperator(string op, IDynamicMethod func, Type type)
 {
     _register.RegisterOperator(_type, op, func, false, type);
 }
 public DynamicMethodImpl(MethodInfo methodInfo, IDynamicMethod generatedMethod)
 {
     this.nullArguments = new object[methodInfo.GetParameters().Length];
     this.methodInfo = methodInfo;
     this.method = generatedMethod;
 }
 public DynamicMethodWrapper(IDynamicMethod method)
 {
     _method = method;
 }
Exemple #29
0
 public void AddSelfOperator(string op, IDynamicMethod func)
 {
     _register.RegisterOperator(_type, op, func);
 }