Example #1
0
        /// <summary>
        /// Creates a new command targeting at given method.
        /// </summary>
        /// <param name="method">Method invoked by command</param>
        /// <param name="commandInfo">Command method attribute providing metadata</param>
        /// <returns>Newly created command or null in case of error</returns>
        private static GmCommandHandler CreateCommand(MethodInfo method, CommandAttribute commandInfo)
        {
            ParameterInfo[] parameters = method.GetParameters();

            // First parameter is always player
            if (parameters.Length == 0 || parameters[0].ParameterType != typeof(Player))
            {
                Log.Error("CommandsBuilder", string.Format("{0}.{1} command must expect the player as first parameter.", method.DeclaringType.Name, method.Name));
                return(null);
            }

            bool hasTargetParam = HasTargetParameter(parameters); // Second can be target
            int  startIndex     = hasTargetParam ? 2 : 1;

            // Other parameters
            for (int i = startIndex; i < parameters.Length; i++)
            {
                if (!CheckParameter(parameters[i]))
                {
                    return(null);
                }
            }

            // Method invokation handler
            GmCommandHandler.GmComHandler del = (Player player, ref List <string> rawValues) => {
                return(Invoke(method, player, rawValues));
            };

            // Method declaration
            string           description = string.Concat(CommandToString(parameters[0]), " : ", commandInfo.Description);
            GmCommandHandler handler     = new GmCommandHandler(
                method.Name.ToLowerInvariant(), del, null, commandInfo.AccessRequired, -1, description);

            return(handler);
        }
Example #2
0
        /// <summary>
        /// Builds a list of commands using reflexion on the given class.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="declarative"></param>
        /// <returns></returns>
        public static List <GmCommandHandler> BuildCommands(Type type, params GmCommandHandler[] declarative)
        {
            List <GmCommandHandler> list = new List <GmCommandHandler>();

            list.AddRange(declarative); // Optional declarative commands hard coded by invoker

            foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
            {
                object[] attributes = method.GetCustomAttributes(typeof(CommandAttribute), false);
                if (attributes.Length == 1)
                {
                    GmCommandHandler handler = CreateCommand(method, (CommandAttribute)attributes[0]);
                    if (handler != null)
                    {
                        list.Add(handler);
                    }
                }
            }

            return(list);
        }