/// <summary>
        /// Registers the specified command
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="type"></param>
        /// <param name="callback"></param>
        public void RegisterCommand(string cmd, CommandType type, CommandCallback callback)
        {
            // Is it a console command?
            if (type == CommandType.Console) return;

            // Convert to lowercase
            var command_name = cmd.ToLowerInvariant();

            // Check if it already exists
            if (CommandManager.RegisteredCommands.ContainsKey(command_name))
            {
                throw new CommandAlreadyExistsException(command_name);
            }

            // Register it
            var commandAttribute = new CommandAttribute("/" + command_name, string.Empty)
            {
                Method = info =>
                {
                    var player = HurtworldCovalenceProvider.Instance.PlayerManager.GetPlayer(info.PlayerId.ToString());
                    callback(info.Label, CommandType.Chat, player, info.Args);
                }
            };
            CommandManager.RegisteredCommands[command_name] = commandAttribute;
        }
Exemple #2
0
        public void AddChatCommand(string name, Plugin plugin, string callback_name)
        {
            var command_name = name.ToLowerInvariant();

            ChatCommand cmd;
            if (chatCommands.TryGetValue(command_name, out cmd))
            {
                var previous_plugin_name = cmd.Plugin?.Name ?? "an unknown plugin";
                var new_plugin_name = plugin?.Name ?? "An unknown plugin";
                var msg = $"{new_plugin_name} has replaced the '{command_name}' chat command previously registered by {previous_plugin_name}";
                Interface.Oxide.LogWarning(msg);
            }

            cmd = new ChatCommand(command_name, plugin, callback_name);

            // Add the new command to collections
            chatCommands[command_name] = cmd;

            var commandAttribute = new CommandAttribute("/" + command_name, string.Empty);
            var action = (Action<CommandInfo>)Delegate.CreateDelegate(typeof(Action<CommandInfo>), this, GetType().GetMethod("HandleCommand", BindingFlags.NonPublic | BindingFlags.Instance));
            commandAttribute.Method = action;
            if (CommandManager.RegisteredCommands.ContainsKey(command_name))
            {
                var new_plugin_name = plugin?.Name ?? "An unknown plugin";
                var msg = $"{new_plugin_name} has replaced the '{command_name}' chat command";
                Interface.Oxide.LogWarning(msg);
            }
            CommandManager.RegisteredCommands[command_name] = commandAttribute;

            // Hook the unload event
            if (plugin) plugin.OnRemovedFromManager += plugin_OnRemovedFromManager;
        }
 public void GetDescription_ReturnsDescriptionIfTypeNotSet()
 {
     // Arrange
     CommandAttribute cmd = new CommandAttribute("MockCommand", "ResourceName");
     // Act
     var actual = cmd.GetDescription();
     // Assert
     Assert.AreEqual("ResourceName", actual);
 }
 public void GetDescription_ReturnsResourceIfTypeSet()
 {
     // Arrange
     CommandAttribute cmd = new CommandAttribute(typeof(MockResourceType), "MockCommand", "ResourceName") { Description = "Not a string from a resouce." };
     // Act
     var actual = cmd.GetDescription();
     // Assert
     Assert.AreEqual("This is a Resource String.", actual);
 }
 public void GetUsageSummary_ReturnsUsageSummaryIfTypeNotSet()
 {
     // Arrange
     CommandAttribute cmd = new CommandAttribute(
         "MockCommand", "Description") { UsageSummary = "Not a Resource", UsageSummaryResourceName = "ResourceName" };
     // Act
     var actual = cmd.GetUsageSummary();
     // Assert
     Assert.AreEqual("Not a Resource", actual);
 }
 public void GetUsageSummary_ReturnsResourceIfTypeSet()
 {
     // Arrange
     CommandAttribute cmd = new CommandAttribute(typeof(MockResourceType),
         "MockCommand", "Description") { UsageSummary = "Not a Resource", UsageSummaryResourceName = "ResourceName" };
     // Act
     var actual = cmd.GetUsageSummary();
     // Assert
     Assert.AreEqual("This is a Resource String.", actual);
 }
        public void GetDescription_ReturnsResourceIfTypeSet()
        {
            // Arrange
            CommandAttribute cmd = new CommandAttribute(typeof(MockResourceType), "MockCommand", "ResourceName");

            //Act
            var actual = cmd.Description;

            // Assert
            Assert.Equal("This is a Resource String.", actual);
        }
        public void GetUsageDescription_ReturnsUsageDescriptionIfTypeNotSet()
        {
            // Arrange
            CommandAttribute cmd = new CommandAttribute(
                "MockCommand", "Description") { UsageDescription = "Not a Resource", UsageDescriptionResourceName = "ResourceName" };

            //Act
            var actual = cmd.UsageDescription;

            // Assert
            Assert.Equal("Not a Resource", actual);
        }
 public void TriggerCantBeNull()
 {
     CommandAttribute commandAttribute = new CommandAttribute();
     try
     {
         commandAttribute.Trigger = null;
         Assert.Fail();
     }
     catch(ArgumentNullException exception)
     {
         Assert.AreEqual("Trigger", exception.ParamName);
     }
     catch
     {
         Assert.Fail();
     }
 }
 public void ProtocolCantBeNull()
 {
     CommandAttribute commandAttribute = new CommandAttribute();
     try
     {
         commandAttribute.Protocol = null;
         Assert.Fail();
     }
     catch(ArgumentNullException exception)
     {
         Assert.AreEqual("Protocol", exception.ParamName);
     }
     catch
     {
         Assert.Fail();
     }
 }
 public void RegisterCommand(string cmd, CommandType type, CommandCallback callback)
 {
     if (type == CommandType.Console) return;
     var command_name = cmd.ToLowerInvariant();
     if (CommandManager.RegisteredCommands.ContainsKey(command_name))
     {
         throw new CommandAlreadyExistsException(command_name);
     }
     var commandAttribute = new CommandAttribute("/" + command_name, string.Empty)
     {
         Method = info =>
         {
             var player = ReignOfKingsCovalenceProvider.Instance.PlayerManager.GetPlayer(info.PlayerId.ToString());
             callback(info.Label, CommandType.Chat, player, info.Args);
         }
     };
     CommandManager.RegisteredCommands[command_name] = commandAttribute;
 }
