コード例 #1
0
    MemberInfo[] GetStateCandidates(System.Type type)
    {
        List <MemberInfo> member_info_list = new List <MemberInfo>();

        member_info_list.AddRange(type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.NonPublic, (a, b) => MatchStateCandidate(a, b, type), null));

        return(member_info_list.ToArray());
    }
コード例 #2
0
 private static MemberInfo FindMember(Type t, string name, MemberTypes types)
 {
     return t
         .FindMembers(types, BindingFlags.Instance | BindingFlags.Public, Type.FilterNameIgnoreCase, name)
         .OrderByDescending(x => x.Name == name)
         .ThenByDescending(x => x.MemberType == MemberTypes.Property)
         .FirstOrDefault();
 }
コード例 #3
0
 public static bool IsNativelyScrolled(Type widgettype)
 {
     MemberInfo[] infos = widgettype.FindMembers(
         MemberTypes.Event,
         BindingFlags.Instance | BindingFlags.Public,
         SignalFilter,
         "set_scroll_adjustment");
     return infos.Length > 0;
 }
コード例 #4
0
    public string[] RepopulateCandidateList(SerializedProperty targetProperty, SerializedProperty candidateNamesProperty,
                                            SerializedProperty indexProperty, SerializedProperty propepty)
    {
        System.Type type = targetProperty.objectReferenceValue.GetType();
        if (targetProperty.objectReferenceValue is GameObject)
        {
            var obj = targetProperty.objectReferenceValue as GameObject;
            var script = obj.GetComponent<MonoBehaviour>();
            targetProperty.objectReferenceValue = script;
            type = script.GetType();
        }
        System.Type[] paramTypes = propepty.Deserilase<Type[]>("_paramsTypeData");
        System.Type returnType = propepty.Deserilase<Type>("_returnTypeData");
        IList<MemberInfo> candidateList = new List<MemberInfo>();
        string[] candidateNames;
        int i = 0;
        Debug.Log("Candidate Criteria:");
        Debug.Log("\treturn type:" + returnType.ToString());
        Debug.Log("\tparam count:" + paramTypes.Length);
        foreach (System.Type paramType in paramTypes)
            Debug.Log("\t\t" + paramType.ToString());

        type.FindMembers(
            MemberTypes.Method,
            BindingFlags.Instance | BindingFlags.Public,
            (member, criteria) =>
            {
                //  Debug.Log("matching " + member.Name);
                MethodInfo method;
                if ((method = type.GetMethod(member.Name, paramTypes)) != null && method.ReturnType == returnType)
                {
                    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;
        }

        // reset popup index
        indexProperty.intValue = 0;

        return candidateNames;
    }
コード例 #5
0
ファイル: ButtonActionDrawer.cs プロジェクト: MUDV587/Maroon
    public string[] RepopulateCandidateList(
        SerializedProperty targetProperty,
        SerializedProperty candidateNamesProperty,
        SerializedProperty indexProperty
        )
    {
        System.Type        type          = targetProperty.objectReferenceValue.GetType();
        System.Type[]      paramTypes    = this.paramTypes;
        IList <MemberInfo> candidateList = new List <MemberInfo>();

        string[] candidateNames;
        int      i = 0;

        Debug.Log("Candidate Criteria:");
        Debug.Log("\treturn type:" + returnType.ToString());
        Debug.Log("\tparam count:" + paramTypes.Length);
        foreach (System.Type paramType in paramTypes)
        {
            Debug.Log("\t\t" + paramType.ToString());
        }

        type.FindMembers(
            MemberTypes.Method,
            BindingFlags.Instance | BindingFlags.Public,
            (member, criteria) =>
        {
            Debug.Log("matching " + member.Name);
            MethodInfo method;
            if ((method = type.GetMethod(member.Name, paramTypes)) != null && method.ReturnType == returnType)
            {
                candidateList.Add(method);
                return(true);
            }
            return(false);
        },
            null
            );

        // clear/resize/initalize 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;
        }

        // reset popup index
        indexProperty.intValue = 0;

        return(candidateNames);
    }
コード例 #6
0
        /// <summary>
        /// Gets the member representing the id if one exists.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        protected MemberInfo GetMember(Type type)
        {
            var foundMembers = type.FindMembers(_memberTypes, _bindingFlags, IsMatch, null);

            if (foundMembers.Length == 0)
                return null;
            if (foundMembers.Length == 1)
                return foundMembers[0];

            //Todo: use custom exception
            throw new Exception("Too many members found matching the criteria.");
        }
コード例 #7
0
        // Everything below came from the Gtk# source:
        public static Type ConvertSignal(Type widgetType, string gladeName)
        {
            //Console.WriteLine("ConvertSignal: " + widgetType.ToString() + " " + gladeName);
            System.Reflection.MemberFilter signalFilter = new System.Reflection.MemberFilter (SignalFilter);
            System.Reflection.MemberInfo[] evnts = widgetType.
                                        FindMembers (System.Reflection.MemberTypes.Event,
                                             System.Reflection.BindingFlags.Instance
                                             | System.Reflection.BindingFlags.Static
                                             | System.Reflection.BindingFlags.Public
                                             | System.Reflection.BindingFlags.NonPublic,
                                             signalFilter, gladeName);

            return (evnts[0] as EventInfo).EventHandlerType;
        }
コード例 #8
0
ファイル: MetadataUtil.cs プロジェクト: radiy/boo
        public static MemberInfo[] GetClrExtensions(Type type, string memberName)
        {
            if (!HasClrExtensions()) return NoExtensions;

            MemberInfo[] members = null;
            if (!_clrExtensionsMembers.TryGetValue(type, out members))
            {
                if (!IsAttributeDefined(type, Types.ClrExtensionAttribute))
                {
                    _clrExtensionsMembers.Add(type, NoExtensions);
                }
                else
                {
                    members = type.FindMembers(MemberTypes.Method, BindingFlags.Public | BindingFlags.Static, ClrExtensionFilter, memberName);
                    _clrExtensionsMembers.Add(type, members);
                }
            }
            return members ?? NoExtensions;
        }
コード例 #9
0
        public TypeInfo(System.String tyName)
        {
            m_type = TypeInfo.GetType(tyName);

            if (m_type != null) {
              if (m_type.IsInterface) {
                m_members = m_type.GetMethods();
              } else {
                m_members =
                  m_type.FindMembers(
                         System.Reflection.MemberTypes.All,
                         System.Reflection.BindingFlags.DeclaredOnly |
                         System.Reflection.BindingFlags.Instance |
                         System.Reflection.BindingFlags.Public |
                         System.Reflection.BindingFlags.Static,
                         new System.Reflection.MemberFilter(myFilter),
                         null);
              }
            }
        }
コード例 #10
0
    private string[] InitializeActionCandidateList(System.Type type, SerializedProperty candidateNamesProperty)
    {
        System.Type[]      paramTypes_1  = new System.Type[] { typeof(MovementController) };
        System.Type[]      paramTypes_2  = new System.Type[] { typeof(MovementController), typeof(UtilityAction) };
        IList <MemberInfo> candidateList = new List <MemberInfo>();

        string[] candidateNames;
        string[] blacklist = new string[] { "AddAction", "CancelInvoke", "StopAllCoroutines" };
        int      i         = 0;

        type.FindMembers(
            MemberTypes.Method,
            BindingFlags.Instance | BindingFlags.Public,
            (member, criteria) => {
            MethodInfo method;
            if (((method = type.GetMethod(member.Name, paramTypes_1)) != null || (method = type.GetMethod(member.Name, paramTypes_2)) != null) &&
                (method.ReturnType == typeof(void) || method.ReturnType == typeof(IEnumerator)) &&
                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);
    }
コード例 #11
0
ファイル: ReflectedOptions.cs プロジェクト: deveel/deveel-cli
        public static Options CreateFromType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            //if (!Attribute.IsDefined(type, typeof(OptionsAttribute)))
            //	throw new ArgumentException("The type '" + type + "' is not marked as options");

            MemberInfo[] members = type.FindMembers(MemberTypes.Field | MemberTypes.Property,
                                                    BindingFlags.Public | BindingFlags.Instance,
                                                    FilterMember, null);

            var groups = new Dictionary<string, OptionGroup>();
            var requiredGroups = new List<string>();

            Attribute[] groupsAttrs = Attribute.GetCustomAttributes(type, typeof(OptionGroupAttribute));
            foreach (OptionGroupAttribute groupAttr in groupsAttrs) {
                OptionGroup group;
                if (!groups.TryGetValue(groupAttr.Name, out @group)) {
                    @group = new OptionGroup {IsRequired = groupAttr.IsRequired};
                    groups[groupAttr.Name] = @group;
                    if (groupAttr.IsRequired)
                        requiredGroups.Add(groupAttr.Name);
                }
            }

            var options = new Options();

            foreach (MemberInfo member in members) {
                Option option = CreateOptionFromMember(member, groups);
                if (option != null)
                    options.AddOption(option);
            }

            foreach(var entry in groups) {
                var group = entry.Value;
                options.AddOptionGroup(group);
            }

            return options;
        }
コード例 #12
0
ファイル: ReflectionCache.cs プロジェクト: apboyle/ironruby
        /// <summary>
        /// Gets a singleton method group from the provided type.
        /// 
        /// The provided method group will be unique based upon the methods defined, not based upon the type/name
        /// combination.  In other words calling GetMethodGroup on a base type and a derived type that introduces
        /// no new methods under a given name will result in the same method group for both types.
        /// </summary>
        public static MethodGroup GetMethodGroup(Type type, string name, BindingFlags bindingFlags, MemberFilter filter) {
            ContractUtils.RequiresNotNull(type, "type");
            ContractUtils.RequiresNotNull(name, "name");

            MemberInfo[] mems = type.FindMembers(MemberTypes.Method,
                bindingFlags,
                filter ?? delegate(MemberInfo mem, object filterCritera) {
                    return mem.Name == name;
                },
                null);

            MethodGroup res = null;
            if (mems.Length != 0) {
                MethodInfo[] methods = ArrayUtils.ConvertAll<MemberInfo, MethodInfo>(
                    mems,
                    delegate(MemberInfo x) { return (MethodInfo)x; }
                );
                res = GetMethodGroup(name, methods);
            }
            return res;
        }
コード例 #13
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);
    }
