Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        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" }));
        }
Ejemplo n.º 3
0
        public void PassNullableArguments()
        {
            IDynamicMethod dm = DynamicMethod.Create(typeof(TestMethods).GetMethod("PassNullableArgumentStatic"));
            DateTime       dt = DateTime.Now;

            Assert.AreEqual(dt, dm.Invoke(null, dt));
        }
Ejemplo n.º 4
0
        private void CanCreateWithRestrictedPermissionsImpl()
        {
            MethodInfo     method = this.GetType().GetMethod("RespectsPermissionsPublicMethod");
            IDynamicMethod m      = DynamicMethod.Create(method);

            m.Invoke(this, null);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Invokes dynamic method.
 /// </summary>
 /// <param name="target">
 /// Target object to invoke method on.
 /// </param>
 /// <param name="arguments">
 /// Method arguments.
 /// </param>
 /// <returns>
 /// A method return value.
 /// </returns>
 public object Invoke(object target, object[] arguments)
 {
     if (isOptimized)
     {
         // try dynamic method first but fall back to standard reflection
         // if arguments are causing InvalidCastExceptions
         try
         {
             return(dynamicMethod.Invoke(target, arguments));
         }
         catch (InvalidCastException e)
         {
             // Only attempt if DynamicReflection code itself threw the exception.
             if (!ExceptionFromDynamicReflection(e))
             {
                 throw;
             }
             isOptimized = false;
             return(methodInfo.Invoke(target, arguments));
         }
     }
     else
     {
         return(methodInfo.Invoke(target, arguments));
     }
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 7
0
        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);
        }
Ejemplo n.º 8
0
        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) { }
        }
Ejemplo n.º 9
0
            /// <summary>
            /// Call the methods
            /// </summary>
            /// <param name="args">Method arguments</param>
            /// <returns>Method return</returns>
            public object[] Invoke(params object[] args)
            {
                Func <object[], string> getArgumentsString = values => string.Join(", ", values.Select(p => p.ToString()).ToArray());

                Logger.InfoFormat("Calling method '{0}' with arguments: {1}", _deployPath, getArgumentsString(args));
                var retval = _dynamicMethod.Invoke(_deployPath, args);

                Logger.InfoFormat("{0} returned from method '{1}' with arguments: {2}", getArgumentsString(retval), _deployPath, getArgumentsString(args));
                return(retval);
            }
Ejemplo n.º 10
0
        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)
            { }
        }
Ejemplo n.º 11
0
        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]);
        }
Ejemplo n.º 12
0
        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)
            { }
        }
Ejemplo n.º 13
0
        //[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);
        }
Ejemplo n.º 14
0
 private ControlCollection CreateControlCollectionInternal(Control target)
 {
     return (ControlCollection) _method.Invoke(target, null);
 }
Ejemplo n.º 15
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();
        }