Exemple #12
0
        static HBOptions()
        {
            _commands   = new Dictionary <string, PropertyInfo>();
            _attributes = new Dictionary <PropertyInfo, CommandAttribute>();

            PropertyInfo[] properties = typeof(HBOptions).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                var commandAtts = (CommandAttribute[])property.GetCustomAttributes(typeof(CommandAttribute), false);
                if (commandAtts.Length == 0)
                {
                    continue;
                }

                CommandAttribute commandAtt = commandAtts[0];
                _commands.Add(commandAtt.Name, property);
                _attributes.Add(property, commandAtt);
            }
        }
Exemple #13
0
        public ConsoleCommandDescriptor(Type t)
        {
            this.CommandType = t;
            var ca = CommandType.GetCustomAttributes(typeof(CommandAttribute), true).FirstOrDefault() as CommandAttribute;

            if (ca == null)
            {
                Info = new CommandAttribute()
                {
                    Keyword = CommandType.Name
                };
            }
            else
            {
                Info = ca;
            }

            this.LoadParameters();
        }
Exemple #14
0
        public void TestAttributes()
        {
            CommandInterpreter ci = new CommandInterpreter(new TestCommands());

            IOption option = ci.Options[0];

            //[Option("Other")]
            Assert.AreEqual("Other", option.DisplayName);
            Assert.AreEqual(typeof(int), option.Type);
            //[AliasName("alias")]
            //[System.ComponentModel.DisplayName("ingored-due-to-OptionAttribute")]
            Assert.AreEqual(2, option.AllNames.Length);
            Assert.IsTrue(new List <string>(option.AllNames).Contains("Other"));
            Assert.IsTrue(new List <string>(option.AllNames).Contains("alias"));
            //[System.ComponentModel.Description("description")]
            Assert.AreEqual("description", option.Description);
            //[System.ComponentModel.Category("category")]
            Assert.AreEqual("category", option.Category);
            //[System.ComponentModel.Browsable(false)]
            Assert.AreEqual(false, option.Visible);
            //[System.ComponentModel.DefaultValue(-1)]
            Assert.AreEqual(-1, option.Value);

            {
                CommandFilterAttribute a = new CommandFilterAttribute();
                Assert.IsFalse(a.Visible);
                a.Visible = true;
                Assert.IsFalse(a.Visible);
            }
            {
                CommandAttribute a = new CommandAttribute();
                a.DisplayName = "test";
                a.AliasNames  = new string[] { "alias" };
                Assert.AreEqual("test,alias", String.Join(",", a.AllNames));
                IDisplayInfo di = a;
                di.Help();                //no-op
            }
            {
                AllArgumentsAttribute a = new AllArgumentsAttribute();
                Assert.AreEqual(typeof(AllArgumentsAttribute), a.GetType());
            }
        }
Exemple #15
0
        public static CommandInfo GetCommandInfo(this Type type)
        {
            if (!Cache.TryGetValue(type, out CommandInfo info))
            {
                CommandAttribute cmd = type.GetCustomAttribute <CommandAttribute>();
                if (cmd != null)
                {
                    info = new CommandInfo
                    {
                        Name            = cmd.Name,
                        Description     = cmd.Description,
                        LongDescription = cmd.LongDescription
                    };

                    Cache.TryAdd(type, info);
                }
            }

            return(info);
        }
Exemple #16
0
        /// <summary>
        /// Resolves <see cref="CommandSchema"/>.
        /// </summary>
        public static CommandSchema Resolve(Type type)
        {
            if (!CommandSchema.IsCommandType(type))
            {
                throw InternalTypinExceptions.InvalidCommandType(type);
            }

            CommandAttribute attribute = type.GetCustomAttribute <CommandAttribute>() !;

            string?name = attribute.Name;

            CommandOptionSchema[] builtInOptions = string.IsNullOrWhiteSpace(name)
                ? new[] { CommandOptionSchema.HelpOption, CommandOptionSchema.VersionOption }
                : new[] { CommandOptionSchema.HelpOption };

            CommandParameterSchema?[] parameters = type.GetProperties()
                                                   .Select(CommandParameterSchemaResolver.TryResolve)
                                                   .Where(p => p != null)
                                                   .ToArray();

            CommandOptionSchema?[] options = type.GetProperties()
                                             .Select(CommandOptionSchemaResolver.TryResolve)
                                             .Where(o => o != null)
                                             .Concat(builtInOptions)
                                             .ToArray();

            CommandSchema command = new CommandSchema(
                type,
                name,
                attribute.Description,
                attribute.Manual,
                attribute.InteractiveModeOnly,
                parameters !,
                options !
                );

            ValidateParameters(command);
            ValidateOptions(command);

            return(command);
        }
