コード例 #1
1
        public static void CallBundleMethod(this IMvxViewModel viewModel, MethodInfo methodInfo, IMvxBundle bundle)
        {
            var parameters = methodInfo.GetParameters().ToArray();
            if (parameters.Count() == 1
                && parameters[0].ParameterType == typeof(IMvxBundle))
            {
                // this method is the 'normal' interface method
                methodInfo.Invoke(viewModel, new object[] { bundle });
                return;
            }

            if (parameters.Count() == 1
                && !MvxSingletonCache.Instance.Parser.TypeSupported(parameters[0].ParameterType))
            {
                // call method using typed object
                var value = bundle.Read(parameters[0].ParameterType);
                methodInfo.Invoke(viewModel, new[] { value });
                return;
            }

            // call method using named method arguments
            var invokeWith = bundle.CreateArgumentList(parameters, viewModel.GetType().Name)
                                   .ToArray();
            methodInfo.Invoke(viewModel, invokeWith);
        }
コード例 #2
0
        public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action)
        {
            var parameters = action.GetParameters();
            var args = new object[parameters.Length];
            for (var i = 0; i < parameters.Length; i++)
            {
                var key = parameters[i].Name;
                object value;
                if (context.NavigationContext.Request.QueryString.ContainsKey(key))
                    value = context.NavigationContext.Request.QueryString[key];
                else
                    value = context.Controller.RouteData[key];
                args[i] = value;
            }

            // If async
            if (action.ReturnType == typeof(Task<ActionResult>))
            {
                return (Task<ActionResult>)action.Invoke(context.Controller, args);
            }
            // If synchronous
            else
            {
                var actionResult = (ActionResult)action.Invoke(context.Controller, args);
                return Task.FromResult(actionResult);
            }
        }
コード例 #3
0
ファイル: SpeedofMethod.cs プロジェクト: MxAR/SGP
        public SpeedofMethod(MethodInfo Method, object[] Parameter, uint Precision = 1)
        {
            // Boost speed
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            // Warm up
            Method.Invoke(null, Parameter);

            // Clean up the system
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            // test
            Stopwatch SW = new Stopwatch();
            SW.Start();
            for (uint i = 0; i < Precision; i++) { Result = Method.Invoke(null, Parameter); }
            SW.Stop();
            Speed = SW.ElapsedTicks / Precision;

            // Reset speed
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
            Thread.CurrentThread.Priority = ThreadPriority.Normal;
        }
コード例 #4
0
        public ScriptBlock GetScriptsToRun(object testClass, MethodInfo method)
        {
            var loadedScripts = LoadScriptsFromAttributes(method);

            var scriptBlock = ScriptBlock.Empty.WithDefaultScripts()
                .AppendScripts(loadedScripts);

            if (IsStringScriptTest(method))
            {
                var scriptText = (string) method.Invoke(testClass, new object[0]);
                scriptBlock = scriptBlock.AppendInlineScript(scriptText);
            }
            else if (IsScriptBlockTest(method))
            {
                scriptBlock = (ScriptBlock) method.Invoke(testClass, new[] {scriptBlock});
            }
            else
            {
                var scriptFormat = "if (typeof this['{1}'] != 'undefined') {{\r\n" + 
                                   "    {1}();\r\n" +
                                   "}} else {{\r\n" + 
                                   "    {0}();\r\n" + 
                                   "}}";

                var methodNameCamelCase = method.Name.Substring(0, 1).ToLower() + method.Name.Substring(1);

                var invocationScript = string.Format(scriptFormat, method.Name, methodNameCamelCase);

                scriptBlock = scriptBlock.AppendScript(new FileScriptSource(testClass.GetType().Name + ".js"))
                    .AppendScript(new InlineScriptSource("test.js", invocationScript));
            }

            return scriptBlock;
        }