コード例 #14
0
		/// <summary>
		/// Finds the type of the method on target.
		/// </summary>
		/// <param name="methodOnInterface">The method on interface.</param>
		/// <param name="proxyTargetType">Type of the proxy target.</param>
		/// /// <param name="checkMixins">if set to <c>true</c> will check implementation on mixins.</param>
		/// <returns></returns>
		protected MethodInfo FindMethodOnTargetType(MethodInfo methodOnInterface, Type proxyTargetType, bool checkMixins)
		{
			// The code below assumes that the target
			// class uses the same generic arguments
			// as the interface generic arguments

			MemberInfo[] members = proxyTargetType.FindMembers(MemberTypes.Method,
			                                                   BindingFlags.Public | BindingFlags.Instance,
			                                                   delegate(MemberInfo mi, object criteria)
			                                                   	{
			                                                   		if (mi.Name != criteria.ToString()) return false;

			                                                   		MethodInfo methodInfo = (MethodInfo) mi;

			                                                   		return IsEquivalentMethod(methodInfo, methodOnInterface);
			                                                   	}, methodOnInterface.Name);


			if (members.Length == 0)
			{
				// Before throwing an exception, we look for an explicit
				// interface method implementation

				MethodInfo[] privateMethods =
					MethodFinder.GetAllInstanceMethods(proxyTargetType, BindingFlags.NonPublic | BindingFlags.Instance);

				foreach(MethodInfo methodInfo in privateMethods)
				{
					// We make sure it is a method used for explicit implementation

					if (!methodInfo.IsFinal || !methodInfo.IsVirtual || !methodInfo.IsHideBySig)
					{
						continue;
					}

					if (IsEquivalentMethod(methodInfo, methodOnInterface))
					{
						throw new GeneratorException(String.Format("DynamicProxy cannot create an interface (with target) " +
						                                           "proxy for '{0}' as the target '{1}' has an explicit implementation of one of the methods exposed by the interface. " +
						                                           "The runtime prevents use from invoking the private method on the target. Method {2}",
						                                           methodOnInterface.DeclaringType.Name, methodInfo.DeclaringType.Name,
						                                           methodInfo.Name));
					}
				}
			}

			if (members.Length > 1)
			{
				throw new GeneratorException("Found more than one method on target " + proxyTargetType.FullName + " matching " +
				                             methodOnInterface.Name);
			}
			else if (members.Length == 0)
			{
				if (checkMixins && IsMixinMethod(methodOnInterface))
				{
					return FindMethodOnTargetType(methodOnInterface, method2MixinType[methodOnInterface], false);
				}
				throw new GeneratorException("Could not find a matching method on " + proxyTargetType.FullName + ". Method " + methodOnInterface.Name);
			}

			return (MethodInfo) members[0];
		}
コード例 #15
0
        private ITransactionAttribute computeTransactionAttribute(MethodInfo method, Type targetType)
        {
            MethodInfo specificMethod;
            if (targetType == null)
            {
                specificMethod = method;
            }
            else
            {
                ParameterInfo[] parameters = method.GetParameters();

                ComposedCriteria searchCriteria = new ComposedCriteria();
                searchCriteria.Add(new MethodNameMatchCriteria(method.Name));
                searchCriteria.Add(new MethodParametersCountCriteria(parameters.Length));
#if NET_2_0
                searchCriteria.Add(new MethodGenericArgumentsCountCriteria(
                    method.GetGenericArguments().Length));
#endif
                searchCriteria.Add(new MethodParametersCriteria(ReflectionUtils.GetParameterTypes(parameters)));

                MemberInfo[] matchingMethods = targetType.FindMembers(
                    MemberTypes.Method,
                    BindingFlags.Instance | BindingFlags.Public,
                    new MemberFilter(new CriteriaMemberFilter().FilterMemberByCriteria),
                    searchCriteria);

                if (matchingMethods != null && matchingMethods.Length == 1)
                {
                    specificMethod = matchingMethods[0] as MethodInfo;
                }
                else
                {
                    specificMethod = method;
                }
            }

            ITransactionAttribute transactionAttribute = getTransactionAttribute(specificMethod);
            if (null != transactionAttribute)
            {
                return transactionAttribute;
            }
            else if (specificMethod != method)
            {
                transactionAttribute = getTransactionAttribute(method);
            }
            return null;
        }
コード例 #16
0
 /// <summary>
 ///  Within <paramref name="type"/>, counts the number of overloads for the method with the given (case-insensitive!) <paramref name="name"/> 
 /// </summary>
 /// <param name="type">The type to be searched</param>
 /// <param name="name">the name of the method for which overloads shall be counted</param>
 /// <returns>The number of overloads for method <paramref name="name"/> within type <paramref name="type"/></returns>
 public static int MethodCountForName(Type type, string name)
 {
     AssertUtils.ArgumentNotNull(type, "type", "Type must not be null");
     AssertUtils.ArgumentNotNull(name, "name", "Method name must not be null");
     MemberInfo[] methods = type.FindMembers(
         MemberTypes.Method,
         ReflectionUtils.AllMembersCaseInsensitiveFlags,
         new MemberFilter(ReflectionUtils.MethodNameFilter),
         name);
     return methods.Length;
 }