Exemple #17
0
        /// <summary>
        /// Builds the help message.
        /// </summary>
        public override void RunCommand()
        {
            List <Assembly> assemblies     = AppDomain.CurrentDomain.GetAssemblies().ToList();
            List <Type>     commandClasses = new List <Type>();

            foreach (var assembly in assemblies)
            {
                List <Type> comandTypes = assembly.GetTypes().Where(tp => tp.IsSubclassOf(typeof(AbstractCommand))).ToList();
                commandClasses.AddRange(comandTypes);
            }

            StringBuilder helpStringBuilder = new StringBuilder();

            foreach (var commandClass in commandClasses)
            {
                CommandAttribute attr = commandClass.GetCustomAttribute(typeof(CommandAttribute)) as CommandAttribute;
                helpStringBuilder.AppendLine($"{attr.CommandString}: {attr.CommandDescription}");
            }

            this.helpmessage = helpStringBuilder.ToString();
        }
    public TerminalMethods()
    {
        methods = new List <MethodInfo>();
        var assembly = System.AppDomain.CurrentDomain.Load("Assembly-CSharp");

        methods = assembly
                  .GetTypes()
                  .SelectMany(x => x.GetMethods())
                  .Where(y => y.GetCustomAttributes(true).OfType <CommandAttribute>().Any()).ToList();
        foreach (var method in methods)
        {
            foreach (var attribute in method.GetCustomAttributes(true))
            {
                if (attribute is CommandAttribute) //Does not pass
                {
                    CommandAttribute attr = (CommandAttribute)attribute;
                    methodNames.Add(attr.commandName);
                }
            }
        }
    }
Exemple #19
0
        public async Task DisableCommand([Remainder] string commandName)
        {
            CommandAttribute command = GetCommandAttribute();

            if (commandName == command.Text)
            {
                logger.LogWarning("Disabling this command is not recommended...");
                return;
            }

            command = GetCommandAttribute(nameof(EnableCommand));
            if (commandName == command.Text)
            {
                logger.LogWarning("Disabling this command is not recommended...");
                return;
            }

            logger.LogDebug("Disabling a command...");
            RuntimeChanges.DisabledCommands.Add(commandName);
            await Reply("Completed");
        }
Exemple #20
0
        private void LoadCommands(Type type)
        {
            var methods = type.GetMethods();

            foreach (MethodInfo method in methods)
            {
                CommandAttribute commandAttribute = Attribute.GetCustomAttribute(method, typeof(CommandAttribute), false) as CommandAttribute;
                if (commandAttribute == null)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(commandAttribute.Command))
                {
                    commandAttribute.Command = method.Name;
                }

                StringBuilder sb = new StringBuilder();
                sb.Append("/");
                sb.Append(commandAttribute.Command);
                var parameters = method.GetParameters();
                if (parameters.Length > 0)
                {
                    sb.Append(" ");
                }
                foreach (var parameter in parameters)
                {
                    sb.AppendFormat("<{0}> ", parameter.Name);
                }
                commandAttribute.Usage = sb.ToString().Trim();

                DescriptionAttribute descriptionAttribute = Attribute.GetCustomAttribute(method, typeof(DescriptionAttribute), false) as DescriptionAttribute;
                if (descriptionAttribute != null)
                {
                    commandAttribute.Description = descriptionAttribute.Description;
                }

                _pluginCommands.Add(method, commandAttribute);
            }
        }
Exemple #21
0
    private void StartCommands()
    {
        commands.Clear();

        var methods = GetType().GetMethods();

        for (int i = 0; i < methods.Length; i++)
        {
            foreach (Attribute attribute in Attribute.GetCustomAttributes(methods[i]))
            {
                if (attribute.GetType() == typeof(CommandAttribute))
                {
                    CommandAttribute commandAttribute = (CommandAttribute)attribute;
                    List <ParamType> paramTypes       = new List <ParamType>();
                    var parameters = methods[i].GetParameters();
                    for (int p = 0; p < parameters.Length; p++)
                    {
                        if (parameters[p].ParameterType == typeof(string))
                        {
                            paramTypes.Add(ParamType.String);
                        }
                        else if (parameters[p].ParameterType == typeof(bool))
                        {
                            paramTypes.Add(ParamType.Bool);
                        }
                        else if (parameters[p].ParameterType == typeof(int))
                        {
                            paramTypes.Add(ParamType.Int);
                        }
                        else if (parameters[p].ParameterType == typeof(float))
                        {
                            paramTypes.Add(ParamType.Float);
                        }
                    }

                    RegisterCommand(commandAttribute, paramTypes, methods[i].Name);
                }
            }
        }
    }
Exemple #22
0
        public Command(Type type, ref object typeInstance, MethodInfo commandMethod)
        {
            Type          = type;
            CommandMethod = commandMethod;

            CommandAttribute commandAttribute = commandMethod.GetCustomAttribute <CommandAttribute>();

            Name = (commandAttribute.CommandName == "" ? commandMethod.Name : commandAttribute.CommandName).ToLowerInvariant();
            _triggers.Add(Name);
            Hidden          = commandAttribute.Hidden;
            DisableDMs      = commandAttribute.DisableDMs;
            GroupName       = commandAttribute.GroupName;
            PermissionLevel = commandAttribute.PermissionLevel;

            if (commandMethod.IsDefined(typeof(AliasAttribute), false))
            {
                _triggers = _triggers.Concat(commandMethod.GetCustomAttribute <AliasAttribute>().Aliases).ToList();
            }

            Description = commandMethod.IsDefined(typeof(DescriptionAttribute), false) ?
                          commandMethod.GetCustomAttribute <DescriptionAttribute>().DescriptionText : DescriptionAttribute.NoDescriptionText;

            Permissions = commandMethod.IsDefined(typeof(RequiredPermissionsAttribute), false) ?
                          commandMethod.GetCustomAttribute <RequiredPermissionsAttribute>().Permissions : Permissions.None;

            UserWhitelist = commandMethod.IsDefined(typeof(UserWhitelistAttribute), false) ?
                            commandMethod.GetCustomAttribute <UserWhitelistAttribute>().UserIds : null;

            IList <Type> args = new List <Type>();

            foreach (ParameterInfo param in commandMethod.GetParameters())
            {
                args.Add(param.ParameterType);
                _parameters.Add(new CommandParameter(param));
            }
            args.Add(commandMethod.ReturnType);
            Type delDecltype = Expression.GetDelegateType(args.ToArray());

            MethodDelegate = Delegate.CreateDelegate(delDecltype, typeInstance, commandMethod.Name);
        }