コード例 #5
0
        /// <summary>
        /// Register Request types 
        /// </summary>
        /// <param name="httpConfiguration">HttpConfiguration value</param>
        /// <param name="setSampleRequest">SampleRequest MethodInfo value</param>
        /// <param name="controllerName">ControllerName value</param>
        /// <param name="requestActions">RequestActions value</param>
        internal static void Register(HttpConfiguration httpConfiguration, MethodInfo setSampleRequest, string controllerName, IEnumerable<MethodInfo> requestActions, MethodInfo generateObject)
        {
            try
            {
                JsonMediaTypeFormatter jsonFormatter = null;

                if (httpConfiguration.Formatters != null && httpConfiguration.Formatters.Count > 0)
                {
                    jsonFormatter = httpConfiguration.Formatters.JsonFormatter;
                }

                foreach (var action in requestActions)
                {

                    if (action.GetParameters().Count() > 0) // Make sure request action is a parameterized action
                    {
                        // Documentation output builders
                        IFluentRequestBuilder jsonSampleBuilder = new JSONSampleBuilder(generateObject, jsonFormatter);
                        IFluentRequestBuilder xmlSampleBuilder = new XMLSampleBuilder(generateObject);

                        var actionName = action.Name;
                        var requestCustomAttribs = Attribute.GetCustomAttributes(action);

                        foreach (var parameter in action.GetParameters())
                        {
                            Type type = parameter.ParameterType;
                            string parameterName = parameter.Name;

                            if (requestCustomAttribs != null && requestCustomAttribs.Count() > 0)
                            {
                                // Check if the action is decorated with [RequestTypeAttribute] attribute class and if so grab the type from the attribute
                                var typeQuery = requestCustomAttribs.
                                    Where(rt => rt is RequestTypeAttribute).
                                    Where(p => p.TypeId.ToString().Equals(parameterName));
                                type = (typeQuery != null && typeQuery.Count() > 0) ?
                                    type = ((RequestTypeAttribute)typeQuery.FirstOrDefault()).Type : type;
                            }

                            jsonSampleBuilder = jsonSampleBuilder.BuildSample(type, parameterName);
                            xmlSampleBuilder = xmlSampleBuilder.BuildSample(type, parameterName);
                        }

                        var parameters = action.GetParameters().Select(a => a.Name).ToArray();

                        setSampleRequest.Invoke(null, new object[] { httpConfiguration, jsonSampleBuilder.Sample, new MediaTypeHeaderValue("text/json"), controllerName, actionName, parameters });

                        setSampleRequest.Invoke(null, new object[] { httpConfiguration, jsonSampleBuilder.Sample, new MediaTypeHeaderValue("application/json"), controllerName, actionName, parameters });

                        setSampleRequest.Invoke(null, new object[] { httpConfiguration, xmlSampleBuilder.Sample, new MediaTypeHeaderValue("text/xml"), controllerName, actionName, parameters });

                        setSampleRequest.Invoke(null, new object[] { httpConfiguration, xmlSampleBuilder.Sample, new MediaTypeHeaderValue("application/xml"), controllerName, actionName, parameters });
                    }
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
コード例 #6
0
        private void CreateInvokeDelegate(AphidInteropFunctionAttribute attribute, MethodInfo method)
        {
            var parameters = method.GetParameters();
            var paramsParam = parameters
                .FirstOrDefault(x => x
                    .GetCustomAttributes(true)
                    .Any(y => y is ParamArrayAttribute));

            if (paramsParam == null)
            {
                if (!attribute.PassInterpreter)
                {
                    _invoke = (callerScope, x) => method.Invoke(null, x);
                }
                else
                {
                    _invoke = (callerScope, x) => method.Invoke(null, PrefixScope(callerScope, x));
                }
            }
            else
            {
                var paramCount = parameters.Count();

                if (attribute.PassInterpreter)
                {
                    paramCount--;
                }

                _invoke = (callerScope, x) =>
                {
                    object[] parameters2;
                    if (x.Length < paramCount)
                    {
                        parameters2 = new object[x.Length + 1];
                        Array.Copy(x, parameters2, x.Length);
                        parameters2[x.Length] = new object[0];
                    }
                    else
                    {
                        parameters2 = new object[paramCount];
                        var stdParamCount = paramCount - 1;
                        Array.Copy(x, parameters2, stdParamCount);
                        var paramArrayLen = x.Length - stdParamCount;
                        var paramArray = new object[paramArrayLen];
                        Array.Copy(x, stdParamCount, paramArray, 0, paramArrayLen);
                        parameters2[stdParamCount] = paramArray;
                    }

                    if (attribute.PassInterpreter)
                    {
                        parameters2 = PrefixScope(callerScope, parameters2);
                    }

                    return method.Invoke(null, parameters2);
                };
            }
        }
コード例 #7
0
ファイル: ServiceController.cs プロジェクト: rickxie/MiniAbp
 private object Invoke(MethodInfo method, object instance, object param)
 {
     object result;
     var deSerializedParam = GetMethoParam(method, param);
     if (deSerializedParam == null)
     {
         result = method.Invoke(instance, null);
     }
     else
     {
         result = method.Invoke(instance, new[] { deSerializedParam });
     }
     return result;
 }
コード例 #8
0
            internal InvokeDelegate GenerateInvokeDelegate(MethodInfo method, out int inputParameterCount, out int outputParameterCount)
            {
                ParameterInfo[] parameters = method.GetParameters();
                bool returnsValue = method.ReturnType != typeof (void);
                var inputCount = parameters.Length;
                inputParameterCount = inputCount;

                var outputParamPositions = new List<int>();
                for (int i = 0; i < inputParameterCount; i++)
                {
                    if (parameters[i].ParameterType.IsByRef)
                    {
                        outputParamPositions.Add(i);
                    }
                }

                var outputPos = outputParamPositions.ToArray();
                outputParameterCount = outputPos.Length;

                InvokeDelegate lambda = delegate(object target, object[] inputs, object[] outputs)
                {
                    object[] inputsLocal = null;
                    if (inputCount > 0)
                    {
                        inputsLocal = new object[inputCount];
                        for (var i = 0; i < inputCount; i++)
                        {
                            inputsLocal[i] = inputs[i];
                        }
                    }
                    object result = null;
                    if (returnsValue)
                    {
                        result = method.Invoke(target, inputsLocal);
                    }
                    else
                    {
                        method.Invoke(target, inputsLocal);
                    }
                    for (var i = 0; i < outputPos.Length; i++)
                    {
                        outputs[i] = inputs[outputPos[i]];
                    }

                    return result;
                };

                return lambda;
            }
コード例 #9
0
        public object InvokeTargetsMethod(MethodInfo getTargetsMethod, IParameters parameters) {
            ParameterInfo[] methodParameters = getTargetsMethod.GetParameters();
            if (methodParameters.Length == 1) {
                if (methodParameters[0].ParameterType.IsAssignableFrom(typeof(IParameters)))
                {
                    return getTargetsMethod.Invoke(null, new[] { parameters });
                }
            }

            if (methodParameters.Length == 0) {
                return getTargetsMethod.Invoke(null, new object[0]);
            }

            throw new TargetsMethodWrongSignatureException(getTargetsMethod.Name);
        }
コード例 #10
0
        public override IEnumerable<ITestCase> CreateTests(
            IFixture fixture,
            MethodInfo method)
        {
            if (!typeof(IEnumerable<ITestCase>).IsAssignableFrom(method.ReturnType))
            {
                List<ITestCase> tests = new List<ITestCase>();
                tests.Add(new BadTestCase(
                    fixture.Name,
                    method.Name,
                    "A method tagged with DynamicTest must return IEnumerable<ITestCase>",
                    null
                    ));
                return tests;
            }

            // the fixture does not exist yet.
            Object fixtureInstance = null;
            System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                fixtureInstance = fixture.CreateInstance();
                return (IEnumerable<ITestCase>)method.Invoke(fixtureInstance, null);
            }
            finally
            {
                IDisposable disposable = fixtureInstance as IDisposable;
                if (disposable != null)
                    disposable.Dispose();
            }
        }
コード例 #11
0
        private bool TryInvokeMemberWithNamedParameters(InvokeMemberBinder binder, object[] args, out object result,
                                                        MethodInfo method, ParameterInfo[] parameters)
        {
            var fixedArgs = new List<object>();
            for (int i = 0; i < parameters.Length; i++)
            {
                if (parameters[i].RawDefaultValue == DBNull.Value)
                {
                    fixedArgs.Add(args[i]);
                }
                else
                {
                    var index = binder.CallInfo.ArgumentNames.IndexOf(parameters[i].Name);
                    if (index > -1)
                    {
                        if (!parameters[i].ParameterType.IsInstanceOfType(args[index]))
                        {
                            result = null;
                            return false;
                        }
                    }
                    else
                    {
                        fixedArgs.Add(parameters[i].RawDefaultValue);
                    }
                }
            }

            result = method.Invoke(_adapter, fixedArgs.ToArray());
            return true;
        }
コード例 #12
0
ファイル: WarmupTestRunner.cs プロジェクト: Hammerstad/Moya
        public ITestResult Execute(MethodInfo methodInfo)
        {
            var type = methodInfo.DeclaringType;

            if (!MethodHasWarmupAttribute(methodInfo))
            {
                return new TestResult
                {
                    Outcome = TestOutcome.NotFound,
                    TestType = TestType.PreTest
                };
            }

            DetectDurationFromMethod(methodInfo);

            ExecuteWarmup(() =>
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                var instance = Activator.CreateInstance(type);
                do
                {
                    methodInfo.Invoke(instance, null);
                }
                while (Duration > 0);
            });

            return new TestResult
            {
                Outcome = TestOutcome.Success,
                TestType = TestType.PreTest
            };
        }
コード例 #13
0
ファイル: DetailsPage.xaml.cs プロジェクト: keyanmca/fameLive
        public void InvokeMethod( string ClassName, MethodInfo methodinfo, params object[] list )
        {
            ServiceModel model = new ServiceModel( this );
              Type MyType = ServiceLibInfo.testAssembly.GetType( ClassName );
              ConstructorInfo TestClassConstructor = MyType.GetConstructor( new Type[] { typeof( UserControl ), typeof( String ) } );
              object TestClassObject = TestClassConstructor.Invoke( new object[] { this, App.ViewModel.WebORBURL } );
              ParameterInfo[] parameters = methodinfo.GetParameters();
              Type[] returnGenericArgs = parameters[ parameters.Length - 1 ].ParameterType.GetGenericArguments();
              MethodInfo handlerMethod = model.GetType().GetMethod( methodinfo.Name + "ResultHandler", returnGenericArgs );
              Type responseHandlerType = typeof( ResponseHandler<> );
              responseHandlerType = responseHandlerType.MakeGenericType( returnGenericArgs );
              Delegate d = Delegate.CreateDelegate( responseHandlerType, model, handlerMethod );

              MethodInfo errorhandlerMethod = model.GetType().GetMethod( "ErrorHandler", new Type[] { typeof( Fault ) } );
              Delegate errordel = Delegate.CreateDelegate( typeof( ErrorHandler ), model, errorhandlerMethod );

              Type responderType = typeof( Responder<> );
              responderType = responderType.MakeGenericType( returnGenericArgs );
              Object responderObj = Activator.CreateInstance( responderType, new object[] { d, errordel } );

              if( parameters.Length == 1 )
              {
            list = new object[] { responderObj };
              }
              else
              {
            object[] newlist = new object[ list.Length + 1 ];
            Array.Copy( list, newlist, list.Length );
            newlist[ newlist.Length - 1 ] = responderObj;

            list = newlist;
              }

              methodinfo.Invoke( TestClassObject, list );
        }
コード例 #14
0
        private static void ChangeStates(UnityObject target, MethodInfo restoreState, MethodInfo saveState) {
            object result = restoreState.Invoke(null, new object[] { target });
            if ((bool)result == false) {
                Debug.LogWarning("Skipping " + target + " -- unable to successfuly deserialize", target);
                return;
            }

            ISerializedObject serializedObj = (ISerializedObject)target;
            var savedKeys = new List<string>(serializedObj.SerializedStateKeys);
            var savedValues = new List<string>(serializedObj.SerializedStateValues);
            var savedRefs = new List<UnityObject>(serializedObj.SerializedObjectReferences);

            result = saveState.Invoke(null, new object[] { target });
            if ((bool)result == false) {
                Debug.LogWarning("Skipping " + target + " -- unable to successfuly serialize", target);

                serializedObj.SerializedStateKeys = savedKeys;
                serializedObj.SerializedStateValues = savedValues;
                serializedObj.SerializedObjectReferences = savedRefs;

                return;
            }

            Debug.Log("Successfully migrated " + target, target);
            EditorUtility.SetDirty(target);
        }
コード例 #15
0
        private IEnumerable<TestCaseParameter> CreateMultipleInstances(MethodInfo method)
        {
            System.Collections.IEnumerable instances = null;
            object factory = null;
            System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                factory = Activator.CreateInstance(this.FactoryType);
                instances = method.Invoke(factory, null) as IEnumerable;

                int index = 0;
                foreach (object instance in instances)
                {
                    yield return new TestCaseParameter(
                        String.Format("{0}.{1}.{2}", this.FactoryType.Name, method.Name, index++),
                        instance
                        );
                }
            }
            finally
            {
                IDisposable disposable = factory as IDisposable;
                if (disposable != null)
                    disposable.Dispose();
            }
        }
