.NET Tutorial

C# Example:

The below text demonstrates some of the features of the library. This demo application is available in the GitHub repository.

In the command usage shown, "<argument>" represents a required parameter, and "[argument]" represents an optional parameter.

Getting Started:

Getting started is very easy, first, create a parser object to parse your commands:

Parser = CommandParser.CreateNew();

Customize the command prefix by using:

 Parser = CommandParser.CreateNew().UsePrefix(string.Empty);

Let's also add a handler to provide messages when a parsing error occurs:

 Parser = CommandParser.CreateNew().UsePrefix(string.Empty).OnError(OnParseError);
...
private static void OnParseError(object sender, string message)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine(message);
   Console.ForegroundColor = ConsoleColor.Gray;
}

Now that the parser is set up, we can add a simple command. This command is called "Hello", and can be called by typing the alias "hello". Commands can have multiple aliases that will execute the action. In this case, the action will print out "Hello World" to the console.

Parser.AddCommand(Command
.Create("Hello")
.AddAlias("hello")
.SetDescription("Prints: 'Hello World!'")
.SetAction((arguments, data) =>
{
    Console.WriteLine("Hello World!");
}));

Now we have everything set up, so we can now call the Parser.Parse(input) method to handle the input. You would add this to your game or applications chat or console.

Console.WriteLine("\nEnter command:\n");
while (true)
{
    Console.ForegroundColor = ConsoleColor.Green;
    Console.Write("$ ");
    Console.ForegroundColor = ConsoleColor.Gray;

    //Read input and parse command
    var input = Console.ReadLine();
    Parser.Parse(input);
}

Try typing into the console or your application now, you should be able to type "hello" if you are using an empty prefix, or "/hello" with the default prefix.

Now, lets make a simple ban command that makes use of an argument.

Parser.AddCommand(Command
    .Create("Ban User") 
    .AddAlias("ban")
    .AddAlias("banuser")
    .SetDescription("Bans a user from the server.")
    .SetAction((arguments, data) =>
    {
         //Retrieve the value of the argument named "user"
         Console.WriteLine("{0} has been banned!" + arguments.FromName("user"));
    })
    .AddArgument(Argument //Add an argument named "User"
        .Create("User")));

Now, we can type "/ban Bob" to ban the user Bob. Of course, actual logic would be more than a simple console log. You can add multiple arguments to a command, and even nest them inside each other to create groups of optional arguments. Advanced Features:

Here are some helpful and more advanced features that will be useful for creating commands discussed below:

Optional Arguments:

Optional arguments can be created by calling the MakeOptional() method on an argument. Note that optional arguments must come last. All arguments are required by default. Default Values:

Optional arguments can have default values specified in the case that they are not specified by using the SetDefault(value) method on an argument. Note that optional arguments must come last.

Enum Arguments:

An "Enum" argument is an argument that is limited to a set of specific values. Instead of any value, they must be one of the defined choices set by the AddOption(argument) method. This is most useful for creating different options within a command, such as "On" or "Off". Each option can have its own sub-arguments that vary depending on the option. Below is an example of an enum argument for a mail system that allows users to read, clear, and send mail in a game.

Parser.AddCommand(Command
    .Create("Mail")
    .AddAlias("mail")
    .SetDescription("Allows users to send messages.")
    .SetAction(OnMailExecuted)
    //Note a deep nesting of arguments.
    .AddArgument(Argument
        .Create("type")
        .MakeOptional()
        //Note command options. These turn the "type" argument into an enum style list of values.
        //The user has to type read, clear, or send (Which has it's own nested arguments).
        .AddOption(Argument.Create("read"))
        .AddOption(Argument.Create("clear"))
        .AddOption(Argument.Create("send")
            .AddArgument((Argument.Create("user")))
            .AddArgument((Argument.Create("message"))))));

Note how the send option contains nested "user" and "message" arguments, while the other options require no parameters

Argument Validation:

Arguments can be validated using the ValidationRule class. It comes with some handy rules such as email, IP, alphanumerical, etc. You can also define your own custom rules to validate arguments against. Below is an example use in a register command that only allows alphanumerical usernames and valid emails.

Parser.AddCommand(Command.Create("Register").AddAlias("register").SetDescription("Create an account")
.SetAction((arguments, data) =>
{
       var user = arguments.FromName("username");
        var email = arguments.FromName("email");
        Console.WriteLine("{0} ({1}) has registered.", user, email);
})
//Note argument validator.
.AddArgument(Argument.Create("username").SetValidator(Argument.ValidationRule.AlphaNumerical))
.AddArgument(Argument.Create("password"))
.AddArgument(Argument.Create("email").SetValidator(Argument.ValidationRule.Email)));

Access Levels:

Commands can be restricted to certain users and situations by adding an access level through RestrictAccess(int accessLevel) and calling the parser's Parse(int level) method with the specified level. If a commands level is less than the specified level when parsing, it will not be allowed to run.

Command Pre-Conditions:

Commands can be given a condition using the SetAction(Action<Argument[]> action) method. The action specified will be ran before the command is executed. If it fails, by returning an error in the form of a string, the error will be sent to the parser's ParseError event, otherwise, the command will be executed.

Command Data:

Data can be passed to the command by the calling code by using command data. For example, a username could be passed to the command so the command itself knows who sent it.

Parse.Parse(input, "Test")

The data "Test" can be used in the command through the data parameter.

Command.SetAction((arguments, data) =>

More Documentation:

We suggest you take a look at the demo application to learn a range of advanced commands that can be made. The parsing code is well documented and will be able to explain any other features that were not covered here. If you have any questions, feel free to make a post on our forums.