Exemple #23
0
        private void RegisterCommands()
        {
            Assembly.GetEntryAssembly().GetTypesAssignableFrom <BaseHandler>().ForEach((type) =>
            {
                Dictionary <string, MethodInfo> commands = new Dictionary <string, MethodInfo>();
                MethodInfo[] methods = type.GetMethods();

                foreach (MethodInfo method in methods)
                {
                    CommandAttribute attribute = method.GetCustomAttributes(true).FirstOrDefault(x => x is CommandAttribute == true) as CommandAttribute;

                    if (attribute is not object)
                    {
                        continue;
                    }

                    attribute.Commands.ForEach((command) => commands.Add(command, method));
                }

                _registeredHandlers.Add(type, commands);
            });
        }
Exemple #24
0
    public static void ShowCommandHelp(CommandAttribute attribute,
																		 string indent)
    {
        Console.Write(indent + attribute.Name);
        if (!String.IsNullOrEmpty(attribute.Alias)) Console.Write(" (alias {0})", attribute.Alias);
        Console.WriteLine();

        string description = attribute.Description;
        int x = 0;

        while (x < description.Length)
            {
                int y = Math.Min(x + 60, description.Length);
                int z = description.IndexOf(' ', y) + 1;
                if (z == 0) z = description.Length;

                Console.WriteLine(indent + "  " + description.Substring(x, z - x));
                x = z;
            }

        Console.WriteLine();
    }
Exemple #25
0
        private static string Parse(CommandAttribute attribute, CommandPrefixAttribute prefix)
        {
            var cmd = attribute?.Command;
            var pre = prefix?.Command;

            if (cmd == null && pre == null)
            {
                return(null);
            }

            if (cmd == null)
            {
                return(pre);
            }

            if (pre == null)
            {
                return(cmd);
            }

            return(pre + " " + cmd);
        }