コード例 #16
0
        /// <summary>
        /// Converts the given method into an <see cref="IDomainEventHandler"/> object.
        /// </summary>
        /// <param name="aggregateRoot">The aggregateroot from which we want to invoke the method.</param>
        /// <param name="method">The method to invoke</param>
        /// <param name="exact"><b>True</b> if we need to have an exact match, otherwise <b>False</b>.</param>
        /// <returns>An <see cref="IDomainEventHandler"/> that handles the execution of the given method.</returns>
        private static IDomainEventHandler CreateHandlerForMethod(AggregateRoot aggregateRoot, MethodInfo method, bool exact)
        {
            Type firstParameterType = method.GetParameters().First().ParameterType;

            Action<DomainEvent> handler = e => method.Invoke(aggregateRoot, new object[] { e });
            return new TypeThresholdedActionBasedDomainEventHandler(handler, firstParameterType, exact);
        }
コード例 #17
0
        public IEnumerable<MethodValue> GetValues(ReflectedInstance value, Type type, MethodInfo methodInfo)
        {
            if (methodInfo.Name == "Beep")
            {
                Note[] melody = new Note[] {
                    new Note(Note.C, 0, 100),
                    new Note(Note.C, 0, 100),
                    new Note(Note.D, 0, 100),
                    new Note(Note.E, 0, 100),
                    new Note(Note.F, 0, 100),
                    new Note(Note.G, 0, 100),
                    new Note(Note.A, 0, 100),
                    new Note(Note.B, 0, 100),
                    new Note(Note.C, 1, 100),
                    new Note(Note.D, 1, 100),
                    new Note(Note.E, 1, 100),
                    new Note(Note.F, 1, 100),
                    new Note(Note.G, 1, 100),
                    new Note(Note.A, 1, 100),
                    new Note(Note.B, 1, 100),
                    new Note(Note.C, 2, 100)
                };

                var parameters = methodInfo.GetParameters();
                foreach (var note in melody)
                {
                    var methodValue = methodInfo.Invoke("Beep", new object[] { note.Frequency, note.Duration });
                    var parameter = new MethodValueParam(parameters[0].Name, parameters[0], note.Frequency);
                    var parameter1 = new MethodValueParam(parameters[1].Name, parameters[1], note.Duration);
                    yield return new MethodValue(methodValue, parameter, parameter1);
                }
            }
        }
コード例 #18
0
 private object InvokeMethod(HttpContext context,MethodInfo methodInfo)
 {
     if(methodInfo!=null)
     {
         var parameters = methodInfo.GetParameters();
         object[] methodParameters=new object[parameters.Length];
         for (int i=0;i<parameters.Length;i++)
         {
             var parameterInfo = parameters[i];
             Type parameterType = parameterInfo.ParameterType;
             if(!parameterType.IsValueType && parameterType!=typeof(string))
             {
                 throw new Exception("只能处理参数为值类型和字符串的ajax方法");
             }
             string postParameter = context.Request.Form[parameterInfo.Name];
             if(string.IsNullOrEmpty(postParameter))
             {
                 methodParameters[i] = ReflectionHelper.GetDefaultValue(parameterType);
             }
             else
             {
                 methodParameters[i] = ReflectionHelper.ToType(parameterType, postParameter);
             }
         }
         object obj = null;
         if (!methodInfo.IsStatic)
             obj = Activator.CreateInstance(_type);
         return methodInfo.Invoke(obj, methodParameters);
     }
     return null;
 }
コード例 #19
0
 private void InvokeEventHandler(MethodInfo methodtoBeInvoked, IEvent e)
 {
     if (methodtoBeInvoked != null)
     {
         methodtoBeInvoked.Invoke(this, new object[] { e });
     }
 }
コード例 #20
0
        private void RunTest(MethodInfo testMethod, Type testClass, List<MethodInfo> testInitializeMethods, List<MethodInfo> testCleanupMethods)
        {
            var testClassInstance = Activator.CreateInstance(testClass);

            foreach (var testInitializeMethod in testInitializeMethods)
            {
                testInitializeMethod.Invoke(testClassInstance, null);
            }

            try
            {
                testMethod.Invoke(testClassInstance, null);
                PublishTestPassedEvent(testMethod);
            }
            catch (TargetInvocationException actualException)
            {
                if (WasExceptionExpected(testMethod, actualException))
                {
                    PublishTestPassedEvent(testMethod);
                }
                else
                {
                    PublishTestFailureEvent(testMethod, actualException);
                }
            }
            catch (Exception ex)
            {
                PublishTestFailureEvent(testMethod, ex);
            }

            foreach (var testCleanupMethod in testCleanupMethods)
            {
                testCleanupMethod.Invoke(testClassInstance, null);
            }
        }
コード例 #21
0
        private static object InvokeMethod(MethodInfo methodInfo, object instance, object[] arguments)
        {
            try
            {
                return methodInfo.Invoke(instance, arguments);
            }
            catch (ArgumentException ex)
            {
                throw new JobPerformanceException(
                    "An exception occurred during performance of the job.",
                    ex);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException is OperationCanceledException && !(ex.InnerException is TaskCanceledException))
                {
                    // `OperationCanceledException` and its descendants are used
                    // to notify a worker that job performance was canceled,
                    // so we should not wrap this exception and throw it as-is.
                    throw ex.InnerException;
                }

                throw new JobPerformanceException(
                    "An exception occurred during performance of the job.",
                    ex.InnerException);
            }
        }
コード例 #22
0
ファイル: ClrServiceEntryFactory.cs プロジェクト: yuexie/Rpc
        private ServiceEntry Create(string serviceId, MethodInfo method)
        {
            var type = method.DeclaringType;

            return new ServiceEntry
            {
                Descriptor = new ServiceDescriptor
                {
                    Id = serviceId
                },
                Func = parameters =>
                {
                    var instance = _serviceFactory.Create(type);

                    var list = new List<object>();
                    foreach (var parameterInfo in method.GetParameters())
                    {
                        var value = parameters[parameterInfo.Name];
                        list.Add(Convert.ChangeType(value, parameterInfo.ParameterType));
                    }

                    return method.Invoke(instance, list.ToArray());
                }
            };
        }
