📜 ⬆️ ⬇️

NConsoler - parsing console application arguments

Usually you have to spend a lot of time parsing console arguments in console applications. On the Internet, I found several systems that simplify this task, but they seemed cumbersome to me, so it was decided to create a new system based on metainformation - NConsoler.

The task was to turn a certain set of arguments at the input into a call to a specific method. If there is something wrong with the arguments, then an error should be displayed. Also on the meta-information, you can make simple help messages.
So, in order for the system to know which method to use, you need to mark it in some way. Attributes work well with this. I made an attribute of Action :
[ Action ]
public static void Method(...)...

Naturally, some arguments may be mandatory, and some may not. This should also be indicated as meta-information.
[ Action ]
public static void Method(
[ Required ] string name,
[ Optional ( true )] bool flag)...

since all parameters must be passed to the method, then for optional ones, you must specify a default value
Enough for a start. Now you need to run the method for execution. Let's do this in the Main method:
public static void Main( params string [] args) {
Consolery .Run( typeof ( Program ), args);
}

in the Run method, you must pass the type that contains our method marked with the Action attribute, as well as the arguments.

Here is the complete listing of the application:
using System;
using NConsoler;

public class Program {
public static void Main( params string [] args) {
Consolery .Run( typeof ( Program ), args);
}

[ Action ]
public static void Method(
[ Required ] string name,
[ Optional ( true )] bool flag) {
Console .WriteLine( "name: {0}, flag: {1}" , name, flag);
}
}

It remains to run the application:
> program.exe "Max"
name: Max, flag: true

or with flag inversion:
> program.exe "Max" / -flag
name: Max, flag: false

Naturally, an error can creep into the description of Action methods. In many libraries, the source of the error is often not so obvious, so it is very important to display an adequate error message. Before launching the Action method, NConsoler checks the meta information as well as the parameters of the command line and displays a detailed error message with a possible cause. You can say this is the development of the idea “Design by contract” that allows you to work with the library without resorting to help.

Find more information, download the library and its source code can be on the site NConsoler: nconsoler.csharpus.com

')

Source: https://habr.com/ru/post/38896/


All Articles