コード例 #17
0
        /// <summary>
        /// Gets the site map node from MVC site map node attribute.
        /// </summary>
        /// <param name="attribute">IMvcSiteMapNodeAttribute to map</param>
        /// <param name="type">Type.</param>
        /// <param name="methodInfo">MethodInfo on which the IMvcSiteMapNodeAttribute is applied</param>
        /// <returns>
        /// A SiteMapNode which represents the IMvcSiteMapNodeAttribute.
        /// </returns>
        protected SiteMapNode GetSiteMapNodeFromMvcSiteMapNodeAttribute(IMvcSiteMapNodeAttribute attribute, Type type, MethodInfo methodInfo)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (methodInfo == null) // try to find Index action
            {
                var ms = type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public,
                                          (mi, o) => mi != null && string.Equals(mi.Name, "Index"), null);
                foreach (MethodInfo m in ms.OfType<MethodInfo>())
                {
                    var pars = m.GetParameters();
                    if (pars.Length == 0)
                    {
                        methodInfo = m;
                        break;
                    }
                }
            }

            // Determine area (will only work if controller is defined as Assembly.<Area>.Controllers.HomeController)
            string area = "";
            if (!string.IsNullOrEmpty(attribute.AreaName))
            {
                area = attribute.AreaName;
            }
            if (string.IsNullOrEmpty(area))
            {
                var parts = type.Namespace.Split('.');
                area = parts[parts.Length - 2];

                var assemblyParts = type.Assembly.FullName.Split(',');

                if (type.Namespace == assemblyParts[0] + ".Controllers" || type.Namespace.StartsWith(area))
                {
                    // Is in default areaName...
                    area = "";
                }
            }

            // Determine controller and (index) action
            string controller = type.Name.Substring(0, type.Name.IndexOf("Controller"));
            string action = (methodInfo != null ? methodInfo.Name : null) ?? "Index";
            if (methodInfo != null) // handle custom action name
            {
                var actionNameAttribute = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), true).FirstOrDefault() as ActionNameAttribute;
                if (actionNameAttribute != null)
                {
                    action = actionNameAttribute.Name;
                }
            }

            // Generate key for node
            string key = NodeKeyGenerator.GenerateKey(
                null,
                attribute.Key,
                attribute.Url,
                attribute.Title,
                area,
                controller, action,
                attribute.Clickable);

            // Handle title and description globalization
            var explicitResourceKeys = new NameValueCollection();
            var title = attribute.Title;
            var description = attribute.Description;
            HandleResourceAttribute("title", ref title, ref explicitResourceKeys);
            HandleResourceAttribute("description", ref description, ref explicitResourceKeys);

            // Create a new SiteMap node, setting the key and url
            var siteMapNode = CreateSiteMapNode(key, explicitResourceKeys, null);

            // Set the properties on siteMapNode.
            siteMapNode.Title = title;
            siteMapNode.Description = description;
            siteMapNode.Roles = attribute.Roles;
            if (!string.IsNullOrEmpty(attribute.Route))
            {
                siteMapNode["route"] = attribute.Route;
            }
            siteMapNode["area"] = area;
            siteMapNode["controller"] = controller;
            siteMapNode["action"] = action;
            siteMapNode["dynamicNodeProvider"] = attribute.DynamicNodeProvider;
            siteMapNode["urlResolver"] = attribute.UrlResolver;
            siteMapNode["visibilityProvider"] = attribute.VisibilityProvider;
            siteMapNode.LastModifiedDate = attribute.LastModifiedDate;
            siteMapNode.ChangeFrequency = attribute.ChangeFrequency;
            siteMapNode.UpdatePriority = attribute.UpdatePriority;
            siteMapNode.TargetFrame = attribute.TargetFrame;
            siteMapNode.ImageUrl = attribute.ImageUrl;
            siteMapNode.PreservedRouteParameters = attribute.PreservedRouteParameters;

            if (!string.IsNullOrEmpty(attribute.Url))
                siteMapNode.Url = attribute.Url;

            siteMapNode.ResourceKey = attribute.ResourceKey;

            // Create a route data dictionary
            IDictionary<string, object> routeValues = new Dictionary<string, object>();
            routeValues.Add("area", area);
            routeValues.Add("controller", controller);
            routeValues.Add("action", action);

            // Add route values to sitemap node
            siteMapNode.RouteValues = routeValues;

            // Add defaults for SiteMapNodeUrlResolver
            if (siteMapNode.UrlResolver == null)
            {
                siteMapNode.UrlResolver = this.SiteMapNodeUrlResolver;
            }

            // Add defaults for SiteMapNodeVisibilityProvider
            if (siteMapNode.VisibilityProvider == null)
            {
                siteMapNode.VisibilityProvider = this.SiteMapNodeVisibilityProvider;
            }

            // Clickable?
            siteMapNode.Clickable = attribute.Clickable;

            return siteMapNode;
        }
コード例 #18
0
		/// <summary>
		/// Queries the input type for a <see cref="MethodInfo" /> signature matching the input
		/// <see cref="MethodInfo"/> signature.
		/// </summary>
		/// <remarks>
		/// Typically used to query a potential subscriber to see if they implement an event handler.
		/// </remarks>
		/// <param name="invoke"><see cref="MethodInfo"/> to match against</param>
		/// <param name="subscriberType"><see cref="Type"/> to query</param>
		/// <returns>
		/// <see cref="MethodInfo"/> matching input <see cref="MethodInfo"/>
		/// signature, or <see langword="null"/> if there is no match.
		/// </returns>
		public static MethodInfo GetMethodInfoMatchingSignature(
			MethodInfo invoke, Type subscriberType)
		{
            ParameterInfo[] parameters = invoke.GetParameters();

			ComposedCriteria criteria = new ComposedCriteria();
			criteria.Add(new MethodReturnTypeCriteria(invoke.ReturnType));
            criteria.Add(new MethodParametersCountCriteria(parameters.Length));
			criteria.Add(new MethodParametersCriteria(ReflectionUtils.GetParameterTypes(parameters)));

			MemberInfo[] methods = subscriberType.FindMembers(
				MemberTypes.Method, ReflectionUtils.AllMembersCaseInsensitiveFlags,
				new MemberFilter(new CriteriaMemberFilter().FilterMemberByCriteria),
				criteria);
			if (methods != null
				&& methods.Length > 0)
			{
				return methods[0] as MethodInfo;
			}
			return null;
		}
コード例 #19
0
		// internal for testing
		internal static IEnumerable<SerializingMember> GetTargetMembers( Type type )
		{
#if DEBUG && !UNITY
			Contract.Assert( type != null );
#endif // DEBUG && !UNITY
#if !NETFX_CORE
			var members =
				type.FindMembers(
					MemberTypes.Field | MemberTypes.Property,
					BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
					( member, criteria ) => CheckTargetEligibility( member ),
					null
				);
			var filtered = members.Where( item => Attribute.IsDefined( item, typeof( MessagePackMemberAttribute ) ) ).ToArray();
#else
			var members =
				type.GetRuntimeFields().Where( f => !f.IsStatic ).OfType<MemberInfo>()
					.Concat( type.GetRuntimeProperties().Where( p => p.GetMethod != null && !p.GetMethod.IsStatic ) )
					.Where( CheckTargetEligibility );
			var filtered = members.Where( item => item.IsDefined( typeof( MessagePackMemberAttribute ) ) ).ToArray();
#endif

			if ( filtered.Length > 0 )
			{
				return
					filtered.Select( member =>
						new SerializingMember(
							member,
							new DataMemberContract( member, member.GetCustomAttribute<MessagePackMemberAttribute>() )
						)
					);
			}

			if ( type.GetCustomAttributesData().Any( attr =>
				attr.GetAttributeType().FullName == "System.Runtime.Serialization.DataContractAttribute" ) )
			{
				return
					members.Select(
						item =>
						new
						{
							member = item,
							data = item.GetCustomAttributesData()
								.FirstOrDefault(
									data => data.GetAttributeType().FullName == "System.Runtime.Serialization.DataMemberAttribute" )
						}
					).Where( item => item.data != null )
					.Select(
						item =>
						{
							var name = item.data.GetNamedArguments()
								.Where( arg => arg.GetMemberName() == "Name" )
								.Select( arg => ( string )arg.GetTypedValue().Value )
								.FirstOrDefault();
							var id = item.data.GetNamedArguments()
								.Where( arg => arg.GetMemberName() == "Order" )
								.Select( arg => ( int? ) arg.GetTypedValue().Value )
								.FirstOrDefault();
#if SILVERLIGHT
							if ( id == -1 )
							{
								// Shim for Silverlight returns -1 because GetNamedArguments() extension method cannot recognize whether the argument was actually specified or not.
								id = null;
							}
#endif // SILVERLIGHT

							return
								new SerializingMember(
									item.member,
									new DataMemberContract( item.member, name, NilImplication.MemberDefault, id )
								);
						}
					);
			}
#if SILVERLIGHT || NETFX_CORE
			return members.Where( member => member.GetIsPublic() ).Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#else
			return
				members.Where( item => item.GetIsPublic() && !Attribute.IsDefined( item, typeof( NonSerializedAttribute ) ) )
				.Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#endif
		}