コード例 #23
0
 private static object CallMethod(MethodInfo methodInfo)
 {
     if (methodInfo.GetParameters().Length > 0) return null;
     var obj = Activator.CreateInstance(methodInfo.DeclaringType);
     var ret = methodInfo.Invoke(obj, null);
     return ret;
 }
        /// <summary>
        /// Converts the given method into an <see cref="ISourcedEventHandler"/> object.
        /// </summary>
        /// <param name="aggregateRoot">The event source from which we want to invoke the method.</param>
        /// <param name="method">The method to invoke</param>
        /// <param name="exact"><b>True</b> if we need to have an exact match, otherwise <b>False</b>.</param>
        /// <returns>An <see cref="ISourcedEventHandler"/> that handles the execution of the given method.</returns>
        private static ISourcedEventHandler CreateHandlerForMethod(IEventSource eventSource, MethodInfo method, bool exact)
        {
            Type firstParameterType = method.GetParameters().First().ParameterType;

            Action<IEvent> handler = e => method.Invoke(eventSource, new object[] { e });
            return new TypeThresholdedActionBasedDomainEventHandler(handler, firstParameterType, exact);
        }
コード例 #25
0
ファイル: TestRunner.cs プロジェクト: fundeveloper/CrossUI
        TestResultBitmap runMethodTest(object instance, MethodInfo method)
        {
            if (method.IsGenericMethod)
                throw new Exception("{0}: is not allowed to be generic".format(method));

            var parameters = method.GetParameters();
            if (parameters.Length != 1)
                throw new Exception("{0}: expect one parameter".format(method));

            var firstParameter = parameters[0];
            if (firstParameter.ParameterType != typeof(IDrawingContext))
                throw new Exception("{0}: expect IDrawingContext as first and only parameter");

            var attribute = (BitmapDrawingTestAttribute)method.GetCustomAttributes(typeof (BitmapDrawingTestAttribute), false)[0];

            using (var context = new BitmapDrawingContext(attribute.Width, attribute.Height))
            {
                IDrawingContext drawingContext;
                using (context.beginDraw(out drawingContext))
                {
                    method.Invoke(instance, new object[] { drawingContext });
                }

                return new TestResultBitmap(attribute.Width, attribute.Height, context.extractRawBitmap());
            }
        }
コード例 #26
0
        private static void SaveCLR(MailMessage message, Stream outputStream, MethodInfo sendMethod)
        {
            // Unfortunately we have to use reflection because of poorly designed .NET framework components

            Assembly assembly = typeof(SmtpClient).Assembly;
            Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

            // Get reflection info for MailWriter contructor
            var mailWriterContructor = mailWriterType.GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic,
                null,
                new[] { typeof(Stream) },
                null);

            // Construct MailWriter object with our FileStream
            object mailWriter = mailWriterContructor.Invoke(new object[] { outputStream });

            var methodParams = sendMethod.GetParameters().Length == 2
                                   ? new[] { mailWriter, true } // .NET 4.0 (and earlier?)
                                   : new[] { mailWriter, true, true }; // .NET 4.5 has an additional parameter

            // Call method passing in MailWriter
            sendMethod.Invoke(
                message,
                BindingFlags.Instance | BindingFlags.NonPublic,
                null,
                methodParams,
                null);
        }
コード例 #27
0
        private async Task<FeatureTestResult> RunTestAsync(MethodInfo test, Type adapterType, IEnumerable<FeatureTestRun> dependencies) {
            var specialCase = this.GetSpecialCase(test, adapterType)
                           ?? this.GetSpecialCase(test.DeclaringType, adapterType);

            if (specialCase != null && specialCase.Skip)
                return new FeatureTestResult(FeatureTestResultKind.SkippedDueToSpecialCase, specialCase.Comment);
            
            foreach (var dependency in dependencies) {
                var result = await dependency.Task;
                if (result.Kind != FeatureTestResultKind.Success) {
                    var className = FeatureTestAttributeHelper.GetDisplayName(dependency.Method.DeclaringType);
                    var testName = FeatureTestAttributeHelper.GetDisplayName(dependency.Method);

                    var skippedComment = string.Format("Skipped as {0} ({1}) is not supported by this library.", testName, className);
                    return new FeatureTestResult(FeatureTestResultKind.SkippedDueToDependency, skippedComment);
                }
            }

            var instance = Activator.CreateInstance(test.DeclaringType);
            using (instance as IDisposable) {
                try {
                    await Task.Run(() => test.Invoke(instance, new object[] {LibraryProvider.CreateAdapter(adapterType)}));
                }
                catch (Exception ex) {
                    var useful = ToUsefulException(ex);
                    if (useful is SkipException)
                        return new FeatureTestResult(FeatureTestResultKind.SkippedDueToSpecialCase, useful.Message);

                    return new FeatureTestResult(FeatureTestResultKind.Failure, exception: useful);
                }
            }

            var comment = specialCase != null ? specialCase.Comment : null;
            return new FeatureTestResult(FeatureTestResultKind.Success, comment);
        }
 public static void executeXRuleMethod(MethodInfo methodToExecute, Action<bool,object> executionResult)
 {            
     if (methodToExecute == null)
     {                
         executionResult(false,null);
     }
     else
         try
         {
             DI.log.info("executing method: {0}", methodToExecute.Name);
             // create method's type using default constructor
             var liveObject = DI.reflection.createObjectUsingDefaultConstructor(methodToExecute.DeclaringType);
             // and execute the method
             var returnData = methodToExecute.Invoke(liveObject, new object[] { });            // don't use the DI.reflection methods since we want the exceptions to be thrown
             //DI.reflection.invoke(liveObject, methodInfo, new object[] {});
             executionResult(true, returnData);
         }
         catch (Exception ex)
         {
             DI.log.error("in UnitTestSupport.executeXRuleMethod: {0} threw error: {1} ", methodToExecute.ToString(),
                          ex.Message);
             if (ex.InnerException != null)
             {
                 var innerExceptionMessage = ex.InnerException.Message;
                 DI.log.error("   InnerException value: {0}", innerExceptionMessage);
                 executionResult(false, innerExceptionMessage);
             }
             else
                 executionResult(false, null);
         }
 }
コード例 #29
0
ファイル: Internal.cs プロジェクト: RoqueDeicide/CryCIL
        private TestResultInfo RunTest(MethodInfo test)
        {
            var attr = test.GetAttribute<TestAttribute>();
            var testInfo = new TestResultInfo { Name = attr.Name, Description = attr.Description };

            if (test.ContainsAttribute<IgnoreTestAttribute>())
            {
                testInfo.Result = TestResult.Ignored;
                return testInfo;
            }

            try
            {
                test.Invoke(this.Instance, null);
                testInfo.Result = TestResult.Success;
                return testInfo;
            }
            catch (Exception ex)
            {
                // The main exception will always be a TargetInvocationException because we invoke
                // via reflection
                var inner = ex.InnerException;
                var trace = new StackTrace(inner, true);

                testInfo.Exception = inner;
                testInfo.Stack = trace;
                testInfo.Result = TestResult.Failure;
                return testInfo;
            }
        }
コード例 #30
0
ファイル: HandlerHelper.cs プロジェクト: ktj007/mmo
        private static void RegisterMessageHandler(object handler, MethodInfo method, int messageId)
        {
            var parameters = method.GetParameters();

            // MessageId가 있으면 그것으로 MessageType을 찾지만, 없다면 가장 마지막 인자가 MessageType이라고 추측한다.
            var messageType = messageId != MessageHandlerAttribute.DeduceFromParameter
                ? MessageHelper.TypeMap[messageId]
                : parameters.Last().ParameterType;

            // bind entity handler
            if (CheckIfParametersEquals(parameters, typeof(Entity), typeof(MessageSession),
                                        messageType))
            {
                var entitySessionHandler = new DispatchHandler.EntitySessionHandler(
                    (entity, session, message) => method.Invoke(handler, new object[] {entity, session, message}));

                DispatchHandler.Instance.AddHandler(messageType, entitySessionHandler);
            }

            // bind non-entity handler
            if (CheckIfParametersEquals(parameters, typeof(MessageSession), messageType))
            {
                var sessionHandler = new DispatchHandler.SessionHandler(
                    (session, message) => method.Invoke(handler, new object[] {session, message}));

                DispatchHandler.Instance.AddHandler(messageType, sessionHandler);
            }

            // bind non-session handler
            if (CheckIfParametersEquals(parameters, typeof(Entity), messageType))
            {
                var entityHandler = new DispatchHandler.EntityHandler(
                    (entity, message) => method.Invoke(handler, new object[] {entity, message}));

                DispatchHandler.Instance.AddHandler(messageType, entityHandler);
            }

            // bind message-only handler
            if (CheckIfParametersEquals(parameters, messageType))
            {
                var messageHandler = new DispatchHandler.Handler(
                    message => method.Invoke(handler, new object[] {message}));

                DispatchHandler.Instance.AddHandler(messageType, messageHandler);
            }
        }
