GetMethod() public method

Searches for the public method with the specified name.
More than one method is found with the specified name. is null.
public GetMethod ( string name ) : MethodInfo
name string The string containing the name of the public method to get.
return MethodInfo
Esempio n. 1
0
        public static bool GetPrimitives(Type containerType, Type type, out MethodInfo writer, out MethodInfo reader)
        {
            if (type.IsEnum)
                type = Enum.GetUnderlyingType(type);

            if (type.IsGenericType == false)
            {
                writer = containerType.GetMethod("WritePrimitive", BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding, null,
                    new Type[] { typeof(Stream), type }, null);

                reader = containerType.GetMethod("ReadPrimitive", BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding, null,
                    new Type[] { typeof(Stream), type.MakeByRefType() }, null);
            }
            else
            {
                var genType = type.GetGenericTypeDefinition();

                writer = GetGenWriter(containerType, genType);
                reader = GetGenReader(containerType, genType);
            }

            if (writer == null && reader == null)
                return false;
            else if (writer != null && reader != null)
                return true;
            else
                throw new InvalidOperationException(String.Format("Missing a {0}Primitive() for {1}",
                    reader == null ? "Read" : "Write", type.FullName));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="incomingActionMethod"></param>
        /// <param name="outgoingActionMethod"></param>
        public ActionServiceBehavior(Type provider, string incomingActionMethod, string outgoingActionMethod)
        {
            if (provider == null)
                throw new ServiceArgumentException("The provider for getting ISessionFactory object cannot be null.", "provider");

            if (string.IsNullOrEmpty(incomingActionMethod))
                throw new ServiceArgumentException("The incoming action method cannot be null.", "incomingActionMethod");

            if (string.IsNullOrEmpty(outgoingActionMethod))
                throw new ServiceArgumentException("The outgoing action method cannot be null.", "outgoingActionMethod");

            const BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
            MethodInfo incomingMethod = provider.GetMethod(incomingActionMethod, flags);
            MethodInfo outgoingMethod = provider.GetMethod(outgoingActionMethod, flags);

            if (incomingMethod == null)
                throw new ServiceArgumentException(string.Format("No incoming method found, name method: {0}", incomingActionMethod), "incomingActionMethod");

            if (outgoingActionMethod == null)
                throw new ServiceArgumentException(string.Format("No outgoing method found, name method: {0}", outgoingActionMethod), "outgoingActionMethod");

            try
            {
                this.incomingAction = (Action) Delegate.CreateDelegate(typeof(Action), incomingMethod, true);
                this.outgoingAction = (Action) Delegate.CreateDelegate(typeof(Action), outgoingMethod, true);
            }
            catch (Exception ex)
            {
                throw new ServiceBehaviorException("An inner exception occurs when the calling instance tried to compile own action for inspectors, for details see innerException.", ex);
            }
        }
Esempio n. 3
0
		static ZipTools()
		{
			try
			{
				var windowsBase = typeof (Package).Assembly;
				ZipArchive = windowsBase.GetType("MS.Internal.IO.Zip.ZipArchive");
				ZipArchive_OpenOnFile = ZipArchive.GetMethod("OpenOnFile", BindingFlags.NonPublic | BindingFlags.Static);
				ZipArchive_GetFiles = ZipArchive.GetMethod("GetFiles", BindingFlags.NonPublic | BindingFlags.Instance);
				ZipArchive_ZipIOBlockManager = ZipArchive.GetField("_blockManager", BindingFlags.NonPublic | BindingFlags.Instance);

				ZipFileInfo = windowsBase.GetType("MS.Internal.IO.Zip.ZipFileInfo");
				ZipFileInfo_GetStream = ZipFileInfo.GetMethod("GetStream", BindingFlags.NonPublic | BindingFlags.Instance);
				ZipFileInfo_Name = ZipFileInfo.GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
				ZipFileInfo_FolderFlag = ZipFileInfo.GetProperty("FolderFlag", BindingFlags.NonPublic | BindingFlags.Instance);

				ZipIOBlockManager = windowsBase.GetType("MS.Internal.IO.Zip.ZipIOBlockManager");
				ZipIOBlockManager_Encoding = ZipIOBlockManager.GetField("_encoding", BindingFlags.NonPublic | BindingFlags.Instance);

				Enabled = true;
			}
			catch
			{
				Enabled = false;
			}
		}
        public override void Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder specification) {
            IFacet facet = null;

            if (!type.IsInterface && typeof (IViewModel).IsAssignableFrom(type)) {
                MethodInfo deriveMethod = type.GetMethod("DeriveKeys", new Type[] {});
                MethodInfo populateMethod = type.GetMethod("PopulateUsingKeys", new[] {typeof (string[])});

                var toRemove = new List<MethodInfo> {deriveMethod, populateMethod};

                if (typeof (IViewModelEdit).IsAssignableFrom(type)) {
                    facet = new ViewModelEditFacetConvention(specification);
                }
                else if (typeof (IViewModelSwitchable).IsAssignableFrom(type)) {
                    MethodInfo isEditViewMethod = type.GetMethod("IsEditView");
                    toRemove.Add(isEditViewMethod);
                    facet = new ViewModelSwitchableFacetConvention(specification);
                }
                else {
                    facet = new ViewModelFacetConvention(specification);
                }
                methodRemover.RemoveMethods(toRemove.ToArray());
            }

            FacetUtils.AddFacet(facet);
        }