コード例 #20
0
        private static CollectionAdapterDescription GetDescriptionInternal(System.Type type, System.Type referenceType)
        {
            if (typeof(IDictionary).IsAssignableFrom(type) || typeof(IDictionary <object, object>).IsAssignableFrom(type) && type.Name == "ResourceDictionary")
            {
                return(new CollectionAdapterDescription.CollectionDescription(type, typeof(DictionaryEntry)));
            }
            if (!typeof(ICollection).IsAssignableFrom(type))
            {
                if (!typeof(XmlNamespaceMappingCollection).IsAssignableFrom(type))
                {
                    return(null);
                }
                return(new CollectionAdapterDescription.CollectionDescription(type, typeof(XmlNamespaceMapping)));
            }
            if (type.IsArray)
            {
                return(new CollectionAdapterDescription.CollectionDescription(type, type.GetElementType()));
            }
            System.Type  genericCollectionType = CollectionAdapterDescription.GetGenericCollectionType(type);
            MemberInfo[] memberInfoArray       = type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public, (MemberInfo member, object arg) => member.Name == "Add", null);
            MethodInfo   methodInfo            = null;

            MemberInfo[] memberInfoArray1 = memberInfoArray;
            for (int i = 0; i < (int)memberInfoArray1.Length; i++)
            {
                MethodInfo methodInfo1 = memberInfoArray1[i] as MethodInfo;
                if (methodInfo1 != null && MemberCollection.ReferenceMethodExists(referenceType, "Add", BindingFlags.Instance | BindingFlags.Public))
                {
                    ParameterInfo[] parameters = methodInfo1.GetParameters();
                    if ((int)parameters.Length == 1)
                    {
                        if (genericCollectionType == null)
                        {
                            methodInfo            = methodInfo1;
                            genericCollectionType = parameters[0].ParameterType;
                            break;
                        }
                        else if (parameters[0].ParameterType == genericCollectionType)
                        {
                            methodInfo = methodInfo1;
                            break;
                        }
                    }
                }
            }
            if (genericCollectionType == null)
            {
                return(null);
            }
            if (typeof(IList).IsAssignableFrom(type))
            {
                return(new CollectionAdapterDescription.CollectionDescription(type, genericCollectionType));
            }
            if (methodInfo != null)
            {
                memberInfoArray = type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public, (MemberInfo member, object arg) => member.Name == "Clear", null);
                MethodInfo   methodInfo2      = null;
                MemberInfo[] memberInfoArray2 = memberInfoArray;
                int          num = 0;
                while (num < (int)memberInfoArray2.Length)
                {
                    MethodInfo methodInfo3 = memberInfoArray2[num] as MethodInfo;
                    if (!(methodInfo3 != null) || !MemberCollection.ReferenceMethodExists(referenceType, "Clear", BindingFlags.Instance | BindingFlags.Public) || (int)methodInfo3.GetParameters().Length != 0)
                    {
                        num++;
                    }
                    else
                    {
                        methodInfo2 = methodInfo3;
                        break;
                    }
                }
                memberInfoArray = type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public, (MemberInfo member, object arg) => member.Name == "Insert", null);
                MethodInfo   methodInfo4      = null;
                MemberInfo[] memberInfoArray3 = memberInfoArray;
                for (int j = 0; j < (int)memberInfoArray3.Length; j++)
                {
                    MethodInfo methodInfo5 = memberInfoArray3[j] as MethodInfo;
                    if (methodInfo5 != null && MemberCollection.ReferenceMethodExists(referenceType, "Insert", BindingFlags.Instance | BindingFlags.Public))
                    {
                        ParameterInfo[] parameterInfoArray = methodInfo5.GetParameters();
                        if ((int)parameterInfoArray.Length == 2 && parameterInfoArray[0].ParameterType == typeof(int) && parameterInfoArray[1].ParameterType == genericCollectionType)
                        {
                            methodInfo4 = methodInfo5;
                            break;
                        }
                    }
                }
                memberInfoArray = type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public, (MemberInfo member, object arg) => member.Name == "RemoveAt", null);
                MethodInfo   methodInfo6      = null;
                MemberInfo[] memberInfoArray4 = memberInfoArray;
                for (int k = 0; k < (int)memberInfoArray4.Length; k++)
                {
                    MethodInfo methodInfo7 = memberInfoArray4[k] as MethodInfo;
                    if (methodInfo7 != null && MemberCollection.ReferenceMethodExists(referenceType, "RemoveAt", BindingFlags.Instance | BindingFlags.Public))
                    {
                        ParameterInfo[] parameters1 = methodInfo7.GetParameters();
                        if ((int)parameters1.Length == 1 && parameters1[0].ParameterType == typeof(int))
                        {
                            methodInfo6 = methodInfo7;
                            break;
                        }
                    }
                }
                memberInfoArray = type.FindMembers(MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public, (MemberInfo member, object arg) => member.Name == "Item", null);
                PropertyInfo propertyInfo     = null;
                MemberInfo[] memberInfoArray5 = memberInfoArray;
                for (int l = 0; l < (int)memberInfoArray5.Length; l++)
                {
                    PropertyInfo propertyInfo1 = memberInfoArray5[l] as PropertyInfo;
                    if (propertyInfo1 != null && propertyInfo1.CanRead && propertyInfo1.CanWrite && (!(referenceType != null) || !(referenceType.GetProperty("Item", BindingFlags.Instance | BindingFlags.Public) == null)))
                    {
                        ParameterInfo[] indexParameters = propertyInfo1.GetIndexParameters();
                        if ((int)indexParameters.Length == 1 && indexParameters[0].ParameterType == typeof(int))
                        {
                            propertyInfo = propertyInfo1;
                            break;
                        }
                    }
                }
                if (methodInfo2 != null && methodInfo4 != null && methodInfo6 != null && propertyInfo != null)
                {
                    return(new ReflectionCollectionDescription(type, genericCollectionType, methodInfo, methodInfo2, methodInfo4, methodInfo6, propertyInfo));
                }
            }
            return(new CollectionAdapterDescription.CollectionDescription(type, genericCollectionType));
        }
コード例 #21
0
ファイル: DynamicMock.cs プロジェクト: bbriggs/FieldWorks
		private MethodInfo GetMethodHelper(Type type, MethodSignature signature)
		{
			MemberInfo[] methods = type.FindMembers(MemberTypes.Method,
				ClassGenerator.ALL_INSTANCE_METHODS,
				new MemberFilter(MethodFilter), signature);

			if (methods != null && methods.Length == 1)
				return methods[0] as MethodInfo;

			return null;
		}
コード例 #22
0
		private FieldInfo[] BuildSerializableFieldsArray(Type type)
		{
			MemberInfo[] members = type.FindMembers(MemberTypes.Field,
				BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic,
				null, null);
			
			ArrayList fields = new ArrayList();
			foreach (FieldInfo field in members)
			{
				if (field.IsNotSerialized)
				{
					continue;
				}
				fields.Add(field);
			}
			return (FieldInfo[])fields.ToArray(typeof(FieldInfo));
		}	
コード例 #23
0
 private static object ParseEnum(string name, Type type)
 {
     if (type.IsEnum)
     {
         MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field,
                                                     BindingFlags.Public | BindingFlags.DeclaredOnly |
                                                     BindingFlags.Static,
                                                     Type.FilterNameIgnoreCase, name);
         if (memberInfos.Length != 0) return ((FieldInfo) memberInfos[0]).GetValue(null);
     }
     return null;
 }
