internal static bool Test(Type contextType, ContextFilter contextFilter) { if (contextType == null) return false; // Fail for null context if (contextFilter == null) return true; // Pass for no filter bool listed = contextFilter.ContextTypes.Any(type => { switch (contextFilter.FilterPolicy) { case ContextFilterPolicy.IncludeDerived: return type == contextType || type.IsSubclassOf(contextType); default: // ContextFilterPolicy.Strict return type == contextType; } }); return contextFilter.FilterType == ContextFilterType.Whitelist ? listed : !listed; }
internal Command(MethodInfo method, string name, string desc, string category, ContextFilter filter = null) { _method = method; Filter = filter; var pl = _method.GetParameters(); // Examine parameters for optional/params arguments _numOptionalParams = pl.Count(pi => pi.IsOptional); if (pl.Any()) { _contextType = pl[0].ParameterType; var type = typeof (Context); if (!_contextType.IsSubclassOf(type) && type != _contextType) { throw new ArgumentException("Command creation failed: Method '" + method.Name + "' requires a DevcomContext as the first parameter."); } _hasParamsArgument = pl.Last().GetCustomAttributes<ParamArrayAttribute>().Any(); } else { throw new ArgumentException("Command creation failed: Method '" + method.Name + "' requires a DevcomContext as the first parameter."); } // Check the filter against the minimum context type to make sure it lets it through if (filter != null && !ContextFilter.Test(_contextType, Filter)) { throw new ArgumentException("Command creation failed: The base context type '"+ _contextType.Name +"' will always be rejected by the filter rules you specified."); } _paramList = pl; _name = name; _desc = desc; _category = category; _paramHelpString = _paramList.Length > 1 ? _paramList.Where((p, i) => i > 0) .Select(p => "[" + p.Name + (p.IsOptional ? " (optional)]" : p.IsDefined(typeof(ParamArrayAttribute)) ? " ...]" : "]")) .Aggregate((accum, pname) => accum + " " + pname) : ""; }
/// <summary> /// Creates a new command using the specified method, metadata, and an optional filter. /// </summary> /// <param name="method">The method to associate with the command.</param> /// <param name="name">The name of the command.</param> /// <param name="description">The description of the command.</param> /// <param name="category">The category under which to place the command.</param> /// <param name="filter">The filter rules to apply to the command.</param> /// <returns></returns> public static Command CreateCommand(MethodInfo method, string name, string description, string category, ContextFilter filter = null) { if (name == null) { throw new ArgumentNullException("name"); } name = name.Trim().ToLower(); var qname = Util.Qualify(category ?? "", name); if (Commands.ContainsKey(qname)) return null; return Commands[qname] = new Command(method, name, description, category, filter); }