コード例 #31
0
        public static string ToString(this Object obj, string format)
        {
            Type t = obj.GetType();

            Reflection.MethodInfo tostringMethod = t.GetMethod("ToString", Reflection.BindingFlags.Public | Reflection.BindingFlags.Instance, null, new Type[] { typeof(string) }, null);
            if (tostringMethod == null)
            {
                return(obj.ToString());
            }
            else
            {
                //Reflection.ParameterInfo[] paramsInfo = tostringMethod.GetParameters();//得到指定方法的参数列表
                return(tostringMethod.Invoke(obj, new object[] { format }).ToString());
            }
        }
コード例 #32
0
ファイル: DBContext.cs プロジェクト: DebugOfTheRoad/EntityDB
        internal static object InvokeToList(object linqQuery)
        {
            Type dataType  = linqQuery.GetType().GetGenericArguments()[0];
            Type queryType = typeof(System.Linq.Enumerable);
            var  methods   = queryType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static).Where(m => m.Name == "ToList");

            foreach (System.Reflection.MethodInfo method in methods)
            {
                System.Reflection.MethodInfo mmm = method.MakeGenericMethod(dataType);
                if (mmm != null)
                {
                    return(mmm.Invoke(null, new object[] { linqQuery }));
                }
            }
            return(null);
        }