コード例 #24
0
        /// <summary>
        /// Gets the site map node from MVC site map node attribute.
        /// </summary>
        /// <param name="siteMap">The site map.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="type">The type.</param>
        /// <param name="methodInfo">The method info.</param>
        /// <returns></returns>
        protected virtual ISiteMapNode GetSiteMapNodeFromMvcSiteMapNodeAttribute(ISiteMap siteMap, IMvcSiteMapNodeAttribute attribute, Type type, MethodInfo methodInfo)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (!String.IsNullOrEmpty(attribute.SiteMapCacheKey))
            {
                // Return null if the attribute doesn't apply to this cache key
                if (!this.SiteMapCacheKey.Equals(attribute.SiteMapCacheKey))
                {
                    return null;
                }
            }

            if (methodInfo == null) // try to find Index action
            {
                var ms = type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public,
                                          (mi, o) => mi != null && string.Equals(mi.Name, "Index"), null);
                foreach (MethodInfo m in ms.OfType<MethodInfo>())
                {
                    var pars = m.GetParameters();
                    if (pars.Length == 0)
                    {
                        methodInfo = m;
                        break;
                    }
                }
            }

            // Determine area (will only work if controller is defined as Assembly.<Area>.Controllers.HomeController)
            string area = "";
            if (!string.IsNullOrEmpty(attribute.AreaName))
            {
                area = attribute.AreaName;
            }
            if (string.IsNullOrEmpty(area))
            {
                var parts = type.Namespace.Split('.');
                area = parts[parts.Length - 2];

                var assemblyParts = type.Assembly.FullName.Split(',');

                if (type.Namespace == assemblyParts[0] + ".Controllers" || type.Namespace.StartsWith(area))
                {
                    // Is in default areaName...
                    area = "";
                }
            }

            // Determine controller and (index) action
            string controller = type.Name.Substring(0, type.Name.IndexOf("Controller"));
            string action = (methodInfo != null ? methodInfo.Name : null) ?? "Index";
            string httpMethod = "*";
            if (methodInfo != null)
            {
                // handle ActionNameAttribute
                var actionNameAttribute = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), true).FirstOrDefault() as ActionNameAttribute;
                if (actionNameAttribute != null)
                {
                    action = actionNameAttribute.Name;
                }

                // handle AcceptVerbsAttribute
                var acceptVerbsAttribute = methodInfo.GetCustomAttributes(typeof(AcceptVerbsAttribute), true).FirstOrDefault() as AcceptVerbsAttribute;
                if (acceptVerbsAttribute != null)
                {
                    httpMethod = string.Join(",", acceptVerbsAttribute.Verbs.ToArray());
                }
            }

            // Handle title and description
            var title = attribute.Title;
            var description = String.IsNullOrEmpty(attribute.Description) ? title : attribute.Description;

            // Handle implicit resources
            var implicitResourceKey = attribute.ResourceKey;

            // Generate key for node
            string key = nodeKeyGenerator.GenerateKey(
                null,
                attribute.Key,
                "",
                title,
                area,
                controller, action, httpMethod,
                attribute.Clickable);

            var siteMapNode = siteMapNodeFactory.Create(siteMap, key, implicitResourceKey);

            // Assign defaults
            siteMapNode.Title = title;
            siteMapNode.Description = description;
            AcquireAttributesFrom(attribute, siteMapNode.Attributes);
            AcquireRolesFrom(attribute, siteMapNode.Roles);
            siteMapNode.Clickable = attribute.Clickable;
            siteMapNode.VisibilityProvider = attribute.VisibilityProvider;
            siteMapNode.DynamicNodeProvider = attribute.DynamicNodeProvider;
            siteMapNode.ImageUrl = attribute.ImageUrl;
            siteMapNode.TargetFrame = attribute.TargetFrame;
            siteMapNode.HttpMethod = httpMethod;
            if (!string.IsNullOrEmpty(attribute.Url)) siteMapNode.Url = attribute.Url;
            siteMapNode.CacheResolvedUrl = attribute.CacheResolvedUrl;
            siteMapNode.CanonicalUrl = attribute.CanonicalUrl;
            siteMapNode.CanonicalKey = attribute.CanonicalKey;
            AcquireMetaRobotsValuesFrom(attribute, siteMapNode.MetaRobotsValues);
            siteMapNode.LastModifiedDate = attribute.LastModifiedDate;
            siteMapNode.ChangeFrequency = attribute.ChangeFrequency;
            siteMapNode.UpdatePriority = attribute.UpdatePriority;

            // Handle route details
            siteMapNode.Route = attribute.Route;
            AcquireRouteValuesFrom(attribute, siteMapNode.RouteValues);
            AcquirePreservedRouteParametersFrom(attribute, siteMapNode.PreservedRouteParameters);
            siteMapNode.UrlResolver = attribute.UrlResolver;

            // Specified area, controller and action properties will override any
            // provided in the attributes collection.
            if (!string.IsNullOrEmpty(area)) siteMapNode.RouteValues.Add("area", area);
            if (!string.IsNullOrEmpty(controller)) siteMapNode.RouteValues.Add("controller", controller);
            if (!string.IsNullOrEmpty(action)) siteMapNode.RouteValues.Add("action", action);

            // Handle MVC details

            // Add defaults for area
            if (!siteMapNode.RouteValues.ContainsKey("area"))
            {
                siteMapNode.RouteValues.Add("area", "");
            }

            return siteMapNode;
        }
コード例 #25
0
        /// <summary>
        /// Process the top operator on the operator stack.
        /// Consume as many operands as needed from the operands stack.
        /// When top-operator is closing bracket, two options:
        ///   a * ( b + c )
        ///   In(a, b)
        /// </summary>
        private void ProcessOperator(OperatorInfo op, Stack <Var> operands)
        {
            ArrayList arglist = new ArrayList();

            if (op.function)
            {
                foreach (Var v in op.parameters)
                {
                    arglist.Add(v);
                }
            }
            else
            {
                // It must be an operator. It can be unary or not, so get at least one operand.
                arglist.Insert(0, operands.Pop());
                if (!op.unary)
                {
                    arglist.Insert(0, operands.Pop());
                }
            }

            if (op.methodname == null && op.function)
            {
                // Process function
                // Haal eerst de functieinformatie op.
                Var result = myTokenResolver.FunctionEvaluator(op.name, arglist);
                System.Diagnostics.Debug.Assert(result != null);
                operands.Push(result);
            }
            else
            {
                Var          o1 = (arglist[0] as Var);
                System.Type  t1 = o1.GetType();
                MemberInfo[] ts = t1.FindMembers(
                    System.Reflection.MemberTypes.Method,
                    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public,
                    new System.Reflection.MemberFilter(FindOperator),
                    op);

                if (ts.GetLength(0) == 0)
                {
                    throw new OperationNotDefinedException(null, op.name, o1.TypeName(), arglist);
                }

                // Find the method taking the right type of parameter
                MethodInfo methodFound = null;
                foreach (MethodInfo method in ts)
                {
                    ParameterInfo[] parms = method.GetParameters();

                    if (parms.GetLength(0) == arglist.Count)
                    {
                        methodFound = method;
                        for (int pi = 0; pi < arglist.Count; pi++)
                        {
                            if (parms[pi].ParameterType != arglist[pi].GetType())
                            {
                                methodFound = null;
                                break;
                            }
                        }
                        if (methodFound != null)
                        {
                            break;
                        }
                    }
                }
                if (methodFound == null)
                {
                    throw new OperationNotDefinedException(null, op.name, o1.TypeName(), arglist);
                }

                // Method found. Apply it
                object[] args = arglist.ToArray();
                //			if (op.unary)
                //				args = new object[] {o1};
                //			else
                //				args = new object[] {o1, o2};

                if (methodFound.ReturnType == typeof(void))
                {
                    methodFound.Invoke(null, args);
                }
                else
                {
                    object result = methodFound.Invoke(null, args);
                    operands.Push(result as Var);
                }
            }
            return;
        }