Esempio n. 5
0
 static FGConsole()
 {
     consoleWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
     if (consoleWindowType != null)
     {
         consoleWindowField = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
         consoleListViewField = consoleWindowType.GetField("m_ListView", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         consoleActiveTextField = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         consoleOnGUIMethod = consoleWindowType.GetMethod("OnGUI", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
     }
     listViewStateType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ListViewState");
     if (listViewStateType != null)
     {
         listViewStateRowField = listViewStateType.GetField("row", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     }
     editorWindowPosField = typeof(EditorWindow).GetField("m_Pos", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     logEntriesType = typeof(EditorWindow).Assembly.GetType("UnityEditorInternal.LogEntries");
     if (logEntriesType != null)
     {
         getEntryMethod = logEntriesType.GetMethod("GetEntryInternal", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
         startGettingEntriesMethod = logEntriesType.GetMethod("StartGettingEntries", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
         endGettingEntriesMethod = logEntriesType.GetMethod("EndGettingEntries", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
     }
     logEntryType = typeof(EditorWindow).Assembly.GetType("UnityEditorInternal.LogEntry");
     if (logEntryType != null)
     {
         logEntry = System.Activator.CreateInstance(logEntryType);
         logEntryFileField = logEntryType.GetField("file", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         logEntryLineField = logEntryType.GetField("line", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         logEntryInstanceIDField = logEntryType.GetField("instanceID", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     }
 }
Esempio n. 6
0
        internal static SequenceDefinition CreateCollectionDefinition(Type type)
        {
            // IEnumerable<T> with Add(T) method
            Type itemType = type.GetGenericInterfaceType(typeof(IEnumerable<>));
            if (itemType != null)
            {
                MethodInfo addMethod = type.GetMethod("Add", new[] { itemType });
                if (addMethod != null)
                {
                    return new CollectionDefinition(type, itemType, ObjectInterfaceProvider.GetAction(addMethod));
                }
            }

            // IEumerable with Add(object) method
            if (type.CanBeCastTo(typeof(IEnumerable)))
            {
                MethodInfo addMethod = type.GetMethod("Add", new[] { typeof(object) });
                if (addMethod != null)
                {
                    return new CollectionDefinition(type, typeof(object), ObjectInterfaceProvider.GetAction(addMethod));
                }
            }

            return null;
        }
Esempio n. 7
0
 public FactoryProxy(Type factoryType, object target)
 {
     _factoryType = factoryType;
       _target = target;
       _create = _factoryType.GetMethod("Create");
       _deactivate = _factoryType.GetMethod("Deactivate");
 }
Esempio n. 8
0
        //
#if !mono

        public void runMain(Type mainType, object main, Scanner scanner, string ansExpected, object answerType)
        {
            var input = mainType.GetMethod("createInput").Invoke(main, new object[] { scanner });


            //string ans = ( (InputFileConsumer<LostInput,string>) main).processInput(input);
            var ans = mainType.GetMethod("processInput").Invoke(main, new object[] { input });

            if ("double".Equals(answerType))
            {
                Logger.LogInfo("String [{}]", (string)ans);
                try
                {
                    double ans_d = double.Parse((string)ans, new CultureInfo("en-US"));
                    double expected_d = double.Parse(ansExpected, new CultureInfo("en-US"));
                    Assert.AreEqual(expected_d, ans_d, 0.00001);
                }
                catch (System.FormatException)
                {
                    Logger.LogInfo("ERROR [{}] [{}]", (string)ans, ansExpected);
                    Assert.IsTrue(false);
                }
            }
            else
            {
                Assert.AreEqual(ansExpected, ans);
            }

        }
        private static Tuple<MethodInfo, Redirector> RedirectMethod(Type targetType, MethodInfo detour, bool reverse)
        {
            var parameters = detour.GetParameters();
            Type[] types;
            if (parameters.Length > 0 && (
                (!targetType.IsValueType && parameters[0].ParameterType == targetType) ||
                (targetType.IsValueType && parameters[0].ParameterType == targetType.MakeByRefType())))
            {
                types = parameters.Skip(1).Select(p => p.ParameterType).ToArray();
            }
            else {
                types = parameters.Select(p => p.ParameterType).ToArray();
            }

            MethodInfo originalMethod = originalMethod = targetType.GetMethod(detour.Name, MethodFlags, null, types, null);
            if (originalMethod == null && detour.Name.EndsWith("Alt"))
            {
                originalMethod = targetType.GetMethod(detour.Name.Substring(0, detour.Name.Length - 3), MethodFlags, null, types, null);
            }

            var redirector = reverse ? new Redirector(detour, originalMethod) : new Redirector(originalMethod, detour);

            redirector.Apply();

            return Tuple.New(originalMethod, redirector);
        }
Esempio n. 10
0
        private Func<Exception, IEnumerable<IResult>> CreateHandler(ActionExecutionContext context, Type targetType)
        {
            Func<Exception, IEnumerable<IResult>> handler = null;
#if SILVERLIGHT
            // you may not invoke private methods in SL
            const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
#elif WPF
            const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
#endif

            var method = targetType.GetMethod(MethodName, bindingFlags, Type.DefaultBinder, new[] { typeof(Exception) }, null)
                ?? targetType.GetMethod(MethodName, bindingFlags);

            if (method == null)
                throw new Exception(string.Format("Could not find method {0} on type {1}",
                                                  MethodName,
                                                  targetType.Name));

            var obj = method.IsStatic ? null : context.Target;
            handler = ex =>
                      {
                          var param = method.GetParameters().Any() ? new object[] { ex } : new object[0];
                          object result = method.Invoke(obj, param);

                          if (result is IResult) return new[] { result as IResult };
                          if (result is IEnumerable<IResult>) return result as IEnumerable<IResult>;

                          return new IResult[0];
                      };

            return handler;
        }
Esempio n. 11
0
 public bool CanSerialize(Type type) {
   return
     ReflectionTools.HasDefaultConstructor(type) &&
     type.GetInterface(typeof(IEnumerable).FullName) != null &&
     type.GetMethod("Add") != null &&
     type.GetMethod("Add").GetParameters().Length == 1;
 }
        static CustomizationApi()
        {
            CustomAssembly = Assembly.GetEntryAssembly();
            CUSTOM_NAMESPACE = (from t in CustomAssembly.GetExportedTypes() where t.Name == CUSTOM_BOT_CLASS_NAME select t.Namespace).FirstOrDefault();
            if (CUSTOM_NAMESPACE == null)
                LogMessage.Exit("Could not find class " + CUSTOM_BOT_CLASS_NAME + " in the entry assembly.");
            bot_type = CustomAssembly.GetType(CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME);
            if (bot_type == null)
                LogMessage.Exit("Could not find class " + CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME + " in the entry assembly.");

            try
            {
                session_creating = (Action)Delegate.CreateDelegate(typeof(Action), bot_type.GetMethod("SessionCreating", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static));
            }
            catch
            {
                Log.Main.Warning("Method " + CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME + ".SessionCreating was not found.");
            }
            try
            {
                session_closing = (Action)Delegate.CreateDelegate(typeof(Action), bot_type.GetMethod("SessionClosing", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static));
            }
            catch
            {
                Log.Main.Warning("Method " + CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME + ".SessionClosing was not found.");
            }
            try
            {
                fill_start_input_item_queue = (Action<InputItemQueue, Type>)Delegate.CreateDelegate(typeof(Action<InputItemQueue, Type>), bot_type.GetMethod("FillStartInputItemQueue", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static));
            }
            catch
            {
                Log.Main.Warning("Method " + CUSTOM_NAMESPACE + "." + CUSTOM_BOT_CLASS_NAME + ".FillStartInputItemQueue was not found.");
            }
        }
Esempio n. 13
0
 public static MethodInfo GetMethodInfo(Type type, string methodName, Type[] argsTypes)
 {
     MethodInfo methodInfo;
     //
     string cacheKey = type.FullName + ":" + methodName;
     if (argsTypes != null)
     {
         foreach (Type argType in argsTypes)
         {
             cacheKey += ":" + argType.FullName;
         }
     }
     //
     if (methodCache.TryGetValue(cacheKey, out methodInfo))
     {
         return methodInfo;
     }
     //
     lock (Locker)
     {
         MethodInfo method = null;
         if (argsTypes != null)
             method = type.GetMethod(methodName, argsTypes);
         else
             method = type.GetMethod(methodName);
         methodCache[cacheKey] = method;
         return method;
     }
 }
Esempio n. 14
0
 public MethodInfo getGetter(Type clazz, string field)
 {
     MethodInfo m = null;
     getProf.enter();
     string cacheKey = clazz.FullName.ToString() + "#get" + field;
     m = reflCache[cacheKey];
     if (m == null)
     {
         try
         {
             string name = buildMethodName("is", field);
             m = clazz.GetMethod(name);
             reflCache.Add(cacheKey, m);
         }
         catch (NoSuchMethodException e)
         {
             if (m == null)
             {
                 string name = buildMethodName("get", field);
                 m = clazz.GetMethod(name);
                 reflCache.Add(cacheKey, m);
             }
         }
     }
     getProf.exit();
     return m;
 }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    protected override void RegisterWithKey (object regKey, Type regKeyType)
    {
      // 
      // Unified registration functionality for accepting both RegistrationAttribute.Key and RegistryKey objects.
      // 

      try
      {
        MethodInfo 
          regKeySetValue = regKeyType.GetMethod ("SetValue", new [] { typeof (string), typeof (object) }),
          regKeyClose = regKeyType.GetMethod("Close");

        if (regKeySetValue == null)
        {
          throw new InvalidOperationException ();
        }

        if (regKeyClose == null)
        {
          throw new InvalidOperationException ();
        }

        regKeySetValue.Invoke (regKey, new object [] { string.Empty, m_portSupplierType.AssemblyQualifiedName });

        regKeySetValue.Invoke (regKey, new object [] { "CLSID", m_portSupplierType.GUID.ToString ("B") });

        regKeySetValue.Invoke (regKey, new object [] { "Name", m_portSupplierName });

        regKeyClose.Invoke (regKey, null);
      }
      catch (Exception e)
      {
        LoggingUtils.HandleException (e);
      }
    }
 public static System.Reflection.MethodInfo ParseLinkCommand(string cmdNm, string cmdArg, Type miType)
 {
     if (!string.IsNullOrEmpty(cmdArg))
         return miType.GetMethod(cmdNm, flags, null, new Type[] { typeof(System.Web.UI.Control), typeof(System.String[]) }, null);
     else
         return miType.GetMethod(cmdNm, flags, null, new Type[] { typeof(System.Web.UI.Control) }, null);
 }
        static JSIChatterer()
        {
            try
            {
                var loadedChattererAssy = AssemblyLoader.loadedAssemblies.FirstOrDefault(a => a.name == "Chatterer");

                if (loadedChattererAssy == null)
                {
                    chattererFound = false;

                    return;
                }

                //--- Process all the reflection info
                // MechJebCore
                chatterer_t = loadedChattererAssy.assembly.GetExportedTypes()
                    .SingleOrDefault(t => t.FullName == "Chatterer.chatterer");
                if (chatterer_t == null)
                {
                    JUtil.LogErrorMessage(null, "Did not find Chatterer.chatterer");
                    return;
                }

                MethodInfo txMethod = chatterer_t.GetMethod("VesselIsTransmitting", BindingFlags.Instance | BindingFlags.Public);
                if (txMethod == null)
                {
                    throw new NotImplementedException("txMethod");
                }
                chattererTx = DynamicMethodDelegateFactory.CreateFuncBool(txMethod);

                MethodInfo rxMethod = chatterer_t.GetMethod("VesselIsReceiving", BindingFlags.Instance | BindingFlags.Public);
                if (rxMethod == null)
                {
                    throw new NotImplementedException("rxMethod");
                }
                chattererRx = DynamicMethodDelegateFactory.CreateFuncBool(rxMethod);

                MethodInfo chatterMethod = chatterer_t.GetMethod("InitiateChatter", BindingFlags.Instance | BindingFlags.Public);
                if (chatterMethod == null)
                {
                    throw new NotImplementedException("chatterMethod");
                }
                chattererStartTalking = DynamicMethodDelegateFactory.CreateAction(chatterMethod);
            }
            catch (Exception e)
            {
                chatterer_t = null;
                JUtil.LogMessage(null, "Exception initializing JSIChatterer: {0}", e);
            }

            if (chatterer_t != null && chattererStartTalking != null)
            {
                chattererFound = true;
            }
            else
            {
                chattererFound = false;
            }
        }
Esempio n. 18
0
        static TypeGenerator()
        {
            typeInfo = Type.GetType("Microsoft.CodeAnalysis.CodeGeneration.TypeGenerator" + ReflectionNamespaces.WorkspacesAsmName, true);

            createArrayTypeSymbolMethod = typeInfo.GetMethod("CreateArrayTypeSymbol");
            createPointerTypeSymbolMethod = typeInfo.GetMethod("CreatePointerTypeSymbol");
            constructMethod = typeInfo.GetMethod("Construct");
        }
Esempio n. 19
0
 public void Complete(Type actualTravellerType)
 {
     _travellerType = actualTravellerType;
     _constructor = actualTravellerType.GetConstructor(_members.TravellerConstructorTypes);
     _travelWriteMethod = actualTravellerType.GetMethod("Travel", _travelWriteMethod.GetParameters().Select(p => p.ParameterType).ToArray());
     _travelReadMethod = actualTravellerType.GetMethod("Travel", _travelReadMethod.GetParameters().Select(p => p.ParameterType).ToArray());
     _isConstructing = false;
 }
        /// <summary>
        /// Parses a list of numbers separated by a comma. This function can also interpret ranges within the
        /// list.
        /// </summary>
        /// <param name="values">The string value representation of the list</param>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="elementType">The target element type</param>
        /// <returns>
        /// The <see cref="ICollection{T}"/> implementation of <paramref name="targetType" /> containing the parsed values
        /// </returns>
        /// <exception cref="System.ArgumentException">The given target type is not an implementation of <see cref="ICollection{T}"/>, or a parser could not 
        /// be found for the given <paramref name="elementType"/></exception>
        /// <exception cref="System.Exception"><paramref name="values"/> could not be parsed as a an implementation of <see cref="ICollection{T}"/>. See the inner exception for more details</exception>
        /// <example>"1,2,3,4,5,6,7,8,9,10"</example>
        /// <example>"1-10"</example>
        /// <example>"1,2,3-8,9,10"</example>
        internal static object ParseCollection(string[] values, Type targetType, Type elementType)
        {
            try
            {
                if(!targetType.IsGenericCollectionImplementation())
                    throw new ArgumentException($"{targetType.FullName} does not implement {typeof(ICollection<>).FullName}");

                var arr = Activator.CreateInstance(targetType);
                var parser = StringParsing.GetParser(elementType);

                if(parser == null)
                    throw new ArgumentException($"No parser could be found for element type, {elementType.FullName}");

                foreach (var value in values)
                {
                    if (value.Contains("-")) // parse range
                    {
                        var bounds = value.Split('-');
                        var range = Activator.CreateInstance(targetType);

                        // double should handle all floating and integral types, unless
                        // the type is decimal, then we need to handle decimal
                        // explicitly

                        if (elementType == typeof(decimal))
                        {
                            for (var i = (decimal)parser.Parse(bounds[0].Trim(), elementType);
                                i <= (decimal)parser.Parse(bounds[1].Trim(), elementType);
                                i++)
                                targetType.GetMethod("Add")
                                    .Invoke(range, new[] { Convert.ChangeType(i, elementType) });
                        }
                        else
                        {
                            for (var i = (double)Convert.ChangeType(parser.Parse(bounds[0].Trim(), elementType), typeof(double));
                                i <= (double)Convert.ChangeType(parser.Parse(bounds[1].Trim(), elementType), typeof(double));
                                i++)
                                targetType.GetMethod("Add")
                                    .Invoke(range, new[] { Convert.ChangeType(i, elementType) });

                        }

                        foreach (var item in (IList)range)
                            targetType.GetMethod("Add").Invoke(arr, new[] { item });
                    }
                    else
                    {
                        targetType.GetMethod("Add").Invoke(arr, new[] { parser.Parse(value, elementType) });
                    }
                }

                return arr;
            }
            catch (Exception ex)
            {
                throw new Exception($"Values could not be parsed as a {typeof(ICollection<>).FullName}. See the inner exception for more details", ex);
            }
        }
Esempio n. 21
0
        public DynamicTravellerMembers()
        {
            VisitArgsType = typeof (VisitArgs);
            VisitArgsFactoryType = typeof (IVisitArgsFactory);
            ConstructVisitArgsMethod = VisitArgsFactoryType.GetMethod("Construct");
            ConstructVisitArgsWithTypeMethod = VisitArgsFactoryType.GetMethod("ConstructWith");

            TravellerConstructorTypes = new[] {VisitArgsFactoryType};
        }
		static ICodeDefinitionFactoryExtensions ()
		{
			typeInfo = Type.GetType ("Microsoft.CodeAnalysis.Shared.Extensions.ICodeDefinitionFactoryExtensions" + ReflectionNamespaces.WorkspacesAsmName, true);
			createFieldDelegatingConstructorMethod = typeInfo.GetMethod ("CreateFieldDelegatingConstructor", BindingFlags.Static | BindingFlags.Public);
			createFieldsForParametersMethod = typeInfo.GetMethod ("CreateFieldsForParameters", BindingFlags.Static | BindingFlags.Public);
			createAssignmentStatementMethod = typeInfo.GetMethod ("CreateAssignmentStatements", BindingFlags.Static | BindingFlags.Public);
			createThrowNotImplementStatementMethod = typeInfo.GetMethod ("CreateThrowNotImplementStatement", new [] { typeof (SyntaxGenerator), typeof(Compilation) });

		}
        public object DrawAndGetNewValue(Type memberType, string memberName, object value, Entity entity, int index, IComponent component)
        {
            var elementType = memberType.GetGenericArguments()[0];
            var itemsToRemove = new ArrayList();
            var itemsToAdd = new ArrayList();
            var isEmpty = !((IEnumerable)value).GetEnumerator().MoveNext();

            EditorGUILayout.BeginHorizontal();
            {
                if (isEmpty) {
                    EditorGUILayout.LabelField(memberName, "empty");
                } else {
                    EditorGUILayout.LabelField(memberName);
                }

                if (GUILayout.Button("+", GUILayout.Width(19), GUILayout.Height(14))) {
                    object defaultValue;
                    if (EntityDrawer.CreateDefault(elementType, out defaultValue)) {
                        itemsToAdd.Add(defaultValue);
                    }
                }
            }
            EditorGUILayout.EndHorizontal();

            if (!isEmpty) {
                EditorGUILayout.Space();
                var indent = EditorGUI.indentLevel;
                EditorGUI.indentLevel = indent + 1;
                foreach (var item in (IEnumerable)value) {
                    EditorGUILayout.BeginHorizontal();
                    {
                        var newItem = EntityDrawer.DrawAndGetNewValue(elementType, string.Empty, item, entity, index, component);
                        if (EntityDrawer.DidValueChange(item, newItem)) {
                            itemsToRemove.Add(item);
                            itemsToAdd.Add(newItem);
                        }

                        if (GUILayout.Button("-", GUILayout.Width(19), GUILayout.Height(14))) {
                            itemsToRemove.Add(item);
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                }

                EditorGUI.indentLevel = indent;
            }

            foreach (var item in itemsToRemove) {
                memberType.GetMethod("Remove").Invoke(value, new [] { item });
            }

            foreach (var item in itemsToAdd) {
                memberType.GetMethod("Add").Invoke(value, new [] { item });
            }

            return value;
        }
Esempio n. 24
0
        public static void genDelegateCall(	Type			interfaceType
													,Type[]			parameters
													,MethodBuilder	methodBuilder
													,FieldInfo		invoker
													,FieldInfo		target)
        {
            ILGenerator	IL	=	methodBuilder.GetILGenerator();
            // Declare and initialize the array for passing the parameters.
            IL.DeclareLocal(typeof(object[]));		//loc.0
            IL.DeclareLocal(typeof(MethodInfo));	//loc.1
            IL.DeclareLocal(typeof(object));		//loc.2

            //If there is a return
            if(methodBuilder.ReturnType!=typeof(void))
                IL.DeclareLocal(methodBuilder.ReturnType);	//loc.3
            // Init the args array
            if(parameters==null)
            {
                IL.Emit(OpCodes.Ldnull);
                storeLocal(IL,0);
            }
            else
            {
                loadInt32(IL,parameters.Length);
                IL.Emit(OpCodes.Newarr, typeof(object));
                storeLocal(IL,0);
                // Store the parameters in the new array.
                for(int i = 0; i < parameters.Length; i++)
                {
                    loadLocal(IL,0);//Load the array reference
                    putArgInArray(IL,i, parameters[i]);
                }
            }
            // Store the methodinfo object using the Ldtoken command. Must use the interfaces MethodInfo.
            MethodInfo	mi	=	parameters==null?interfaceType.GetMethod(methodBuilder.Name):interfaceType.GetMethod(methodBuilder.Name,parameters);
            IL.Emit(OpCodes.Ldtoken,mi);
            IL.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle"));
            storeLocal(IL,1);
            IL.Emit(OpCodes.Ldarg_0);		//	Proxy (this)
            IL.Emit(OpCodes.Ldfld, target);	//	The delegate from the proxy
            storeLocal(IL,2);
            // Setup the stack for the delegate call.
            IL.Emit(OpCodes.Ldarg_0);		//	this needed for the load field opcode
            IL.Emit(OpCodes.Ldfld, invoker);//	The delegate from the proxy
            loadLocal(IL,2);
            //IL.Emit(OpCodes.Ldarg_0);		//	1st arg - Proxy (this)
            loadLocal(IL,1);				//	2nd arg - MethodInfo
            loadLocal(IL,0);				//	3rd arg - array of arguments
            IL.Emit(OpCodes.Callvirt,(typeof(Proxy.InvocationDelegate).GetMethod("Invoke")));
            emitReturnFromMethod(IL, methodBuilder.ReturnType);
            if(methodBuilder.ReturnType!=typeof(void))
            {	// Not sure I need to so this but the C# compiler seems to generate this code?
                storeLocal(IL,3);
                loadLocal(IL,3);
            }
            IL.Emit(OpCodes.Ret);
        }
 public bool HasAddMethod(Type type) {
   return
     type.GetMethod("Add") != null &&
     type.GetMethod("Add").GetParameters().Length == 1 &&
     type.GetConstructor(
       BindingFlags.Public |
       BindingFlags.NonPublic |
       BindingFlags.Instance,
       null, Type.EmptyTypes, null) != null;
 }
Esempio n. 26
0
		public static AccelMode MethodAccelerationMode (Type type, String method, Type[] signature)
		{
			MethodInfo mi = signature == null ? type.GetMethod (method) : type.GetMethod (method, signature);
			if (mi == null)
				return AccelMode.None;
			object[] attr = mi.GetCustomAttributes (typeof (AccelerationAttribute), false);
			if (attr.Length == 0)
				return AccelMode.None;
			return ((AccelerationAttribute) attr [0]).Mode;
		}
 public BuildExplorerWrapper(IBuildExplorer buildExplorer)
 {
     _buildExplorer = buildExplorer;
     _buildExplorerType = _buildExplorer.GetType();
     _addBuildDefinitionMethod = new Lazy<MethodInfo>(() => _buildExplorerType.GetMethod("AddBuildDefinition", BindingFlags.Static | BindingFlags.Public));
     _openControllerAgentManagerMethod = new Lazy<MethodInfo>(() => _buildExplorerType.GetMethod("OpenControllerAgentManager", BindingFlags.Static | BindingFlags.Public));
     _openQualityManagerMethod = new Lazy<MethodInfo>(() => _buildExplorerType.GetMethod("OpenQualityManager", BindingFlags.Static | BindingFlags.Public));
     _openBuildSecurityDialogMethod = new Lazy<MethodInfo>(() => _buildExplorerType.GetMethod("OpenBuildSecurityDialog", BindingFlags.Static | BindingFlags.Public));
     _navigateToProcessFileMethod = new Lazy<MethodInfo>(() => _buildExplorerType.GetMethod("NavigateToProcessFile", BindingFlags.Static | BindingFlags.Public));
 }
        static SortingLayerHelper()
        {
            _utilityType = Type.GetType("UnityEditorInternal.InternalEditorUtility, UnityEditor");
            _sortingLayerNamesProperty = _utilityType.GetProperty("sortingLayerNames", BindingFlags.Static | BindingFlags.NonPublic);
#if UNITY_5
            _getSortingLayerUserIdMethod = _utilityType.GetMethod("GetSortingLayerUniqueID", BindingFlags.Static | BindingFlags.NonPublic);
#else
            _getSortingLayerUserIdMethod = _utilityType.GetMethod("GetSortingLayerUserID", BindingFlags.Static | BindingFlags.NonPublic);
#endif 
        }
 protected static Metadata CreateMetadata(Type closureType, bool isAction)
 {
     var ctor = (Func<IntPtr, Object>)Delegate.CreateDelegate(typeof(Func<IntPtr, Object>), closureType.GetMethod("Create"));
     MethodInfo invoker = closureType.GetMethod(MethodName);
     MethodInfo carryingInvoker = closureType.GetMethod(CarryingMethodName);
     if (isAction)
         return new ActionMetadata(ctor, invoker, carryingInvoker);
     else
         return new FuncMetadata(ctor, invoker, carryingInvoker);
 }
Esempio n. 30
0
        public JSIParachute(Vessel _vessel)
            : base(_vessel)
        {
            try
            {
                rcModuleRealChute = AssemblyLoader.loadedAssemblies.SelectMany(
                    a => a.assembly.GetExportedTypes())
                    .SingleOrDefault(t => t.FullName == "RealChute.RealChuteModule");
                if (rcModuleRealChute == null)
                {
                    rcFound = false;
                    if (JUtil.debugLoggingEnabled)
                    {
                        JUtil.LogMessage(this, "A supported version of RealChute is {0}", (rcFound) ? "present" : "not available");
                    }
                    return;
                }

                PropertyInfo rcAnyDeployed = rcModuleRealChute.GetProperty("anyDeployed", BindingFlags.Instance | BindingFlags.Public);
                rcGetAnyDeployed = rcAnyDeployed.GetGetMethod();

                rcArmChute = rcModuleRealChute.GetMethod("GUIArm", BindingFlags.Instance | BindingFlags.Public);
                rcDisarmChute = rcModuleRealChute.GetMethod("GUIDisarm", BindingFlags.Instance | BindingFlags.Public);
                rcDeployChute = rcModuleRealChute.GetMethod("GUIDeploy", BindingFlags.Instance | BindingFlags.Public);
                rcCutChute = rcModuleRealChute.GetMethod("GUICut", BindingFlags.Instance | BindingFlags.Public);

                rcArmed = rcModuleRealChute.GetField("armed", BindingFlags.Instance | BindingFlags.Public);
            }
            catch (Exception)
            {
                rcModuleRealChute = null;
                rcGetAnyDeployed = null;
                rcArmChute = null;
                rcDisarmChute = null;
                rcDeployChute = null;
                rcCutChute = null;
                rcArmed = null;
            }

            if (rcModuleRealChute != null && rcArmChute != null &&
                rcGetAnyDeployed != null && rcDisarmChute != null && rcDeployChute != null &&
                rcCutChute != null && rcArmed != null)
            {
                rcFound = true;
            }
            else
            {
                rcFound = false;
            }

            if (JUtil.debugLoggingEnabled)
            {
                JUtil.LogMessage(this, "A supported version of RealChute is {0}", (rcFound) ? "present" : "not available");
            }
        }
Esempio n. 31
0
            public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option)
            {
                if (s_winRTFolderPathsGetFolderPath == null)
                {
                    Type?      winRtFolderPathsType = Type.GetType("System.WinRTFolderPaths, System.Runtime.WindowsRuntime, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", throwOnError: false);
                    MethodInfo?getFolderPathsMethod = winRtFolderPathsType?.GetMethod("GetFolderPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(SpecialFolder), typeof(SpecialFolderOption) }, null);
                    var        d = (Func <SpecialFolder, SpecialFolderOption, string>?)getFolderPathsMethod?.CreateDelegate(typeof(Func <SpecialFolder, SpecialFolderOption, string>));
                    s_winRTFolderPathsGetFolderPath = d ?? delegate { return(string.Empty); };
                }

                return(s_winRTFolderPathsGetFolderPath(folder, option));
            }
Esempio n. 32
0
        private bool TryGetIdentifier(string identifier, object context, out object value)
        {
            value = null;

            if (identifier == null)
            {
                return(false);
            }

            var type = context.GetType();

            try
            {
                var extension = customExtensions?.GetMethod(identifier, new[] { type });
                if (extension != null)
                {
                    value = extension.Invoke(null, new[] { context });
                    return(true);
                }

                var property = type.GetProperty(identifier);
                if (property != null)
                {
                    value = property.GetValue(context);
                    return(true);
                }

                extension = standardExtensions.GetMethod(identifier, new[] { type });
                if (extension != null)
                {
                    value = extension.Invoke(null, new[] { context });
                    return(true);
                }
            }
            catch (Exception e)
            {
                hasError = true;
                Log.Error(e.Message);
            }

            return(false);
        }
 /// <summary>
 /// This is called from the compile/run appdomain to convert objects within an expression block to a string
 /// </summary>
 public string ToStringWithCulture(object objectToConvert)
 {
     if ((objectToConvert == null))
     {
         throw new global::System.ArgumentNullException("objectToConvert");
     }
     System.Type t = objectToConvert.GetType();
     System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
         typeof(System.IFormatProvider)
     });
     if ((method == null))
     {
         return(objectToConvert.ToString());
     }
     else
     {
         return((string)(method.Invoke(objectToConvert, new object[] {
             this.formatProviderField
         })));
     }
 }
Esempio n. 34
0
        public Build(string code, string _exe)
        {
            Code = "";
            exe  = _exe;


            Code = PrepareCode(code);
            string[] lines = Code.Split('\n');
            Code = "";
            foreach (string l in lines)
            {
                Code += string.Format("Console.WriteLine(\"{0}\");\n", l);
            }
            Code = SetCode(Code);
            CSharpCodeProvider provider   = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.OutputAssembly     = _exe;
            parameters.GenerateInMemory   = true;
            parameters.GenerateExecutable = true;
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, Code);

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }
                throw new InvalidOperationException(sb.ToString());
            }
            Assembly assembly = results.CompiledAssembly;

            Debug.WriteLine(Assembly.GetExecutingAssembly().CodeBase);
            System.Type program = assembly.GetType("Clite.Program");
            MethodInfo  main    = program.GetMethod("Main");

            main.Invoke(null, null);
        }
Esempio n. 35
0
        /// <summary>
        /// Looks for .NET method
        /// </summary>
        /// <param name="generator">The IL generator.</param>
        /// <param name="callNode">The node which called the .NET static method</param>
        /// <returns>ILFunctionRef for called .NET static method.
        /// <c>null</c> - if there is no static method with this name exist in .NET framework</returns>
        public static ILFunctionRef LookForDotNetMethod(ILCodeGenerator generator, FunctionCall callNode)
        {
            string name  = callNode.Name;
            int    index = name.LastIndexOf('.');

            if (index == -1)
            {
                return(null);
            }
            string typeName   = name.Substring(0, index);
            string methodName = name.Substring(index + 1);

            System.Type type = System.Type.GetType(typeName);
            if (type == null)
            {
                type = System.Type.GetType("System." + typeName);
            }
            if (type == null)
            {
                return(null);
            }


            List <Type>         argTypes = new List <Type>();
            ExpressionGenerator g        = new ExpressionGenerator(generator);

            foreach (Expression arg in callNode)
            {
                argTypes.Add(ILTypeTranslator.Translate(g.Create(arg).Type));
            }

            MethodInfo method = type.GetMethod(methodName, argTypes.ToArray());

            if (method == null || !method.IsStatic)
            {
                return(null);
            }

            return(new ILFunctionRef(generator, method));
        }
Esempio n. 36
0
    private string[] InitializeScorerCandidateList <T>(System.Type type, SerializedProperty candidateNamesProperty)
    {
        System.Type[]      paramTypes    = new System.Type[] { typeof(MovementController) };
        IList <MemberInfo> candidateList = new List <MemberInfo>();

        string[] candidateNames;
        string[] blacklist = new string[] { "IsInvoking", "Equals", "get_useGUILayout", "get_runInEditMode", "get_enabled", "get_isActiveAndEnabled" };
        int      i         = 0;

        type.FindMembers(
            MemberTypes.Method,
            BindingFlags.Instance | BindingFlags.Public,
            (member, criteria) => {
            MethodInfo method;
            if ((method = type.GetMethod(member.Name, paramTypes)) != null &&
                method.ReturnType == typeof(T) &&
                Array.IndexOf(blacklist, method.Name) == -1)
            {
                candidateList.Add(method);
                return(true);
            }
            return(false);
        },
            null
            );

        // clear/resize/initialize storage containers
        candidateNamesProperty.ClearArray();
        candidateNamesProperty.arraySize = candidateList.Count;
        candidateNames = new string[candidateList.Count];

        // assign storage containers
        i = 0;
        foreach (SerializedProperty element in candidateNamesProperty)
        {
            element.stringValue = candidateNames[i] = candidateList[i++].Name;
        }

        return(candidateNames);
    }
Esempio n. 37
0
        /// <summary>
        /// Runs the specified example name.
        /// </summary>
        /// <param name="exampleName">Name of the example.</param>
        /// <param name="args">The arguments.</param>
        /// <exception cref="KeyNotFoundException">Thrown if the example with the specified name
        /// is not found.</exception>
        public void Run(string exampleName, IEnumerable <string> args)
        {
            SystemType codeExampleType = GetCodeExampleType(exampleName);

            if (codeExampleType != null)
            {
                Console.WriteLine($"Requested: '{exampleName}', Loaded: '" +
                                  $"{ExampleBase.GetVersionedName(codeExampleType)}'.");
            }
            else
            {
                throw new KeyNotFoundException($"Code example not found: '{exampleName}'.");
            }

            MethodBase method = codeExampleType.GetMethod("Main",
                                                          BindingFlags.Static | BindingFlags.Public);

            if (method == null)
            {
                throw new MissingMethodException($"Main method not found in example: " +
                                                 $"'{exampleName}'.");
            }
            try
            {
                method.Invoke(null, new object[] { args.ToArray() });
            }
            catch (Exception e)
            {
                StackTrace stackTrace = new StackTrace(e.InnerException);
                StackFrame frame      = stackTrace.GetFrame(0);
                if (frame.GetMethod() == method)
                {
                    // The site of the exception was the main method itself. So there was an error
                    // calling the Run() method, typically due to argument errors.
                    throw new ArgumentException("Could not call the Run() method from Main(). " +
                                                "Check your arguments.");
                }
                throw e.InnerException;
            }
        }
Esempio n. 38
0
        /// <summary>
        /// Are given objects equal when using type specific equality checks
        /// </summary>
        internal static bool IsEqual(object x, object y, System.Type t)
        {
            // if only one object is null then they are not equal
            if ((x == null && y != null) || (x != null && y == null))
            {
                return(false);
            }
            // if both are null then consider equal
            if (x == null && y == null)
            {
                return(true);
            }
            // if both objects are empty arrays then consider equal
            if (t.IsSubclassOf(typeof(Array)))
            {
                if (EqualCount(t, x, y, 0, "Length"))
                {
                    return(true);
                }
            }
            else if (t.ImplementsInterface(typeof(System.Collections.ICollection)))
            {
                if (EqualCount(t, x, y, 0, "Count"))
                {
                    return(true);
                }
            }
            MethodInfo equals = t.GetMethod("Equals", new System.Type[] { t });

            if (equals != null)
            {
                // call type-specific equality check
                return((bool)equals.Invoke(x, new object[] { y }));
            }
            else
            {
                // call generic object equality check
                return(x.Equals(y));
            }
        }
Esempio n. 39
0
        } //end of method

        private static object RunMethod(System.Type t, string
                                        strMethod, object objInstance, object[] aobjParams, BindingFlags eFlags)
        {
            MethodInfo m;

            try
            {
                m = t.GetMethod(strMethod, eFlags);
                if (m == null)
                {
                    throw new ArgumentException("There is no method '" +
                                                strMethod + "' for type '" + t.ToString() + "'.");
                }

                object objRet = m.Invoke(objInstance, aobjParams);
                return(objRet);
            }
            catch
            {
                throw;
            }
        } //end of method
Esempio n. 40
0
        protected override bool TryConvertMap(IReferenceMap referenceMap, TypeReference elementTypeInstance, object value, out object result)
        {
            if (value == null || (value as JToken)?.Type == JTokenType.Null)
            {
                result = null;
                return(true);
            }

            if (value is JObject jsonObject)
            {
                System.Type elementType    = _types.GetFrameworkType(elementTypeInstance, false);
                System.Type dictionaryType = typeof(Dictionary <,>).MakeGenericType(typeof(string), elementType);

                ConstructorInfo dictionaryConstructor = dictionaryType.GetConstructor(new System.Type[] { });
                MethodInfo      dictionaryAddMethod   = dictionaryType.GetMethod("Add", new System.Type[] { typeof(string), elementType });
                object          dictionary            = dictionaryConstructor.Invoke(new object[] { });

                if (jsonObject.ContainsKey("$jsii.map"))
                {
                    jsonObject = (JObject)jsonObject["$jsii.map"];
                }

                foreach (JProperty property in jsonObject.Properties())
                {
                    if (!TryConvert(elementTypeInstance, elementType, referenceMap, property.Value, out object convertedElement))
                    {
                        throw new ArgumentException("Could not convert all elements of map", nameof(value));
                    }

                    dictionaryAddMethod.Invoke(dictionary, new object[] { property.Name, convertedElement });
                }

                result = dictionary;
                return(true);
            }

            result = null;
            return(false);
        }
Esempio n. 41
0
            public static void StopClip(AudioClip clip)
            {
                Assembly unityEditorAssembly = typeof(AudioImporter).Assembly;

                System.Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
                MethodInfo  method         = audioUtilClass.GetMethod(
                    "StopClip",
                    BindingFlags.Static | BindingFlags.Public,
                    null,
                    new System.Type[] {
                    typeof(AudioClip)
                },
                    null
                    );

                method.Invoke(
                    null,
                    new object[] {
                    clip
                }
                    );
            }
Esempio n. 42
0
        static JsiiMethodAttribute GetMethodAttributeCore(System.Type type, string methodName, System.Type[] parameterTypes, BindingFlags bindingFlags)
        {
            methodName     = methodName ?? throw new ArgumentNullException(nameof(methodName));
            type           = type ?? throw new ArgumentNullException(nameof(type));
            parameterTypes = parameterTypes ?? throw new ArgumentException(nameof(parameterTypes));

            MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags, null, parameterTypes, new ParameterModifier[0]);

            if (methodInfo == null)
            {
                throw new ArgumentException($"Method {methodName} does not exist", nameof(methodName));
            }

            JsiiMethodAttribute methodAttribute = methodInfo.GetCustomAttribute <JsiiMethodAttribute>();

            if (methodAttribute == null)
            {
                throw new ArgumentException($"Method {methodName} is missing JsiiMethodAttribute", nameof(methodName));
            }

            return(methodAttribute);
        }
Esempio n. 43
0
 private static bool IsMethodOverridden(System.Type clazz, System.String name, System.Type[] params_Renamed)
 {
     try
     {
         System.Reflection.MemberInfo mi = clazz.GetMethod(name, params_Renamed);
         if (mi == null)
         {
             throw new SystemException("Can not find method \"" + name + "\"");
         }
         return(mi.DeclaringType != typeof(Similarity));
         //return clazz.GetMethod(name, (params_Renamed == null) ? new System.Type[0] : (System.Type[])params_Renamed).DeclaringType != typeof(Similarity);
     }
     catch (System.MethodAccessException e)
     {
         // should not happen
         throw new System.SystemException(e.Message, e);
     }
     catch (Exception ex)
     {
         throw new SystemException(ex.Message);
     }
 }
        internal static void SwitchToCPUView(EditorWindow profilerWindow)
        {
#if UNITY_2019_3_OR_NEWER
            var profiler          = (ProfilerWindow)profilerWindow;
            var cpuProfilerModule = profiler.GetProfilerModule <CPUProfilerModule>(ProfilerArea.CPU);
            cpuProfilerModule.ViewType = ProfilerViewType.Hierarchy;

            /*
             #elif UNITY_2019_3
             * GetCpuModule(profilerWindow, out var cpuModuleType, out var cpuModule);
             * var ViewTypeProperty = cpuModuleType.GetProperty("ViewType", BindingFlags.Instance | BindingFlags.NonPublic);
             * var viewType = GetUnityEditorType("ProfilerViewType");
             * var viewTypeHierarchy = viewType.GetEnumValues().GetValue(0);
             * ViewTypeProperty.SetValue(cpuModule,viewTypeHierarchy);
             */
#else
            var CPUOrGPUViewTypeChanged = m_ProfilerWindowType.GetMethod("CPUOrGPUViewTypeChanged", BindingFlags.NonPublic | BindingFlags.Instance);
            var viewType          = GetUnityEditorType("ProfilerViewType");
            var viewTypeHierarchy = viewType.GetEnumValues().GetValue(0);
            CPUOrGPUViewTypeChanged.Invoke(profilerWindow, new object[] { viewTypeHierarchy });
#endif
        }
Esempio n. 45
0
        public static MethodInfo GetSubImplMethod(this System.Type type, string methodName, ref HashSet <Type> exclude)
        {
            MethodInfo method = type.GetMethod(methodName);

            if (method != null)
            {
                return(method);
            }
            foreach (var parent_type in type.GetInterfaces())
            {
                if (!exclude.Contains(parent_type))
                {
                    exclude.Add(parent_type);
                    method = parent_type.GetSubImplMethod(methodName, ref exclude);
                    if (method != null)
                    {
                        break;
                    }
                }
            }
            return(method);
        }
Esempio n. 46
0
        public void Write(object value)
        {
            string stringValue;

            if ((value == null))
            {
                throw new global::System.ArgumentNullException("value");
            }
            System.Type t = value.GetType();
            System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
                typeof(System.IFormatProvider)
            });
            if ((method == null))
            {
                stringValue = value.ToString();
            }
            else
            {
                stringValue = ((string)(method.Invoke(value, new object[] { System.Globalization.CultureInfo.InvariantCulture })));
            }
            WriteLiteral(stringValue);
        }
Esempio n. 47
0
    public static void ClearTheConsole()
    {
        Assembly assembly = Assembly.GetAssembly(typeof(UnityEditor.SceneView));

        //Debug.Log(assembly.FullName);

        System.Type type = assembly.GetType("UnityEditor.LogEntries");
        //Debug.Log(type.Name);
        MethodInfo method = type.GetMethod("Clear");

        method.Invoke(null, null);

        //System.Type[] types = assembly.GetTypes();
        //foreach (Type t in types) {
        //    Debug.Log(t.FullName);
        //}

        //System.Reflection.MethodInfo[] mehthods = type.GetMethods();
        //foreach (MethodInfo m in mehthods) {
        //    Debug.Log(m.Name);
        //}
    }
Esempio n. 48
0
        static StackObject *GetMethod_4(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.BindingFlags @bindingAttr = (System.Reflection.BindingFlags) typeof(System.Reflection.BindingFlags).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String @name = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Type instance_of_this_method = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetMethod(@name, @bindingAttr);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Esempio n. 49
0
 public static object ParseBlock(object obj, string subBlock, object[] param = null)
 {
     Debug.Log("ParseBlock:" + obj + " " + subBlock);
     if (obj == null)
     {
         System.Type type = System.Type.GetType(subBlock);
         return(Activator.CreateInstance(type));
     }
     else
     {
         System.Type type = obj.GetType();
         subBlock = subBlock.Replace("()", "");
         MethodInfo method = type.GetMethod(subBlock);
         if (method != null)
         {
             return(method.Invoke(obj, param));
         }
         else
         {
             FieldInfo field = type.GetField(subBlock);
             if (field != null)
             {
                 return(field.GetValue(obj));
             }
             else
             {
                 PropertyInfo property = type.GetProperty(subBlock);
                 if (property != null)
                 {
                     return(field.GetValue(obj));
                 }
                 else
                 {
                 }
             }
         }
     }
     return(null);
 }
Esempio n. 50
0
        System.Reflection.MethodInfo GetPaneMethod(string methodName, object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            System.Type t = obj.GetType();

            System.Reflection.MethodInfo method = null;
            while (t != null)
            {
                method = t.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                if (method != null)
                {
                    return(method);
                }

                t = t.BaseType;
            }
            return(null);
        }
Esempio n. 51
0
 public override void UpdateTime(GameObject actor, float runningTime, float deltaTime)
 {
     if (EffectObj != null)
     {
         float factor = 0;
         if (duration > 0)
         {
             factor = ((float)runningTime) / duration;
         }
         if (path != null)
         {
             if (path is FollowSkillPath)
             {
                 FollowSkillPath fpath = (FollowSkillPath)path;
                 if (fpath.targetType == FollowTargetType.SELF)
                 {
                     fpath.targetObj = actor.transform;
                 }
             }
             path.UpdatePath(EffectObj.transform, factor);
         }
         if (ParticleRoot == null)
         {
             ParticleRoot = EffectObj.transform;
         }
         if (ParticleSys != null)
         {
             for (int i = 0; i < ParticleSys.Length; i++)
             {
                 UnityEditor.SceneView.RepaintAll();
                 System.Type t  = System.Type.GetType("UnityEditor.GameView,UnityEditor.dll");
                 var         mm = t.GetMethod("RepaintAll", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                 mm.Invoke(null, null);
                 ParticleSys[i].Simulate(deltaTime, true, false);
             }
         }
     }
 }
Esempio n. 52
0
        public void ProcessRequest(HttpContext context)
        {
            string methodStr = context.Request["action"] == null ? context.Request.QueryString["action"] : context.Request["action"];

            if (!string.IsNullOrEmpty(methodStr))
            {
                System.Type t = this.GetType();
                try
                {
                    MethodInfo method = t.GetMethod(methodStr.Trim());

                    ParameterInfo[] paramsInfo = method.GetParameters();//得到指定方法的参数列表
                    object[]        parameters = new object[paramsInfo.Length];
                    for (int i = 0; i < paramsInfo.Length; i++)
                    {
                        Type tType = paramsInfo[i].ParameterType;
                        //如果它是值类型,或者String
                        if (tType.Equals(typeof(string)) || (!tType.IsInterface && !tType.IsClass))
                        {
                            //改变参数类型
                            parameters[i] = Convert.ChangeType(context.Request[paramsInfo[i].Name], tType);
                        }
                    }
                    object obj = Activator.CreateInstance(t);

                    method.Invoke(obj, parameters);
                }
                catch (Exception ex)
                {
                    //throw (ex);
                    HttpContext.Current.Response.Write(@"{""result"":""fail"",""Message"":""方法调用失败,方法不存在或参数异常。""}");
                }
                finally
                {
                    context.Response.End();
                }
            }
        }
Esempio n. 53
0
 public void AddMenuItems(SerializedProperty property, GenericMenu menu)
 {
     // ISSUE: object of a compiler-generated type is created
     // ISSUE: variable of a compiler-generated type
     PropertyHandler.\u003CAddMenuItems\u003Ec__AnonStoreyAE itemsCAnonStoreyAe = new PropertyHandler.\u003CAddMenuItems\u003Ec__AnonStoreyAE();
     // ISSUE: reference to a compiler-generated field
     itemsCAnonStoreyAe.property = property;
     // ISSUE: reference to a compiler-generated field
     itemsCAnonStoreyAe.\u003C\u003Ef__this = this;
     if (this.contextMenuItems == null)
     {
         return;
     }
     // ISSUE: reference to a compiler-generated field
     System.Type type = itemsCAnonStoreyAe.property.serializedObject.targetObject.GetType();
     using (List <ContextMenuItemAttribute> .Enumerator enumerator = this.contextMenuItems.GetEnumerator())
     {
         while (enumerator.MoveNext())
         {
             ContextMenuItemAttribute current = enumerator.Current;
             // ISSUE: object of a compiler-generated type is created
             // ISSUE: variable of a compiler-generated type
             PropertyHandler.\u003CAddMenuItems\u003Ec__AnonStoreyAF itemsCAnonStoreyAf = new PropertyHandler.\u003CAddMenuItems\u003Ec__AnonStoreyAF();
             // ISSUE: reference to a compiler-generated field
             itemsCAnonStoreyAf.\u003C\u003Ef__ref\u0024174 = itemsCAnonStoreyAe;
             // ISSUE: reference to a compiler-generated field
             itemsCAnonStoreyAf.\u003C\u003Ef__this = this;
             // ISSUE: reference to a compiler-generated field
             itemsCAnonStoreyAf.method = type.GetMethod(current.function, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
             // ISSUE: reference to a compiler-generated field
             if (itemsCAnonStoreyAf.method != null)
             {
                 // ISSUE: reference to a compiler-generated method
                 menu.AddItem(new GUIContent(current.name), false, new GenericMenu.MenuFunction(itemsCAnonStoreyAf.\u003C\u003Em__1F9));
             }
         }
     }
 }
 public static void HelicopterDestroy(Thing thing, DestroyMode mode = DestroyMode.Vanish)
 {
     if (!Thing.allowDestroyNonDestroyable && !thing.def.destroyable)
     {
         Log.Error("Tried to destroy non-destroyable thing " + (object)thing, false);
     }
     else if (thing.Destroyed)
     {
         Log.Error("Tried to destroy already-destroyed thing " + (object)thing, false);
     }
     else
     {
         bool spawned = thing.Spawned;
         Map  map     = thing.Map;
         if (thing.Spawned)
         {
             thing.DeSpawn(mode);
         }
         System.Type type  = typeof(Thing);
         FieldInfo   field = type.GetField("mapIndexOrState", BindingFlags.Instance | BindingFlags.NonPublic);
         sbyte       num   = -2;
         field.SetValue((object)thing, (object)num);
         if (thing.def.DiscardOnDestroyed)
         {
             thing.Discard(false);
         }
         if (thing.holdingOwner != null)
         {
             thing.holdingOwner.Notify_ContainedItemDestroyed(thing);
         }
         type.GetMethod("RemoveAllReservationsAndDesignationsOnThis", BindingFlags.Instance | BindingFlags.NonPublic).Invoke((object)thing, (object[])null);
         if (thing is Pawn)
         {
             return;
         }
         thing.stackCount = 0;
     }
 }
        /// <summary>
        /// Parses the RPC exception into a <see cref="AdsBaseException" />.
        /// </summary>
        /// <param name="rpcException">The RPC exception.</param>
        /// <returns>The parsed exception, or a null if the parsing cannot be done.</returns>
        internal static AdsBaseException ParseRpcException <TResponse>(RpcException rpcException)
        {
            if (rpcException == null)
            {
                return(null);
            }

            System.Type exceptionType = FindAdsExceptionType <TResponse>(rpcException);

            if (exceptionType == null)
            {
                return(null);
            }
            MethodInfo methodInfo = exceptionType.GetMethod("Create",
                                                            BindingFlags.Public | BindingFlags.Static);

            if (methodInfo == null)
            {
                return(null);
            }
            return(methodInfo.Invoke(null, new object[] { rpcException })
                   as AdsBaseException);
        }
Esempio n. 56
0
        //辅助方法:调用其他类的私有方法
        //InstanceClass:类的实例,Params:方法的参数实例
        public object InvokePMethod(System.Type Type, string MethodName, object InstanceClass, object[] Params)
        {
            //发现方法的属性 (Attribute) 并提供对方法元数据的访问(摘自:MSDN)
            //这里方法的属性指方法的static,virtual,final等修饰,方法的参数,方法的返回值等详细信息
            //最重要一点是通过MethodInfo可以调用方法(invoke)
            MethodInfo Method;

            //指定被搜索成员的类型,NonPublic表示搜索非公有成员,Instance表示搜索实例成员(非static)
            //所以下面这句表示搜索类型为非公有的实例成员
            BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;

            //Type为System.Reflection功能的根,也是访问元数据的主要方式。(摘自:MSDN)
            //使用Type的成员获取关于类型声明的信息,如构造函数、方法、字段、属性 (Property) 
            //和类的事件,以及在其中部署该类的模块和程序集。(摘自:MSDN)
            //Type是.net中反射的根源,就如java中的Class类.如果连类都没有,那么调用方法,得到属性,一切都无从入手.
            //GetMethod:通过方法名和搜索方式得MethodInfo
            Method = Type.GetMethod(MethodName, flags);

            //调用private方法:参数分别为类的实例和方法参数
            object result = Method.Invoke(InstanceClass, Params);

            return(result);
        }
Esempio n. 57
0
 /// <summary>
 /// Determine if the specified <see cref="System.Type"/> overrides the
 /// implementation of GetHashCode from <see cref="Object"/>
 /// </summary>
 /// <param name="clazz">The <see cref="System.Type"/> to reflect.</param>
 /// <returns><c>true</c> if any type in the hierarchy overrides GetHashCode().</returns>
 public static bool OverridesGetHashCode(System.Type clazz)
 {
     try
     {
         MethodInfo getHashCode = clazz.GetMethod("GetHashCode", new System.Type[0]);
         if (getHashCode == null)
         {
             return(false);
         }
         else
         {
             // make sure that the DeclaringType is not System.Object - if that is the
             // declaring type then there is no override.
             return(!getHashCode.DeclaringType.Equals(typeof(object)));
         }
     }
     catch (AmbiguousMatchException)
     {
         // an ambigious match means that there is an override and it
         // can't determine which one to use.
         return(true);
     }
 }
Esempio n. 58
0
        private static IEnumerable<MethodInfo> GetHarmonyMethod(MethodInfo ctx, string typeName, int skipParams, string name) {
            System.Type type = GetHarmonyType(typeName);
            if (type == null)
                return null;

            if (string.IsNullOrEmpty(name))
                name = ctx.Name;

            if (skipParams < 0)
                return type
                    .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
                    .Where(method => method.Name == name);

            return new MethodInfo[] {
                type.GetMethod(
                    name,
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
                    null,
                    ctx.GetParameters().Skip(skipParams).Select(p => p.ParameterType).ToArray(),
                    null
                )
            };
        }
Esempio n. 59
0
        public override bool Compile(DNET_EXECUTABLE_GENERATION_CONTEXT cont)
        {
            exp1.Compile(cont);
            System.Type typ        = Type.GetType("System.Console");
            Type[]      Parameters = new Type[1];

            TYPE_INFO tdata = exp1.get_type();

            if (tdata == TYPE_INFO.TYPE_STRING)
            {
                Parameters[0] = typeof(string);
            }
            else if (tdata == TYPE_INFO.TYPE_NUMERIC)
            {
                Parameters[0] = typeof(double);
            }
            else
            {
                Parameters[0] = typeof(bool);
            }
            cont.CodeOutput.Emit(OpCodes.Call, typ.GetMethod("WriteLine", Parameters));
            return(true);
        }
Esempio n. 60
0
    private static MethodInfo getMethod(System.Type type, string name, System.Type[] paramTypes)
    {
        // NOTE: There is a bug in Unity 4.3.3+ on Windows Phone that causes all reflection
        // method overloads that take a BindingFlags parameter to throw a runtime exception.
        // This means that we cannot have 100% compatibility between Unity 4.3.3 and prior
        // versions on the Windows Phone platform, and that some functionality
        // will unfortunately be lost.

#if UNITY_EDITOR || !UNITY_WP8
        var method = type.GetMethod(
            name,
            BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
            null,
            paramTypes,
            null
            );

        return(method);
#else
        var methods = type.GetMethods();
        for (int i = 0; i < methods.Length; i++)
        {
            var info = methods[i];
            if (info.IsStatic || info.Name != name)
            {
                continue;
            }

            if (matchesParameterTypes(info, paramTypes))
            {
                return(info);
            }
        }

        return(null);
#endif
    }