コード例 #33
0
ファイル: GameViewUtils.cs プロジェクト: Pbart/Proto-Type
        public static object GetGroup()
        {
            var sizesType    = typeof(Editor).Assembly.GetType("UnityEditor.GameViewSizes");
            var singleType   = typeof(ScriptableSingleton <>).MakeGenericType(sizesType);
            var instanceProp = singleType.GetProperty("instance");

            object gameViewSizesInstance = instanceProp.GetValue(null, null);

            // Find the current group type
            var currentGroupTypeProperty           = sizesType.GetProperty("currentGroupType", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
            GameViewSizeGroupType currentGroupType = (GameViewSizeGroupType)currentGroupTypeProperty.GetValue(gameViewSizesInstance, null);

            // Get the GameViewSizeGroup
            System.Reflection.MethodInfo getGroup = sizesType.GetMethod("GetGroup");
            return(getGroup.Invoke(gameViewSizesInstance, new object[] { (int)currentGroupType }));
        }
コード例 #34
0
        public static object InvokeSelect(object linqQuery, string propertyName)
        {
            Type objectType = linqQuery.GetType();
            Type dataType   = null;

            if (objectType.IsArray)
            {
                object[] arr = (object[])linqQuery;
                if (arr.Length == 0)
                {
                    return(null);
                }
                dataType = arr[0].GetType();
                object[] result = new object[arr.Length];
                for (int i = 0; i < arr.Length; i++)
                {
                    result[i] = arr[i].GetType().GetTypeInfo().GetProperty(propertyName).GetValue(arr[i]);
                }
                return(result);
            }
            else
            {
                dataType = objectType.GetTypeInfo().GetGenericArguments()[0];
            }
            ParameterExpression param = System.Linq.Expressions.Expression.Parameter(dataType, "n");
            PropertyInfo        pinfo;

            System.Linq.Expressions.Expression left = GetPropertyExpression(param, dataType, propertyName, out pinfo);


            System.Linq.Expressions.Expression expression = System.Linq.Expressions.Expression.Lambda(left, param);

            Type myType = (linqQuery is System.Linq.IQueryable) ? typeof(System.Linq.Queryable) : typeof(System.Linq.Enumerable);

            var methods = myType.GetTypeInfo().GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

            foreach (System.Reflection.MethodInfo method in methods)
            {
                if (method.Name != "Select" || method.IsGenericMethod == false)
                {
                    continue;
                }
                System.Reflection.MethodInfo mmm = method.MakeGenericMethod(dataType, pinfo.PropertyType);
                return(mmm.Invoke(null, new object[] { linqQuery, expression }));
            }
            return(null);
        }
コード例 #35
0
    public void GenerateColorPreset(string _colorPath, string _codePath)
    {
        if (string.IsNullOrEmpty(_colorPath) || string.IsNullOrEmpty(_codePath))
        {
            return;
        }

        Debug.Log("_colorPath = " + _colorPath);
        Debug.Log("_codePath = " + _codePath);

        // 获取颜色样式
        System.Object[] instanceArray               = UnityEditorInternal.InternalEditorUtility.LoadSerializedFileAndForget(_colorPath);
        System.Type     typeColorPresetLibrary      = System.Type.GetType("UnityEditor.ColorPresetLibrary,UnityEditor");
        System.Reflection.MethodInfo _CountFunc     = typeColorPresetLibrary.GetMethod("Count");
        System.Reflection.MethodInfo _GetNameFunc   = typeColorPresetLibrary.GetMethod("GetName");
        System.Reflection.MethodInfo _GetPresetFunc = typeColorPresetLibrary.GetMethod("GetPreset");

        string genCode = "";

        System.Object colorLibIntance = instanceArray[0];
        int           count           = (int)_CountFunc.Invoke(colorLibIntance, null);

        for (int i = 0; i < count; ++i)
        {
            string name = (string)_GetNameFunc.Invoke(colorLibIntance, new System.Object[1] {
                i
            });
            Color col = (Color)_GetPresetFunc.Invoke(colorLibIntance, new System.Object[1] {
                i
            });
            string hexStr = ColorPresets.ColorToHexString(col);
            genCode += string.Format(FORMAT_COLORITEM, ColorPresets.COLOR_PREFIX, name, hexStr);
        }

        // 插入到目标代码颜色码区域
        string content    = System.IO.File.ReadAllText(_codePath);
        int    beginIndex = content.IndexOf(BEGIN_GENERATE_CODE);
        int    endIndex   = content.IndexOf(END_GENERATE_CODE);

        string upContent   = content.Substring(0, beginIndex + BEGIN_GENERATE_CODE.Length);
        string backContent = content.Substring(endIndex);

        string newStr = upContent + "\n" + genCode + backContent;

        Debug.Log(newStr);
        File.WriteAllText(_codePath, newStr);
    }
コード例 #36
0
        /// <summary>
        /// Funktion gibt eine Linq To SQL Expression zurück, welche bezüglich der gewählten Spalte 
        /// in der gewählten Richtung sortiert.
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="ViewColName"></param>
        /// <param name="SortDescending"></param>
        /// <returns></returns>
        public IQueryable<TEntity> sort(IQueryable<TEntity> tab, SortColumnDef sc)
        {
            Debug.Assert(!string.IsNullOrEmpty(sc.ColName));
            Debug.Assert(tab != null);
            Debug.Assert(tab.Count() > 0);


            if (sc.ViewType == typeof(TEntityView))
            {
                // Fall: Die Spalte stammt aus der aktuellen View
                Debug.Assert(typeof(TEntityView).GetProperty(sc.ColName) != null);

                // Namen der Eigenschaft einer EntityView auf die Eigenschaft eines zugrundeliegenden Entity abbilden
                string Colname = mapPropertyToColName(typeof(TEntityView), sc.ColName);

                // Sortieren bezüglich abgeleiteter Spalten in den Views
                IQueryable<TEntity> tabSorted;
                if (sortByDerivat(tab, Colname, sc.SortDescending, out tabSorted))
                    return tabSorted;

                // Wenn die Spalte keine abgeleitete Spalte ist, dann sortieren nach den tatsächlichen Spalten
                return OrderFunc<TEntity>(tab, Colname, sc.SortDescending);

            }
            else
            {
                // Fall: Die Spalte stammt aus einer anderen View als der aktuellen

                System.Reflection.PropertyInfo pinfo = sc.ViewType.GetProperty(_sortColname);
                Debug.Assert(pinfo != null);

                // Businessobjekt für andere View erstellen
                Type[] constuctorArgTypes = Type.EmptyTypes;
                System.Reflection.ConstructorInfo ctor = GetBoThatInclude(sc.ViewType).GetConstructor(constuctorArgTypes);
                Debug.Assert(ctor != null);

                object[] constructorArgs = { };
                object boOther = ctor.Invoke(constructorArgs);

                // sort- Methode des anderen Businessobjekts aufrufen
                Type[] sortArgTypes = new Type[] { typeof(IQueryable<TEntity>), typeof(SortColumnDef) };
                System.Reflection.MethodInfo miSort = GetBoThatInclude(sc.ViewType).GetMethod("sort", sortArgTypes);
                Debug.Assert(miSort != null, "Die Sortiermethode ist im Business- Objekt nicht enthalten");
                object[] sortArgs = { tab, sc };
                return miSort.Invoke(boOther, sortArgs) as IQueryable<TEntity>;
            }
        }
コード例 #37
0
        protected void DataPortal_Fetch(object criteria)
        {
            //crear la conexion a la base
            if (Db == null)
            {
                Db = DatabaseFactory.CreateDatabase();
            }
            Comando = Db.CreateSPCommand(ObtenerSp);

            //setear los parametros
            MethodInfo methodInfo = GetType().GetMethod(_nombreMetodo, BindingFlags.NonPublic | BindingFlags.Instance,
                Type.DefaultBinder, new[] {criteria.GetType()}, null);
            if (methodInfo != null)
            {
                methodInfo.Invoke(this, new[] {criteria});
            }
            else
            {
                if (criteria is int)
                {
                    Db.AddParameterWithValue(Comando, "en_id", DbType.Int32, criteria);
                }
                else if (criteria is string)
                {

                    Db.AddParameterWithValue(Comando, "ec_codigo", DbType.String, criteria);
                }
                else
                {
                    throw new JusException(
                        String.Format("No se implemento el metodo {0}, Ej: 'private void {0}({1} criteria)'",
                            _nombreMetodo, criteria.GetType()));
                }
            }
            Db.AddParameter(Comando, "sq_resultado", DbType.Object, ParameterDirection.Output);
            using (var dr = Db.ExecuteDataReader(Comando))

                while (dr.Read())
                {
                    AddCommonData(dr);
                    Fetch(dr);
                    if (dr.NextResult())
                    {
                        throw new JusException("Existe mas de un resultado");
                    }
                }
        }
コード例 #38
0
            /// <summary>
            /// Gets the value of initialization according to the InitialValueMethod of this provider.
            /// </summary>
            /// <param name="bFixedLengthString">Optional bolean flag that indicates if the current array type is fixed length string (original vb6 code) -
            /// its default value is false, because it will be generated in upgraded code when current array type used to be a fixed length string.</param>
            /// <param name="iFixedLengthStringSize">Optional integer value that indicates what is the fixed length string size, used in conjunction with previous (bFixedLengthString) parameter.</param>
            /// <returns>The value of initialization.</returns>
            public Object GetInitialValue(bool bFixedLengthString = false, int iFixedLengthStringSize = 0)
            {
                Initialize();
                switch (_initializeMethod)
                {
#if ACTIVEX_COMPONENTSERVER
                case InitialValueMethod.CsFactory:
                    try
                    {
                        Type factoryType = null;
                        foreach (Type possibleFactory in _elementType.Assembly.GetExportedTypes())
                        {
                            if (possibleFactory.BaseType.Name == "ComponentServerFactory")
                            {
                                factoryType = possibleFactory;
                            }
                        }
                        if (factoryType != null)
                        {
                            MethodInfo mi        = factoryType.GetMethod("CreateInstance", BindingFlags.Static | BindingFlags.Public);
                            MethodInfo miGeneric = mi.MakeGenericMethod(_elementType);
                            return(miGeneric.Invoke(null, new object[] { }));
                        }
                    }
                    catch (Exception ex)
                    {
                        return(new Exception("Error while trying to get initial value for an array", ex));
                    }
                    break;
#endif
                case InitialValueMethod.String:
                    return(bFixedLengthString ? new string('\0', iFixedLengthStringSize) : string.Empty);

                case InitialValueMethod.Constructor:
                    return(_constructor.Invoke(_constructorParams));

                case InitialValueMethod.ValueType:
                    return(Activator.CreateInstance(_elementType));

                case InitialValueMethod.CreateInstanceValueType:
                    return(_method.Invoke(null, new object[] { }));

                case InitialValueMethod.Null:
                    return(null);
                }
                return(null);
            }
コード例 #39
0
        /// <summary>
        /// Converts a string to an object.
        /// </summary>
        /// <param name="target">The target type to convert to.</param>
        /// <param name="txt">The string to convert to an object.</param>
        /// <returns>
        /// The object converted from a string or <c>null</c> when the
        /// conversion failed.
        /// </returns>
        public static object ConvertStringTo(Type target, string txt)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            // If we want a string we already have the correct type
            if (target == typeof(string))
            {
                return(txt);
            }

            if (target.IsEnum)
            {
                // Target type is an enum.

                // Use the Enum.Parse(EnumType, string) method to get the enum value
                return(ParseEnum(target, txt, true));
            }
            else
            {
                // We essentially make a guess that to convert from a string
                // to an arbitrary type T there will be a static method defined on type T called Parse
                // that will take an argument of type string. i.e. T.Parse(string)->T we call this
                // method to convert the string to the type required by the property.
                System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] { typeof(string) });
                if (meth != null)
                {
                    // Call the Parse method
                    return(meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] { txt }, CultureInfo.InvariantCulture));
                }
                else
                {
                    // Ok no Parse() method found.

                    // Lets try to find a type converter
                    IConvertFrom typeConverter = GetTypeConverter(target);
                    if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
                    {
                        // Found appropriate converter
                        return(typeConverter.ConvertFrom(txt));
                    }
                }
            }
            return(null);
        }