コード例 #26
0
ファイル: XQueryFunction.cs プロジェクト: nlhepler/mono
		private static MethodInfo [] FindNamedMethods (Type type, string name)
		{
			ArrayList al = new ArrayList (
				type.FindMembers (
					MemberTypes.Method,
					BindingFlags.Default | BindingFlags.Public | BindingFlags.Static,
					// FIXME: wait for anonymous method support
//					delegate (MemberInfo m, object filterCriteria) {
//						return m.Name == filterCriteria.ToString ();
//					},
					memberFilter,
					name));
			return al.ToArray (typeof (MethodInfo)) as MethodInfo [];
		}
コード例 #27
0
ファイル: IndexExpression.cs プロジェクト: sbc100/mono
        private static PropertyInfo FindProperty(Type type, string propertyName, Expression[] arguments, BindingFlags flags) {
            MemberInfo[] members = type.FindMembers(MemberTypes.Property, flags, Type.FilterNameIgnoreCase, propertyName);
            if (members == null || members.Length == 0)
                return null;

            PropertyInfo pi;
            var propertyInfos = members.Map(t => (PropertyInfo)t);
            int count = FindBestProperty(propertyInfos, arguments, out pi);

            if (count == 0)
                return null;
            if (count > 1)
                throw Error.PropertyWithMoreThanOneMatch(propertyName, type);
            return pi;
        }
コード例 #28
0
ファイル: DynamicMock.cs プロジェクト: bbriggs/FieldWorks
		private PropertyInfo GetPropertyHelper(Type type, MethodSignature signature)
		{
			MemberInfo[] properties = type.FindMembers(MemberTypes.Property,
				ClassGenerator.ALL_INSTANCE_METHODS,
				new MemberFilter(PropertyFilter), signature);

			if (properties != null && properties.Length == 1)
				return properties[0] as PropertyInfo;

			return null;
		}
        /// <summary>
        /// Return the <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/> for this
        /// method.
        /// </summary>
        /// <param name="method">The method to check.</param>
        /// <param name="targetType">
        /// The target <see cref="System.Type"/>. May be null, in which case the declaring 
        /// class of the supplied <paramref name="method"/> must be used.
        /// </param>
        /// <returns>
        /// A <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/> or 
        /// null if the method is non-transactional.
        /// </returns>
        public ITransactionAttribute ReturnTransactionAttribute(MethodInfo method, Type targetType)
        {
            //Might have registered MethodInfo objects whose declaring type is the interface, so 'downcast'
            //to the most specific method which is typically what is passed in as the first method argument.
            foreach (DictionaryEntry dictionaryEntry in _methodMap)
            {
                MethodInfo currentMethod = (MethodInfo)dictionaryEntry.Key;

                MethodInfo specificMethod;
                if (targetType == null)
                {
                    specificMethod = currentMethod;
                }
                else
                {
                    ParameterInfo[] parameters = currentMethod.GetParameters();

                    ComposedCriteria searchCriteria = new ComposedCriteria();
                    searchCriteria.Add(new MethodNameMatchCriteria(currentMethod.Name));
                    searchCriteria.Add(new MethodParametersCountCriteria(parameters.Length));
            #if NET_2_0
                    searchCriteria.Add(new MethodGenericArgumentsCountCriteria(
                        currentMethod.GetGenericArguments().Length));
            #endif
                    searchCriteria.Add(new MethodParametersCriteria(ReflectionUtils.GetParameterTypes(parameters)));

                    MemberInfo[] matchingMethods = targetType.FindMembers(
                        MemberTypes.Method,
                        BindingFlags.Instance | BindingFlags.Public,
                        new MemberFilter(new CriteriaMemberFilter().FilterMemberByCriteria),
                        searchCriteria);

                    if (matchingMethods != null && matchingMethods.Length == 1)
                    {
                        specificMethod = matchingMethods[0] as MethodInfo;
                    }
                    else
                    {
                        specificMethod = currentMethod;
                    }
                }

                if (method == specificMethod)
                {
                    return (ITransactionAttribute)dictionaryEntry.Value;
                }
            }
            return (ITransactionAttribute)_methodMap[method];
        }
コード例 #30
0
		/// <summary>
		/// Look up a conversion method from a type.
		/// </summary>
		/// <param name="methodName">The name of the method to find.</param>
		/// <param name="searchType">The type to search through.</param>
		/// <param name="sourceType">The source type for the conversion.</param>
		/// <param name="targetType">The target type for the conversion.</param>
		/// <returns>A conversion method or null if none could be found.</returns>
		private static MethodInfo FindConversionMethod(string methodName, Type searchType, Type sourceType, Type targetType)
		{
			var members = searchType.FindMembers(
				MemberTypes.Method,
				BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
				new MemberFilter(
				(_m, filter) =>
				{
					MethodInfo m = _m as MethodInfo;
					if (m.Name != methodName) return false;
					if (m.ReturnType != targetType) return false;
					ParameterInfo[] pi = m.GetParameters();
					if (pi.Length != 1) return false;
					if (pi[0].ParameterType != sourceType) return false;
					return true;
				}),
				null);

			return (MethodInfo)members.FirstOrDefault();
		}
コード例 #31
0
        private MemberInfo[] GetMembers(Type type, string methodName)
        {
            MemberInfo[] memberInfo = type.FindMembers(MemberTypes.Property,
                                                       BindingFlags.Public | BindingFlags.Instance,
                                                       Type.FilterName, methodName);

            return memberInfo;
        }