Exemple #26
0
        public async Task HelpAsync(CommandContext context, [Description("HelpCommandParameter")] string commandName = null)
        {
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder {
                Color = new DiscordColor(ColorConstant.embedColor)
            };

            GuildsModel guild = context.Channel.IsPrivate ? null : await new GuildsDAO().GetAsync(new GuildsModel {
                ID = context.Guild.Id
            });
            Locale locale = new LocaleExtension().GetLocale(guild);

            if (commandName == null)
            {
                builder.Title = (await new StringsDAO().LoadAsync(new StringsModel {
                    Identifier = "HelpTitle",
                    Locale = locale,
                })).String.Replace("$prefix", guild.Prefix);
                Type[] types = typeof(HelpModule).Assembly.GetTypes();
                for (int i = 0; i < types.Length; i++)
                {
                    ModuleAttribute moduleAttr = types[i].GetCustomAttribute <ModuleAttribute>();
                    if (moduleAttr != null)
                    {
                        MethodInfo[] methods  = types[i].GetMethods();
                        string       commands = string.Empty;
                        for (int j = 0; j < methods.Length; j++)
                        {
                            CommandAttribute commandAttr = methods[j].GetCustomAttribute <CommandAttribute>();
                            if (commandAttr != null && methods[j].GetCustomAttribute <HiddenAttribute>() == null)
                            {
                                commands += $"`{commandAttr.Name}`, ";
                            }
                        }
                        if (commands.Length != 0)
                        {
                            builder.AddField((await new StringsDAO().LoadAsync(new StringsModel {
                                Locale = locale,
                                Identifier = moduleAttr.Name
                            })).String, commands[..^ 2]);
Exemple #27
0
        private Command HandleCommand(MethodInfo methodInfo)
        {
            if (!methodInfo.IsStatic)
            {
                throw new MethodNotStaticException(methodInfo);
            }
            if (methodInfo.ContainsGenericParameters)
            {
                throw new GenericParametersException(methodInfo);
            }

            CommandAttribute commandAttribute = methodInfo.GetCustomAttribute <CommandAttribute>(false);
            AliasAttribute   aliasAttribute   = methodInfo.GetCustomAttribute <AliasAttribute>(false);
            SummaryAttribute summaryAttribute = methodInfo.GetCustomAttribute <SummaryAttribute>(false);

            return(new Command(
                       name: commandAttribute.Name,
                       aliases: aliasAttribute?.Aliases,
                       summary: summaryAttribute?.Summary,
                       subCommands: new List <Command>(),
                       methodInfo: methodInfo));
        }
        public static async Task <HttpResponseMessage> ApplyAccruedInterestCommand(
            [HttpTrigger(AuthorizationLevel.Function, "POST", Route = @"ApplyAccruedInterest/{accountnumber}")] HttpRequestMessage req,
            string accountnumber,
            [DurableClient] IDurableOrchestrationClient applyInterestOrchestration)
        {
            #region Tracing telemetry
            Activity.Current.AddTag("Account Number", accountnumber);
            #endregion

            // Set the start time for how long it took to process the message
            DateTime startTime = DateTime.UtcNow;

            // use a durable functions GUID so that the orchestration is replayable

            //Command cmdApplyAccruedInterest
            CommandAttribute commandToRun = new CommandAttribute("Bank", "Apply Accrued Interest");
            string           commandId    = await applyInterestOrchestration.StartNewAsync(nameof(StartCommand), commandToRun);

            commandToRun = new CommandAttribute("Bank", "Apply Accrued Interest", commandId);
            Command cmdApplyAccruedInterest = new Command(commandToRun);

            // No parameters passed in - but set the as-of date/time so that if this command is
            // re-executed it does not return a different result
            InstanceParameter paramAsOf = new InstanceParameter(cmdApplyAccruedInterest.AsAttribute(), "As Of Date", startTime);
            await applyInterestOrchestration.StartNewAsync(nameof(SetParametersCommandStep), paramAsOf);

            InstanceParameter paramAccount = new InstanceParameter(cmdApplyAccruedInterest.AsAttribute(), "Account Number", accountnumber);
            await applyInterestOrchestration.StartNewAsync(nameof(SetParametersCommandStep), paramAccount);

            // The rest of the command is performed by a durable functions orchestration
            await applyInterestOrchestration.StartNewAsync(nameof(ApplyAccruedInterestCommandStep), cmdApplyAccruedInterest.AsAttribute());

            // Return that the command has been initiated...
            return(req.CreateResponse <FunctionResponse>(System.Net.HttpStatusCode.OK,
                                                         FunctionResponse.CreateResponse(startTime,
                                                                                         false,
                                                                                         $"Interest accrual process for { accountnumber} initiated"),
                                                         FunctionResponse.MEDIA_TYPE));
        }
Exemple #29
0
        public static CommandAttribute GetCommand(this MemberInfo member)
        {
            try
            {
                CommandAttribute attribute  = null;
                object[]         attributes = member.GetCustomAttributes(typeof(CommandAttribute), false);
                for (int a = 0; a < attributes.Length; a++)
                {
                    if (attributes[a].GetType() == typeof(CommandAttribute))
                    {
                        attribute = attributes[a] as CommandAttribute;
                        return(attribute);
                    }
                }
            }
            catch
            {
                //this could happen due to a TypeLoadException in builds
            }

            return(null);
        }
    /// <summary>
    /// Iterates through all command classes searching for one with the correct CommandAttribute matching the commandName
    /// </summary>
    /// <returns>The vsn command.</returns>
    /// <param name="commandName">Command name.</param>
    /// <param name="vsnArguments">Vsn arguments.</param>
    private VsnCommand InstantiateVsnCommand(string commandName, List <VsnArgument> vsnArguments)
    {
        foreach (Type type in VsnController.instance.possibleCommandTypes)
        {
            foreach (Attribute attribute in type.GetCustomAttributes(false))
            {
                if (attribute is CommandAttribute)
                {
                    CommandAttribute commandAttribute = (CommandAttribute)attribute;

                    if (commandAttribute.CommandString == commandName)
                    {
                        VsnCommand vsnCommand = Activator.CreateInstance(type) as VsnCommand;
                        vsnCommand.InjectArguments(vsnArguments);

                        if (vsnCommand.CheckSyntax() == false)
                        {
                            string line = commandName + ": ";

                            foreach (VsnArgument c in vsnArguments)
                            {
                                line += c.GetStringValue() + "/" + c.GetReference() + "/" + c.GetNumberValue() + " - ";
                            }
                            Debug.LogError("Invalid syntax for this command: " + line);
                            return(new InvalidCommand());
                        }

                        // TODO add metadata like line number?...

                        return(vsnCommand);
                    }
                }
            }
        }

        Debug.Log("Got a null");
        return(null);
    }
Exemple #31
0
 private static IEnumerable <string> GetCommandStrings(CommandAttribute attribute, ICollection <CommandPrefixAttribute> prefixes)
 {
     //TODO: Cleanup
     if (!prefixes.Any())
     {
         var cmd = Parse(attribute, null);
         if (cmd != null)
         {
             yield return(cmd.Trim());
         }
     }
     else
     {
         foreach (var prefix in prefixes)
         {
             var cmd = Parse(attribute, prefix);
             if (cmd != null)
             {
                 yield return(cmd.Trim());
             }
         }
     }
 }
Exemple #32
0
        private void AddCommands(IEnumerable <MethodInfo> commands)
        {
            int numCommands = 0;

            foreach (var command in commands)
            {
                //Debug.Log(command.Name);

                try
                {
                    CommandAttribute commandAttr = (CommandAttribute)command.GetCustomAttributes(typeof(CommandAttribute), false)[0];
                    Console.AddCommand(command, commandAttr.useClassName, commandAttr.alias, commandAttr.className, commandAttr.description);
                    numCommands++;
                }
                catch (Exception e)
                {
                    LogError("Failed to add command " + command.Name);
                    LogException(e);
                }
            }

            Log($"Registered {numCommands} console commands!");
        }
        public MessagesSendParams InvokeCommand(UserPreferences user, String cmd, params String[] args)
        {
            MessagesSendParams p       = null;
            VkCommandContext   context = new VkCommandContext(user, null, cmd, args);

            context.InitWithFunc((@params) =>
            {
                p = @params;
                return(null);
            });
            var method           = CommandAttribute.FindMethods <VkCommandContext>(cmd, assembly: Assembly.GetAssembly(typeof(VkCommands))).First();
            var hasAdminRequired = CommandAttribute.HasAdminPermissionsRequired(method);

            if (hasAdminRequired.Value && !user.IsAdmin)
            {
                Assert.Fail("User is not admin");
            }
            var    ctor     = CommandAttribute.GetConstructorInfo(method);
            Object instance = ctor.Invoke(new[] { context });

            method.Invoke(instance, new Object[] { });
            return(p);
        }
Exemple #34
0
        public async Task Alias(CommandContext ctx, [Description("Command to execute.")] string alias)
        {
            string prefix = null;

            foreach (string p in Program.Prefixes)
            {
                if (alias.StartsWith(p))
                {
                    prefix = p;
                }
            }
            Type commandType = COMMAND_TYPES[prefix];
            IEnumerable <MethodInfo> methods = commandType.GetMethods().Where(method =>
                                                                              method.GetCustomAttributes(typeof(CommandAttribute), false).Length > 0);

            foreach (MethodInfo method in methods)
            {
                CommandAttribute command = (CommandAttribute)method.GetCustomAttributes(typeof(CommandAttribute), false).First();
                // Match starts with command but also isn't a command that starts with a superstring of the given command.
                Regex regex = new Regex($"^{prefix}\\s?{command.Name}(\\s{1}|$)");
                if (regex.Match(alias).Success)
                {
                    Command        aliasCommand     = ctx.CommandsNext.RegisteredCommands[command.Name];
                    string         commandArguments = alias.Split(command.Name)[1];
                    CommandContext context          = ctx.CommandsNext.CreateFakeContext(ctx.User, ctx.Channel, alias, prefix, aliasCommand, commandArguments);
                    DiscordMessage response         = await ctx.RespondAsync($"Executing `{alias}`");

                    await ctx.Message.DeleteAsync();

                    await context.CommandsNext.ExecuteCommandAsync(context);

                    await response.DeleteAsync();

                    return;
                }
            }
        }
Exemple #35
0
        public void AddChatCommand(string name, Plugin plugin, string callback_name)
        {
            var command_name = name.ToLowerInvariant();

            ChatCommand cmd;

            if (chatCommands.TryGetValue(command_name, out cmd))
            {
                var previous_plugin_name = cmd.Plugin?.Name ?? "an unknown plugin";
                var new_plugin_name      = plugin?.Name ?? "An unknown plugin";
                var msg = $"{new_plugin_name} has replaced the '{command_name}' chat command previously registered by {previous_plugin_name}";
                Interface.Oxide.LogWarning(msg);
            }

            cmd = new ChatCommand(command_name, plugin, callback_name);

            // Add the new command to collections
            chatCommands[command_name] = cmd;

            var commandAttribute = new CommandAttribute("/" + command_name, string.Empty);
            var action           = (Action <CommandInfo>)Delegate.CreateDelegate(typeof(Action <CommandInfo>), this, GetType().GetMethod("HandleCommand", BindingFlags.NonPublic | BindingFlags.Instance));

            commandAttribute.Method = action;
            if (CommandManager.RegisteredCommands.ContainsKey(command_name))
            {
                var new_plugin_name = plugin?.Name ?? "An unknown plugin";
                var msg             = $"{new_plugin_name} has replaced the '{command_name}' chat command";
                Interface.Oxide.LogWarning(msg);
            }
            CommandManager.RegisteredCommands[command_name] = commandAttribute;

            // Hook the unload event
            if (plugin)
            {
                plugin.OnRemovedFromManager += plugin_OnRemovedFromManager;
            }
        }
Exemple #36
0
        /// <summary>
        /// Retrieves the command attribute for a command string.
        /// </summary>
        /// <param name="commandName">The string to search.</param>
        /// <returns>CommandAttribute if found else null.</returns>
        private CommandAttribute GetCommand(string commandName)
        {
            CommandAttribute selectedCommand = null;
            int nearestEditDistance          = int.MaxValue;

            foreach (var cmd in _commandMap.Keys)
            {
                if (cmd.Name.Equals(commandName))
                {
                    selectedCommand = cmd;
                    break;
                }
                else if (cmd.Name.StartsWith(commandName))
                {
                    int edit = cmd.Name.DamerauLevenshteinDistance(commandName, 10);
                    if (nearestEditDistance > edit)
                    {
                        nearestEditDistance = edit;
                        selectedCommand     = cmd;
                    }
                }
            }
            return(selectedCommand);
        }
Exemple #37
0
        public override void ConsolerunCommand(string[] args)
        {
            Log.Instance.Info("asdas asd asd!");
            Dictionary <string, Type> cd   = ServerInstance.Instance.CommandManager.GetCommandDictionary();
            List <String>             list = cd.Keys.ToList();

            list.Sort();

            List <CommandAttribute> commands = new List <CommandAttribute>();

            foreach (String cmd in list)
            {
                Type             t  = cd[cmd];
                CommandAttribute ca = Command.GetCommandAttribute(t);
                commands.Add(ca);
            }

            GetPluginHelper.GetLogger.Info(String.Format("==== Help Page ===="));

            foreach (CommandAttribute command1 in commands)
            {
                GetPluginHelper.GetLogger.Info("/" + command1.CommandName + ": " + command1.Description);
            }
        }
        public ServiceCommand ConvertServiceCommand(CommandAttribute command)
        {
            var result = new ServiceCommand();

            if (command != null)
            {
                result = new ServiceCommand
                {
                    CircuitBreakerForceOpen        = command.CircuitBreakerForceOpen,
                    ExecutionTimeoutInMilliseconds = command.ExecutionTimeoutInMilliseconds,
                    FailoverCluster                 = command.FailoverCluster,
                    Injection                       = command.Injection,
                    RequestCacheEnabled             = command.RequestCacheEnabled,
                    Strategy                        = command.Strategy,
                    InjectionNamespaces             = command.InjectionNamespaces,
                    BreakeErrorThresholdPercentage  = command.BreakeErrorThresholdPercentage,
                    BreakerForceClosed              = command.BreakerForceClosed,
                    BreakerRequestVolumeThreshold   = command.BreakerRequestVolumeThreshold,
                    BreakeSleepWindowInMilliseconds = command.BreakeSleepWindowInMilliseconds,
                    MaxConcurrentRequests           = command.MaxConcurrentRequests
                };
            }
            return(result);
        }
Exemple #39
0
        internal static MethodInfo GetCanExecuteMethod(Type type, MethodInfo methodInfo, CommandAttribute commandAttribute, Func <string, Exception> createException, Func <MethodInfo, bool> canAccessMethod)
        {
            if (commandAttribute != null && commandAttribute.CanExecuteMethod != null)
            {
                CheckCanExecuteMethod(methodInfo, createException, commandAttribute.CanExecuteMethod, canAccessMethod);
                return(commandAttribute.CanExecuteMethod);
            }
            bool       hasCustomCanExecuteMethod = commandAttribute != null && !string.IsNullOrEmpty(commandAttribute.CanExecuteMethodName);
            string     canExecuteMethodName      = hasCustomCanExecuteMethod ? commandAttribute.CanExecuteMethodName : GetCanExecuteMethodName(methodInfo);
            MethodInfo canExecuteMethod          = type.GetMethod(canExecuteMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            if (hasCustomCanExecuteMethod && canExecuteMethod == null)
            {
                throw createException(string.Format(Error_MethodNotFound, commandAttribute.CanExecuteMethodName));
            }
            if (canExecuteMethod != null)
            {
                CheckCanExecuteMethod(methodInfo, createException, canExecuteMethod, canAccessMethod);
            }
            return(canExecuteMethod);
        }
Exemple #40
0
        public void RegisterAttributeCommands(Assembly assembly = null)
        {
            Bot b = Bot.Instance;

            if (assembly == null)
            {
                assembly = Assembly.GetEntryAssembly();
            }

            var modules = assembly.GetTypes()
                          .Where(m => m.GetCustomAttributes <ModuleAttribute>().Count() > 0)
                          .ToArray();

            foreach (var m in modules)
            {
                object instance = null;

                Module newModule = new Module(instance);

                try
                {
                    instance = Activator.CreateInstance(Type.GetType(m.AssemblyQualifiedName), newModule, b);
                }
                catch
                {
                    try
                    {
                        instance = Activator.CreateInstance(Type.GetType(m.AssemblyQualifiedName), newModule);
                    }
                    catch
                    {
                        instance = Activator.CreateInstance(Type.GetType(m.AssemblyQualifiedName));
                    }
                }

                newModule.SetInstance(instance);

                ModuleAttribute mAttrib = m.GetCustomAttribute <ModuleAttribute>();
                newModule.Name          = mAttrib.module.Name.ToLower();
                newModule.Nsfw          = mAttrib.module.Nsfw;
                newModule.CanBeDisabled = mAttrib.module.CanBeDisabled;

                var methods = m.GetMethods()
                              .Where(t => t.GetCustomAttributes <CommandAttribute>().Count() > 0)
                              .ToArray();

                foreach (var x in methods)
                {
                    CommandEvent     newEvent         = new CommandEvent();
                    CommandAttribute commandAttribute = x.GetCustomAttribute <CommandAttribute>();

                    newEvent = commandAttribute.command;
                    newEvent.ProcessCommand = async(context) => await(Task) x.Invoke(instance, new object[] { context });
                    newEvent.Module         = newModule;

                    CommandEvent foundCommand = newModule.Events.Find(c => c.Name == newEvent.Name);

                    if (foundCommand != null)
                    {
                        foundCommand.Default(newEvent.ProcessCommand);
                    }
                    else
                    {
                        newModule.AddCommand(newEvent);
                    }

                    foreach (var a in newEvent.Aliases)
                    {
                        commandCache.Add(a.ToLower(), newEvent);
                    }
                    commandCache.Add(newEvent.Name.ToLower(), newEvent);
                }

                var services = m.GetProperties().Where(x => x.GetCustomAttributes <ServiceAttribute>().Count() > 0).ToArray();

                foreach (var s in services)
                {
                    BaseService service = Activator.CreateInstance(s.PropertyType, true) as BaseService;
                    var         attrib  = s.GetCustomAttribute <ServiceAttribute>();

                    service.Name = attrib.Name;
                    newModule.Services.Add(service);
                }

                OnModuleLoaded?.Invoke(newModule);

                modulesLoaded.Add(newModule);
            }
        }
Exemple #41
0
        public void RegisterAttributeCommands()
        {
            Assembly assembly = Assembly.GetEntryAssembly();

            var modules = assembly.GetTypes()
                          .Where(m => m.GetCustomAttributes <ModuleAttribute>().Count() > 0)
                          .ToArray();

            foreach (var m in modules)
            {
                RuntimeModule newModule = new RuntimeModule();
                object        instance  = null;

                try
                {
                    instance = (object)Activator.CreateInstance(Type.GetType(m.AssemblyQualifiedName), newModule);
                }
                catch
                {
                    instance = (object)Activator.CreateInstance(Type.GetType(m.AssemblyQualifiedName));
                }

                newModule.EventSystem = this;

                ModuleAttribute mAttrib = m.GetCustomAttribute <ModuleAttribute>();
                newModule.Name          = mAttrib.module.Name.ToLower();
                newModule.Nsfw          = mAttrib.module.Nsfw;
                newModule.CanBeDisabled = mAttrib.module.CanBeDisabled;

                var methods = m.GetMethods()
                              .Where(t => t.GetCustomAttributes <CommandAttribute>().Count() > 0)
                              .ToArray();

                foreach (var x in methods)
                {
                    RuntimeCommandEvent newEvent         = new RuntimeCommandEvent();
                    CommandAttribute    commandAttribute = x.GetCustomAttribute <CommandAttribute>();

                    newEvent = commandAttribute.command;
                    newEvent.ProcessCommand = async(context) => await(Task) x.Invoke(instance, new object[] { context });
                    newEvent.Module         = newModule;

                    ICommandEvent foundCommand = newModule.Events.Find(c => c.Name == newEvent.Name);

                    if (foundCommand != null)
                    {
                        if (commandAttribute.on != "")
                        {
                            foundCommand.On(commandAttribute.On, newEvent.ProcessCommand);
                        }
                        else
                        {
                            foundCommand.Default(newEvent.ProcessCommand);
                        }
                    }
                    else
                    {
                        newModule.AddCommand(newEvent);
                    }
                }

                newModule.InstallAsync(bot).GetAwaiter().GetResult();
            }
        }
Exemple #42
0
        public void HandleCommand(UserManager <User> userManager, string message, Player player)
        {
            try
            {
                string commandText = message.Split(' ')[0];
                message     = message.Replace(commandText, "").Trim();
                commandText = commandText.Replace("/", "").Replace(".", "");

                string[] arguments = message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                List <CommandAttribute> foundCommands = new List <CommandAttribute>();
                foreach (var handlerEntry in _pluginCommands)
                {
                    CommandAttribute commandAttribute = handlerEntry.Value;
                    if (!commandText.Equals(commandAttribute.Command, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    MethodInfo method = handlerEntry.Key;
                    if (method == null)
                    {
                        return;
                    }

                    foundCommands.Add(commandAttribute);

                    var authorizationAttributes = method.GetCustomAttributes <AuthorizeAttribute>(true);
                    foreach (AuthorizeAttribute authorizationAttribute in authorizationAttributes)
                    {
                        if (userManager == null)
                        {
                            player.SendMessage($"UserManager not found. You are not permitted to use this command!");
                            return;
                        }

                        User user = userManager.FindByName(player.Username);
                        if (user == null)
                        {
                            player.SendMessage($"No registered user '{player.Username}' found. You are not permitted to use this command!");
                            return;
                        }

                        var userIdentity = userManager.CreateIdentity(user, "none");
                        if (!authorizationAttribute.OnAuthorization(new GenericPrincipal(userIdentity, new string[0])))
                        {
                            player.SendMessage("You are not permitted to use this command!");
                            return;
                        }
                    }

                    if (ExecuteCommand(method, player, arguments))
                    {
                        return;
                    }
                }

                foreach (var commandAttribute in foundCommands)
                {
                    player.SendMessage($"Usage: {commandAttribute.Usage}");
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex);
            }
        }
Exemple #43
0
 public static int CommandAttributeCompare( CommandAttribute _cmd1, CommandAttribute _cmd2 )
 {
     return _cmd1.command.CompareTo( _cmd2.command );
 }
 public void Protocol()
 {
     CommandAttribute commandAttribute = new CommandAttribute();
     commandAttribute.Protocol = "IRC";
     Assert.AreEqual("IRC", commandAttribute.Protocol);
 }
 public void Trigger()
 {
     CommandAttribute commandAttribute = new CommandAttribute();
     commandAttribute.Trigger = "NICK";
     Assert.AreEqual("NICK", commandAttribute.Trigger);
 }
Exemple #46
0
 private void PrintCommand(int maxWidth, CommandAttribute commandAttribute)
 {
     Console.Write(" {0, -" + maxWidth + "}   ", GetCommandText(commandAttribute));
     var startIndex = maxWidth + 4;
     Console.PrintJustified(startIndex, commandAttribute.Description);
 }
Exemple #47
0
 private static string GetCommandText(CommandAttribute commandAttribute)
 {
     return commandAttribute.CommandName + GetAltText(commandAttribute.AltName);
 }
Exemple #48
0
 private void PrintCommand(int maxWidth, CommandAttribute commandAttribute)
 {
     // Write out the command name left justified with the max command's width's padding
     Console.Write(" {0, -" + maxWidth + "}   ", GetCommandText(commandAttribute));
     // Starting index of the description
     int descriptionPadding = maxWidth + 4;
     Console.PrintJustified(descriptionPadding, commandAttribute.Description);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandMetadata" /> class.
 /// </summary>
 /// <param name="commandType">Type of the command metadata belongs to.</param>
 /// <param name="attribute">Command attribute instance assigned to the target type.</param>
 private CommandMetadata(Type commandType, CommandAttribute attribute)
 {
     CommandType = commandType;
     _attribute = attribute;
 }
 public MockCommand(CommandAttribute attribute)
 {
     _attribute = attribute;
 }
Exemple #51
0
 public Component(IComponent instance, CommandAttribute command)
 {
     this.Instance = instance;
     this.Command = command;
 }