コード例 #40
0
        public void ProcessControlCommand(ServerAction controlCommand)
        {
            currentServerAction = controlCommand;

            errorMessage       = "";
            errorCode          = ServerActionErrorCode.Undefined;
            collisionsInAction = new List <string>();

            lastAction        = controlCommand.action;
            lastActionSuccess = false;
            lastPosition      = new Vector3(transform.position.x, transform.position.y, transform.position.z);
            System.Reflection.MethodInfo method = this.GetType().GetMethod(controlCommand.action);

            this.actionComplete = false;
            try
            {
                if (method == null)
                {
                    errorMessage = "Invalid action: " + controlCommand.action;
                    errorCode    = ServerActionErrorCode.InvalidAction;
                    Debug.LogError(errorMessage);
                    actionFinished(false);
                }
                else
                {
                    method.Invoke(this, new object[] { controlCommand });
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Caught error with invoke for action: " + controlCommand.action);
                Debug.LogError("Action error message: " + errorMessage);
                Debug.LogError(e);

                errorMessage += e.ToString();
                actionFinished(false);
            }

#if UNITY_EDITOR
            if (errorMessage != "")
            {
                Debug.Log(errorMessage);
            }
#endif

            agentManager.setReadyToEmit(true);
        }
コード例 #41
0
ファイル: LuaTrack.cs プロジェクト: phzou204/UWPTools
        static int setAge(int L)
        {
            if (!LuaCommon.CheckAndShowArgsError(L, LConst.Integer))
            {
                return(0);
            }

            int age = Lua.Lua_tointeger(L, 2);

            //RYTTrackInstanse.AddTask(() => { RYTTrackInstanse.SetAge(age); });

            System.Reflection.MethodInfo AddTask_MethodInfo = TrackType.GetMethod("AddTask");
            Action SetAge_Action = delegate() { TrackType.GetMethod("SetAge").Invoke(RYTTrackInstanse, new object[] { age }); };

            AddTask_MethodInfo.Invoke(RYTTrackInstanse, new object[] { SetAge_Action });
            return(0);
        }
コード例 #42
0
    public static void BroadcastEditorMessageToScene(string messageName, System.Object[] parameters = null)
    {
        MonoBehaviour[] all = Resources.FindObjectsOfTypeAll <MonoBehaviour> ();
        for (int i = 0; i < all.Length; i++)
        {
            MonoBehaviour mb = all[i];

            if (mb.IsSceneObject())
            {
                System.Reflection.MethodInfo method = mb.GetType().GetMethod(messageName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                if (method != null)
                {
                    method.Invoke(mb, parameters);
                }
            }
        }
    }
コード例 #43
0
ファイル: GenUtils.cs プロジェクト: mikesavior/elmcity
 public static T CloneObject <T>(this T obj) where T : class               // http://stackoverflow.com/questions/2023210/cannot-access-protected-member-object-memberwiseclone
 {
     if (obj == null)
     {
         return(null);
     }
     System.Reflection.MethodInfo inst = obj.GetType().GetMethod("MemberwiseClone",
                                                                 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
     if (inst != null)
     {
         return((T)inst.Invoke(obj, null));
     }
     else
     {
         return(null);
     }
 }
コード例 #44
0
        private static void rellenarAtributo(object objetoInstancia, Type tipoInstancia, string valor, string nombreHijo)
        {
            System.Reflection.MethodInfo metodo = tipoInstancia.GetMethod("set_" + nombreHijo);

            string tipoParaetro = metodo.GetParameters()[0].ParameterType.Name;

            object parametro = null;

            switch (tipoParaetro)
            {//completar con los tipos basicos de XML
            case "Decimal":
                parametro = Decimal.Parse(valor);
                break;
            }

            metodo.Invoke(objetoInstancia, new object[] { parametro });
        }
コード例 #45
0
        public static string CallMethod(string url, string methodName, object[] args)
        {
            //设定编译参数
            CompilerParameters cplist = new CompilerParameters();

            cplist.GenerateExecutable = false; //动态编译后的程序集不生成可执行文件
            cplist.GenerateInMemory   = true;  //动态编译后的程序集只存在于内存中,不在硬盘的文件上
            cplist.ReferencedAssemblies.Add("System.dll");
            cplist.ReferencedAssemblies.Add("System.XML.dll");
            cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
            cplist.ReferencedAssemblies.Add("System.Data.dll");
            long t2 = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds);
            //获取WSDL
            WebClient wc = new WebClient();
            //Stream stream = wc.OpenRead(url + "?WSDL");
            Stream             stream = wc.OpenRead(url);
            ServiceDescription sd     = ServiceDescription.Read(stream);
            //var preclass_classname = sd.Services[0].Name;
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, "", "");
            CodeNamespace cn = new CodeNamespace("client");
            //生成客户端代理类代码
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            CSharpCodeProvider csc = new CSharpCodeProvider();
            //编译代理类
            var preclass_cr = csc.CompileAssemblyFromDom(cplist, ccu);

            //编译代理类
            var resource_cr = csc.CompileAssemblyFromDom(cplist, ccu);

            //生成代理实例,并调用方法
            assembly = resource_cr.CompiledAssembly;

            //生成代理实例,并调用方法
            Type   t   = assembly.GetType("client" + "." + sd.Services[0].Name, true, true);
            object obj = Activator.CreateInstance(t);

            System.Reflection.MethodInfo mi = t.GetMethod(methodName);
            //注:method.Invoke(o, null)返回的是一个Object,如果你服务端返回的是DataSet,这里也是用(DataSet)method.Invoke(o, null)转一下就行了,method.Invoke(0,null)这里的null可以传调用方法需要的参数,string[]形式的
            //return (string)mi.Invoke(obj, args);
            return(mi.Invoke(obj, args).ToString());
        }
コード例 #46
0
        private void MakeUnBuffered(Control control)
        {
            System.Reflection.MethodInfo mInfo = typeof(Control).GetMethod("SetStyle",
                                                                           System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod |
                                                                           System.Reflection.BindingFlags.NonPublic);
            if (mInfo != null)
            {
                mInfo.Invoke(control, new

                             object[] { Syncfusion.Windows.Forms.WhidbeyCompatibleControlStyles.DoubleBuffer, false });
            }
            foreach (Control cc in control.Controls)
            {
                cc.CausesValidation = false;
                MakeUnBuffered(cc);
            }
        }
コード例 #47
0
 public static object InvokeWebService(Type type, string methodname, object[] args)
 {
     try
     {
         object obj = Activator.CreateInstance(type);
         System.Reflection.MethodInfo mi = type.GetMethod(methodname);
         if (mi == null)
         {
             throw new Exception("未找到方法名:" + methodname);
         }
         return(mi.Invoke(obj, args));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
     }
 }
コード例 #48
0
ファイル: DBContext.cs プロジェクト: jangocheng/EntityDB
        public static object InvokeFirstOrDefault(object linqQuery)
        {
            Type dataType = linqQuery.GetType().GetGenericArguments()[0];
            Type myType   = typeof(System.Linq.Queryable);
            var  methods  = myType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

            foreach (System.Reflection.MethodInfo method in methods)
            {
                if (method.Name != "FirstOrDefault" || method.IsGenericMethod == false)
                {
                    continue;
                }
                System.Reflection.MethodInfo mmm = method.MakeGenericMethod(dataType);
                return(mmm.Invoke(null, new object[] { linqQuery }));
            }
            return(null);
        }
コード例 #49
0
ファイル: NetworkLogin.cs プロジェクト: mengtest/testSkynet
 private void Client_SendCompleted(NetWorkArgs args)
 {
     try
     {
         if (args.State == NetworkState.Sended)
         {
             NetworkIOArgs arg = args as NetworkIOArgs;
             Type          t   = this.GetType();
             System.Reflection.MethodInfo callback = t.GetMethod(sendMethodName[(int)this.sendstate].Trim(), BindingFlags.NonPublic | BindingFlags.Instance);
             object[] param = new object[] { arg };
             callback.Invoke(this, param);
         }
     }
     catch
     {
     }
 }
コード例 #50
0
ファイル: DBContext.cs プロジェクト: simpleway2016/EntityDB
        public static object GetQueryByString(object linqQuery, string stringQuery)
        {
            Type dataType             = linqQuery.GetType().GetGenericArguments()[0];
            Type dynamicQueryableType = typeof(DynamicQueryable);
            var  methods = dynamicQueryableType.GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);

            foreach (System.Reflection.MethodInfo method in methods)
            {
                if (method.Name != "Where" || method.IsGenericMethod == false)
                {
                    continue;
                }
                System.Reflection.MethodInfo mmm = method.MakeGenericMethod(dataType);
                return(mmm.Invoke(null, new object[] { linqQuery, stringQuery, null }));
            }
            return(linqQuery);
        }