コード例 #32
0
        /// <summary>
        /// Gets the site map node from MVC site map node attribute.
        /// </summary>
        /// <param name="siteMap">The site map.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="type">The type.</param>
        /// <param name="methodInfo">The method info.</param>
        /// <returns></returns>
        protected virtual ISiteMapNode GetSiteMapNodeFromMvcSiteMapNodeAttribute(ISiteMap siteMap, IMvcSiteMapNodeAttribute attribute, Type type, MethodInfo methodInfo)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (!string.IsNullOrEmpty(attribute.SiteMapCacheKey))
            {
                // Return null if the attribute doesn't apply to this cache key
                if (!this.SiteMapCacheKey.Equals(attribute.SiteMapCacheKey))
                {
                    return null;
                }
            }

            if (methodInfo == null) // try to find Index action
            {
                var ms = type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public,
                                          (mi, o) => mi != null && string.Equals(mi.Name, "Index"), null);
                foreach (MethodInfo m in ms.OfType<MethodInfo>())
                {
                    var pars = m.GetParameters();
                    if (pars.Length == 0)
                    {
                        methodInfo = m;
                        break;
                    }
                }
            }

            string area = "";
            if (!string.IsNullOrEmpty(attribute.AreaName))
            {
                area = attribute.AreaName;
            }
            if (string.IsNullOrEmpty(area) && !string.IsNullOrEmpty(attribute.Area))
            {
                area = attribute.Area;
            }
            // Determine area (will only work if controller is defined as [<Anything>.]Areas.<Area>.Controllers.<AnyController>)
            if (string.IsNullOrEmpty(area))
            {
                var m = Regex.Match(type.Namespace, @"(?:[^\.]+\.|\s+|^)Areas\.(?<areaName>[^\.]+)\.Controllers");
                if (m.Success)
                {
                    area = m.Groups["areaName"].Value;
                }
            }

            // Determine controller and (index) action
            string controller = type.Name.Substring(0, type.Name.IndexOf("Controller"));
            string action = (methodInfo != null ? methodInfo.Name : null) ?? "Index";
            if (methodInfo != null)
            {
                // handle ActionNameAttribute
                var actionNameAttribute = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), true).FirstOrDefault() as ActionNameAttribute;
                if (actionNameAttribute != null)
                {
                    action = actionNameAttribute.Name;
                }
            }

            string httpMethod = string.IsNullOrEmpty(attribute.HttpMethod) ? HttpVerbs.Get.ToString().ToUpperInvariant() : attribute.HttpMethod.ToUpperInvariant();

            // Handle title
            var title = attribute.Title;

            // Handle implicit resources
            var implicitResourceKey = attribute.ResourceKey;

            // Generate key for node
            string key = nodeKeyGenerator.GenerateKey(
                null,
                attribute.Key,
                "",
                title,
                area,
                controller, action, httpMethod,
                attribute.Clickable);

            var siteMapNode = siteMapNodeFactory.Create(siteMap, key, implicitResourceKey);

            // Assign defaults
            siteMapNode.Title = title;
            siteMapNode.Description = attribute.Description;
            siteMapNode.Attributes.AddRange(attribute.Attributes, false);
            siteMapNode.Roles.AddRange(attribute.Roles);
            siteMapNode.Clickable = attribute.Clickable;
            siteMapNode.VisibilityProvider = attribute.VisibilityProvider;
            siteMapNode.DynamicNodeProvider = attribute.DynamicNodeProvider;
            siteMapNode.ImageUrl = attribute.ImageUrl;
            siteMapNode.ImageUrlProtocol = attribute.ImageUrlProtocol;
            siteMapNode.ImageUrlHostName = attribute.ImageUrlHostName;
            siteMapNode.TargetFrame = attribute.TargetFrame;
            siteMapNode.HttpMethod = httpMethod;
            if (!string.IsNullOrEmpty(attribute.Url)) siteMapNode.Url = attribute.Url;
            siteMapNode.CacheResolvedUrl = attribute.CacheResolvedUrl;
            siteMapNode.IncludeAmbientValuesInUrl = attribute.IncludeAmbientValuesInUrl;
            siteMapNode.Protocol = attribute.Protocol;
            siteMapNode.HostName = attribute.HostName;
            siteMapNode.CanonicalKey = attribute.CanonicalKey;
            siteMapNode.CanonicalUrl = attribute.CanonicalUrl;
            siteMapNode.CanonicalUrlProtocol = attribute.CanonicalUrlProtocol;
            siteMapNode.CanonicalUrlHostName = attribute.CanonicalUrlHostName;
            siteMapNode.MetaRobotsValues.AddRange(attribute.MetaRobotsValues);
            siteMapNode.LastModifiedDate = string.IsNullOrEmpty(attribute.LastModifiedDate) ? DateTime.MinValue : DateTime.Parse(attribute.LastModifiedDate, CultureInfo.InvariantCulture);
            siteMapNode.ChangeFrequency = attribute.ChangeFrequency;
            siteMapNode.UpdatePriority = attribute.UpdatePriority;
            siteMapNode.Order = attribute.Order;

            // Handle route details
            siteMapNode.Route = attribute.Route;
            siteMapNode.RouteValues.AddRange(attribute.Attributes, false);
            siteMapNode.PreservedRouteParameters.AddRange(attribute.PreservedRouteParameters, new[] { ',', ';' });
            siteMapNode.UrlResolver = attribute.UrlResolver;
            
            // Specified area, controller and action properties will override any 
            // provided in the attributes collection.
            if (!string.IsNullOrEmpty(area)) siteMapNode.RouteValues.Add("area", area);
            if (!string.IsNullOrEmpty(controller)) siteMapNode.RouteValues.Add("controller", controller);
            if (!string.IsNullOrEmpty(action)) siteMapNode.RouteValues.Add("action", action);

            return siteMapNode;
        }
コード例 #33
0
ファイル: PathStruct.cs プロジェクト: erpframework/cloudb
        public object ToObject(Type type)
        {
            object obj = Activator.CreateInstance(type, true);

            MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field | MemberTypes.Property, BindingFlags.Public, null, null);

            int sz = memberInfos.Length;
            if (sz == 0)
                return obj;

            for (int i = 0; i < sz; i++) {
                MemberInfo memberInfo = memberInfos[i];

                if (!HasMember(memberInfo.Name))
                    continue;

                Type memberType;
                if (memberInfo is FieldInfo) {
                    memberType = ((FieldInfo) memberInfo).FieldType;
                } else {
                    memberType = ((PropertyInfo) memberInfo).PropertyType;
                }

                PathValue pathValue = GetValue(memberInfo.Name);
                object value = Convert.ChangeType(pathValue, memberType);

                if (memberInfo is FieldInfo) {
                    ((FieldInfo)memberInfo).SetValue(obj, value);
                } else {
                    ((PropertyInfo)memberInfo).SetValue(obj, value, null);
                }
            }

            return obj;
        }
コード例 #34
0
 private static IEnumerable<MemberInfo> GetTestMethodsInClass(Type testClass)
 {
     return testClass
         .FindMembers(MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, null, null)
         .Where(s => s.IsMarkedWith<FactAttribute>());
 }
 /// <summary>
 /// Returns an array of all of those
 /// <see cref="System.Reflection.MethodInfo">methods</see> exposed on the
 /// <paramref name="searchType"/> that match the supplied criteria.
 /// </summary>
 /// <param name="methodName">
 /// Methods that have this name (can be in the form of a regular expression).
 /// </param>
 /// <param name="expectedArgumentCount">
 /// Methods that have exactly this many arguments.
 /// </param>
 /// <param name="isStatic">
 /// Methods that are static / instance.
 /// </param>
 /// <param name="searchType">
 /// The <see cref="System.Type"/> on which the methods (if any) are to be found.
 /// </param>
 /// <returns>
 /// An array of all of those
 /// <see cref="System.Reflection.MethodInfo">methods</see> exposed on the
 /// <paramref name="searchType"/> that match the supplied criteria.
 /// </returns>
 private static IList<MethodInfo> FindMethods(string methodName, int expectedArgumentCount, bool isStatic, Type searchType)
 {
     ComposedCriteria methodCriteria = new ComposedCriteria();
     methodCriteria.Add(new MethodNameMatchCriteria(methodName));
     methodCriteria.Add(new MethodParametersCountCriteria(expectedArgumentCount));
     BindingFlags methodFlags = BindingFlags.Public | BindingFlags.IgnoreCase | (isStatic ? BindingFlags.Static : BindingFlags.Instance);
     MemberInfo[] methods = searchType.FindMembers(MemberTypes.Method, methodFlags, new CriteriaMemberFilter().FilterMemberByCriteria, methodCriteria);
     return methods.Cast<MethodInfo>().ToArray();
 }
コード例 #36
0
        /// <summary>
        /// Gets the site map node from MVC site map node attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="type">The type.</param>
        /// <param name="methodInfo">The method info.</param>
        /// <param name="helper">The node helper.</param>
        /// <returns></returns>
        protected virtual ISiteMapNodeToParentRelation GetSiteMapNodeFromMvcSiteMapNodeAttribute(
            IMvcSiteMapNodeAttribute attribute, Type type, MethodInfo methodInfo, ISiteMapNodeHelper helper)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (!String.IsNullOrEmpty(attribute.SiteMapCacheKey))
            {
                // Return null if the attribute doesn't apply to this cache key
                if (!helper.SiteMapCacheKey.Equals(attribute.SiteMapCacheKey))
                {
                    return null;
                }
            }

            if (methodInfo == null) // try to find Index action
            {
                var ms = type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public,
                                          (mi, o) => mi != null && string.Equals(mi.Name, "Index"), null);
                foreach (MethodInfo m in ms.OfType<MethodInfo>())
                {
                    var pars = m.GetParameters();
                    if (pars.Length == 0)
                    {
                        methodInfo = m;
                        break;
                    }
                }
            }

            string area = "";
            if (!String.IsNullOrEmpty(attribute.AreaName))
            {
                area = attribute.AreaName;
            }
            if (String.IsNullOrEmpty(area) && !String.IsNullOrEmpty(attribute.Area))
            {
                area = attribute.Area;
            }
            // Determine area (will only work if controller is defined as [<Anything>.]Areas.<Area>.Controllers.<AnyController>)
            if (String.IsNullOrEmpty(area))
            {
                var m = Regex.Match(type.Namespace, @"(?:[^\.]+\.|\s+|^)Areas\.(?<areaName>[^\.]+)\.Controllers");
                if (m.Success)
                {
                    area = m.Groups["areaName"].Value;
                }
            }

            // Determine controller and (index) action
            string controller = type.Name.Substring(0, type.Name.IndexOf("Controller"));
            string action = (methodInfo != null ? methodInfo.Name : null) ?? "Index";

            if (methodInfo != null)
            {
                // handle ActionNameAttribute
                var actionNameAttribute = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), true).FirstOrDefault() as ActionNameAttribute;
                if (actionNameAttribute != null)
                {
                    action = actionNameAttribute.Name;
                }
            }

            string httpMethod = String.IsNullOrEmpty(attribute.HttpMethod) ? HttpVerbs.Get.ToString().ToUpperInvariant() : attribute.HttpMethod.ToUpperInvariant();

            // Handle title and description
            var title = attribute.Title;
            var description = String.IsNullOrEmpty(attribute.Description) ? title : attribute.Description;

            // Handle implicit resources
            var implicitResourceKey = attribute.ResourceKey;

            // Generate key for node
            string key = helper.CreateNodeKey(
                attribute.ParentKey,
                attribute.Key,
                attribute.Url,
                title,
                area,
                controller, action, httpMethod,
                attribute.Clickable);

            var nodeParentMap = helper.CreateNode(key, attribute.ParentKey, SourceName, implicitResourceKey);
            var node = nodeParentMap.Node;

            // Assign defaults
            node.Title = title;
            node.Description = description;
            AcquireAttributesFrom(attribute, node.Attributes, helper);
            AcquireRolesFrom(attribute, node.Roles);
            node.Clickable = attribute.Clickable;
            node.VisibilityProvider = attribute.VisibilityProvider;
            node.DynamicNodeProvider = attribute.DynamicNodeProvider;
            node.ImageUrl = attribute.ImageUrl;
            node.TargetFrame = attribute.TargetFrame;
            node.HttpMethod = httpMethod;
            if (!string.IsNullOrEmpty(attribute.Url)) node.Url = attribute.Url;
            node.CacheResolvedUrl = attribute.CacheResolvedUrl;
            node.CanonicalUrl = attribute.CanonicalUrl;
            node.CanonicalKey = attribute.CanonicalKey;
            AcquireMetaRobotsValuesFrom(attribute, node.MetaRobotsValues);
            node.LastModifiedDate = attribute.LastModifiedDate;
            node.ChangeFrequency = attribute.ChangeFrequency;
            node.UpdatePriority = attribute.UpdatePriority;
            node.Order = attribute.Order;

            // Handle route details
            node.Route = attribute.Route;
            AcquireRouteValuesFrom(attribute, node.RouteValues, helper);
            AcquirePreservedRouteParametersFrom(attribute, node.PreservedRouteParameters);
            node.UrlResolver = attribute.UrlResolver;

            // Specified area, controller and action properties will override any
            // provided in the attributes collection.
            if (!string.IsNullOrEmpty(area)) node.RouteValues.Add("area", area);
            if (!string.IsNullOrEmpty(controller)) node.RouteValues.Add("controller", controller);
            if (!string.IsNullOrEmpty(action)) node.RouteValues.Add("action", action);

            // Handle MVC details

            // Add defaults for area
            if (!node.RouteValues.ContainsKey("area"))
            {
                node.RouteValues.Add("area", "");
            }

            return nodeParentMap;
        }
コード例 #37
0
        private static MethodInfo FindMethod(Type type, string methodName, Type[] typeArgs, Expression[] args, BindingFlags flags) {
            MemberInfo[] members = type.FindMembers(MemberTypes.Method, flags, Type.FilterNameIgnoreCase, methodName);
            if (members == null || members.Length == 0)
                throw Error.MethodDoesNotExistOnType(methodName, type);

            MethodInfo method;

            var methodInfos = members.Map(t => (MethodInfo)t);
            int count = FindBestMethod(methodInfos, typeArgs, args, out method);

            if (count == 0) {
                if (typeArgs != null && typeArgs.Length > 0) {
                    throw Error.GenericMethodWithArgsDoesNotExistOnType(methodName, type);
                } else {
                    throw Error.MethodWithArgsDoesNotExistOnType(methodName, type);
                }
            }
            if (count > 1)
                throw Error.MethodWithMoreThanOneMatch(methodName, type);
            return method;
        }
コード例 #38
0
        /// <summary>
        /// Process the top operator on the operator stack.
        /// Consume as many operands as needed from the operands stack.
        /// When top-operator is closing bracket, two options:
        ///   a * ( b + c )
        ///   In(a, b)
        /// </summary>
        private void ProcessOperator()
        {
            ArrayList arglist = new ArrayList();

            // Process closing bracket. Pop operators and process these
            // until an opening bracket is found on the stack.
            OperatorInfo op = PopOperator();

            if (op.name == ")")
            {
                op = PopOperator();
                while (op.name != "(")
                {
                    System.Diagnostics.Debug.Assert(op.name == ",", "Er zou alleen een ',' op de stack mogen staan of een '(', en niet een '" + op.name + "'");
                    arglist.Insert(0, mOperands.Pop());
                    op = PopOperator();
                }

                if (arglist.Count > 0)
                {
                    if (mTopOperator == null || !mTopOperator.function)
                    {
                        throw new ApplicationException(String.Format("Argument list found but not function call before '('"));
                    }
                }
                else
                {
                    // No arglist found.
                    // If function, pop first argument, else it was () combination. Return
                    if (mTopOperator == null || !mTopOperator.function)
                    {
                        return;
                    }
                }
                // It is a function call
                // Pop first argument
                arglist.Insert(0, mOperands.Pop());
                op = PopOperator();
            }
            else if (op.name == "," || op.name == "(")
            {
                PushOperator(op);                       // do not process yet!
                return;
            }
            else
            {
                // It must be an operator. It can be unary or not, so get at least one operand.
                arglist.Insert(0, mOperands.Pop());
                if (!op.unary)
                {
                    arglist.Insert(0, mOperands.Pop());
                }
            }

            Var o1 = (arglist[0] as Var);

            if (op.methodname == null && op.function)
            {
                // Process function
                // Haal eerst de functieinformatie op.
                Var result = myTokenResolver.FunctionEvaluator(op.name, arglist);
                mOperands.Push(result);
            }
            else
            {
                System.Type  t1 = o1.GetType();
                MemberInfo[] ts = t1.FindMembers(
                    System.Reflection.MemberTypes.Method,
                    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public,
                    new System.Reflection.MemberFilter(FindOperator),
                    op);

                if (ts.GetLength(0) == 0)
                {
                    throw new ApplicationException(String.Format("Operation '{0}' not defined for '{1}'", op.name, o1.GetType().Name));
                }

                // Find the method taking the right type of parameter
                MethodInfo methodFound = null;
                foreach (MethodInfo method in ts)
                {
                    ParameterInfo[] parms = method.GetParameters();

                    if (parms.GetLength(0) == arglist.Count)
                    {
                        methodFound = method;
                        for (int pi = 0; pi < arglist.Count; pi++)
                        {
                            if (parms[pi].ParameterType != arglist[pi].GetType())
                            {
                                methodFound = null;
                                break;
                            }
                        }
                        if (methodFound != null)
                        {
                            break;
                        }
                    }
                }
                if (methodFound == null)
                {
                    string msg = String.Format("Operation '{0}' not defined for ", op.name);
                    foreach (Var v in arglist)
                    {
                        msg += "'" + v.GetType().Name + "',";
                    }
                    throw new ApplicationException(msg);
                    //				if (op.unary)
                    //					throw new ApplicationException(String.Format("Operation '{0}' not defined for '{1}'", op.name, o1.GetType().Name));
                    //				else
                    //					throw new ApplicationException(String.Format("Operation '{0}' not defined for '{1}' and '{2}'", op.name, o1.GetType().Name, o2.GetType().Name));
                }

                // Method found. Apply it
                object[] args = arglist.ToArray();
                //			if (op.unary)
                //				args = new object[] {o1};
                //			else
                //				args = new object[] {o1, o2};

                if (methodFound.ReturnType == typeof(void))
                {
                    methodFound.Invoke(null, args);
                }
                else
                {
                    object result = methodFound.Invoke(null, args);
                    mOperands.Push(result);
                }
            }
            return;
        }