コード例 #51
0
 /// <summary>
 /// Clones a object via shallow copy
 /// </summary>
 /// <typeparam name="T">Object Type to Clone</typeparam>
 /// <param name="obj">Object to Clone</param>
 /// <returns>New Object reference</returns>
 public static T CloneObject <T>(this T obj) where T : class
 {
     if (obj == null)
     {
         return(null);
     }
     System.Reflection.MethodInfo inst = obj.GetType().GetMethod("MemberwiseClone",
                                                                 System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
     if (inst != null)
     {
         return((T)inst.Invoke(obj, null));
     }
     else
     {
         return(null);
     }
 }
コード例 #52
0
ファイル: DBContext.cs プロジェクト: simpleway2016/EntityDB
        public static object GetQueryForThenBy(object linqQuery, string stringOrder)
        {
            Type myType               = typeof(System.Linq.Queryable);
            Type dataType             = linqQuery.GetType().GetGenericArguments()[0];
            ParameterExpression param = System.Linq.Expressions.Expression.Parameter(dataType, "n");
            var methods               = myType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);

            string[] orders = stringOrder.Split(',');
            foreach (string order in orders)
            {
                if (order.Trim().Length == 0)
                {
                    continue;
                }
                bool   desc         = order.Trim().ToLower().Contains(" desc");
                string methodName   = desc ? "ThenByDescending" : "ThenBy";
                string itemProperty = order.Trim().Split(' ')[0];
                if (itemProperty.StartsWith("[") && itemProperty.EndsWith("]"))
                {
                    itemProperty = itemProperty.Substring(1, itemProperty.Length - 2);
                }

                System.Reflection.PropertyInfo     pinfo;
                System.Linq.Expressions.Expression left       = GetPropertyExpression(param, dataType, itemProperty, out pinfo);
                System.Linq.Expressions.Expression expression = System.Linq.Expressions.Expression.Lambda(left, param);


                foreach (System.Reflection.MethodInfo method in methods)
                {
                    if (method.Name != methodName || method.IsGenericMethod == false)
                    {
                        continue;
                    }
                    System.Reflection.MethodInfo mmm = method.MakeGenericMethod(dataType, pinfo.PropertyType);
                    if (mmm.GetParameters().Length != 2)
                    {
                        continue;
                    }

                    linqQuery = mmm.Invoke(null, new object[] { linqQuery, expression });
                    break;
                }
            }
            return(linqQuery);
        }
コード例 #53
0
        //int i = (int)Calc("1+2*3");
        //Console.WriteLine(i.ToString());
        public static object Calc(string expression)
        {
            string className  = "Calc";
            string methodName = "Run";

            expression = expression.Replace("/", "*1.0/");

            //  创建编译器实例。
            System.CodeDom.Compiler.CodeDomProvider _CodeDomProvider = System.CodeDom.Compiler
                                                                       .CodeDomProvider.CreateProvider("CSharp");
            //  设置编译参数。
            System.CodeDom.Compiler.CompilerParameters paras = new System.CodeDom.Compiler.CompilerParameters();
            paras.GenerateExecutable = false;          //编译成exe还是dll
            paras.GenerateInMemory   = false;          //是否写入内存,不写入内存就写入磁盘
            paras.OutputAssembly     = "c:\\test.dll"; //输出路径
            paras.ReferencedAssemblies.Add("System.dll");
            //  创建动态代码。
            StringBuilder classSource = new StringBuilder();

            classSource.Append("public  class  " + className + "\n");
            classSource.Append("{\n");
            classSource.Append("        public  object  " + methodName + "()\n");
            classSource.Append("        {\n");
            classSource.Append("                return  " + expression + ";\n");
            classSource.Append("        }\n");
            classSource.Append("}");

            //   System.Diagnostics.Debug.WriteLine(classSource.ToString());

            //  编译代码。
            System.CodeDom.Compiler.CompilerResults result = _CodeDomProvider
                                                             .CompileAssemblyFromSource(paras, classSource.ToString());

            //  获取编译后的程序集。
            System.Reflection.Assembly assembly = result.CompiledAssembly;

            //  动态调用方法。
            object eval = assembly.CreateInstance(className);

            System.Reflection.MethodInfo method = eval.GetType().GetMethod(methodName);
            object reobj = method.Invoke(eval, null);

            GC.Collect();
            return(reobj);
        }
コード例 #54
0
        GetAllSizeNames()
        {
            List <string> names = new List <string> ();
            object        group = GetCurrentGameViewSizeGroup();

            System.Reflection.MethodInfo getTotalCount   = group.GetType().GetMethod("GetTotalCount", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            System.Reflection.MethodInfo getGameViewSize = group.GetType().GetMethod("GetGameViewSize", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            int size = (int)getTotalCount.Invoke(group, null);

            for (int i = 0; i < size; i++)
            {
                object gameViewSize = getGameViewSize.Invoke(group, new object[] { i });
                string name         = (string)gameViewSize.GetType().GetProperty("baseText", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(gameViewSize, null);
                names.Add(name);
            }
            return(names);
        }
コード例 #55
0
ファイル: GameViewUtils.cs プロジェクト: Pbart/Proto-Type
        public static List <string> GetAllSizeNames()
        {
            List <string> names = new List <string> ();
            object        group = GetGroup();

            System.Reflection.MethodInfo getTotalCount   = group.GetType().GetMethod("GetTotalCount");
            System.Reflection.MethodInfo getGameViewSize = group.GetType().GetMethod("GetGameViewSize");

            int size = (int)getTotalCount.Invoke(group, null);

            for (int i = 0; i < size; i++)
            {
                object gameViewSize = getGameViewSize.Invoke(group, new object[] { i });
                string name         = (string)gameViewSize.GetType().GetProperty("baseText").GetValue(gameViewSize, null);
                names.Add(name);
            }
            return(names);
        }
コード例 #56
0
 private static string ReadStandPref(string ecClassName)
 {
     try
     {
         System.Reflection.Assembly   assembly = System.Reflection.Assembly.Load("Bentley.Plant.StandardPreferences");
         System.Reflection.MethodInfo m        =
             assembly.GetType("Bentley.Plant.StandardPreferences.DlgStandardPreference")
             .GetMethod("GetPreferenceValue");
         Object[]      param = { ecClassName };
         System.Object ret   = m.Invoke(null, param);
         return((string)ret);
     }
     catch (Exception ex)
     {
         string msg = ex.Message;
     }
     return(string.Empty);
 }
コード例 #57
0
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext context = this.Context;
        YZRequest   request = new YZRequest(context);
        string      method  = request.GetString("method", request.GetString("action", "Default"));

        Type type = this.GetType();

        System.Reflection.MethodInfo methodcall = type.GetMethod(method, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public, null, new Type[] {}, null);
        if (methodcall == null)
        {
            this.Default();
        }
        else
        {
            methodcall.Invoke(this, new object[] { });
        }
    }
コード例 #58
0
        public virtual object GetValue()
        {
            object value = null;

            if (Component != null)
            {
                ValidateAccessMethods();
                if (_Getter != null)
                {
                    value = _Getter.Invoke(Component, null);
                }
                else if (_Field != null)
                {
                    value = _Field.GetValue(Component);
                }
            }
            return(value);
        }
コード例 #59
0
ファイル: LuaTrack.cs プロジェクト: phzou204/UWPTools
        static int endSession(int L)
        {
            if (!LuaCommon.CheckAndShowArgsError(L, LConst.NBoolean))
            {
                return(0);
            }
            bool immediately = false;

            if (Lua.Lua_gettop(L) > 1)
            {
                immediately = Lua.Lua_toboolean(L, 2);
            }

            //RYTTrackInstanse.EndSession(immediately);
            System.Reflection.MethodInfo EndSession_MethodInfo = TrackType.GetMethod("EndSession");
            EndSession_MethodInfo.Invoke(RYTTrackInstanse, new object[] { immediately });
            return(0);
        }
コード例 #60
0
        public static bool CallStaticFunction(System.Type p_type, string p_functionName, params object[] p_param)
        {
            if (p_type != null)
            {
                try
                {
                    System.Reflection.MethodInfo v_info = p_type.GetMethod(p_functionName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

                    if (v_info != null)
                    {
                        v_info.Invoke(null, p_param);
                        return(true);
                    }
                }
                catch { }
            }
            return(false);
        }