This is a C# port of a Java port of GNU getopt, a class for parsing command line arguments passed to programs. It it based on the C getopt() functions in glibc 2.0.6 and should parse options in a 100% compatible manner. If it does not, that is a bug. The programmer's interface is also very compatible.
To use Getopt, create a Getopt object with a args array passed to the main method, then call the getopt method in a loop. It will return an int that contains the value of the option character parsed from the command line. When there are no more options to be parsed, it returns -1.

A command line option can be defined to take an argument. If an option has an argument, the value of that argument is stored in an instance variable called optarg, which can be accessed using the Optarg property. If an option that requires an argument is found, but there is no argument present, then an error message is printed. Normally getopt returns a '?' in this situation, but that can be changed as described below.

If an invalid option is encountered, an error message is printed to the standard error and getopt returns a '?'. The value of the invalid option encountered is stored in the instance variable optopt which can be retrieved using the Optopt property. To suppress the printing of error messages for this or any other error, set the value of the opterr instance variable to false using the Opterr property.

Between calls to getopt, the instance variable optind is used to keep track of where the object is in the parsing process. After all options have been returned, optind is the index in argv of the first non-option argument. This variable can be accessed with the Optind property.

Note that this object expects command line options to be passed in the traditional Unix manner. That is, proceeded by a '-' character. Multiple options can follow the '-'. For example "-abc" is equivalent to "-a -b -c". If an option takes a required argument, the value of the argument can immediately follow the option character or be present in the next argv element. For example, "-cfoo" and "-c foo" both represent an option character of 'c' with an argument of "foo" assuming c takes a required argument. If an option takes an argument that is not required, then any argument must immediately follow the option character in the same argv element. For example, if c takes a non-required argument, then "-cfoo" represents option character 'c' with an argument of "foo" while "-c foo" represents the option character 'c' with no argument, and a first non-option argv element of "foo".

The user can stop getopt from scanning any further into a command line by using the special argument "--" by itself. For example: "-a -- -d" would return an option character of 'a', then return -1. The "--" is discarded and "-d" is pointed to by optind as the first non-option argv element.

Here is a basic example of using Getopt: Getopt g = new Getopt("testprog", args, "ab:c::d"); int c; string arg; while ((c = g.getopt()) != -1) { switch(c) { case 'a': case 'd': Console.WriteLine("You picked " + (char)c ); break; case 'b': case 'c': arg = g.Optarg; Console.WriteLine("You picked " + (char)c + " with an argument of " + ((arg != null) ? arg : "null") ); break; case '?': break; // getopt() already printed an error default: Console.WriteLine("getopt() returned " + c); break; } } In this example, a new Getopt object is created with three params. The first param is the program name. This is for printing error messages in the form "program: error message". In the C version, this value is taken from argv[0], but in .NET the program name is not passed in that element, thus the need for this parameter. The second param is the argument list that was passed to the main() method. The third param is the list of valid options. Each character represents a valid option. If the character is followed by a single colon, then that option has a required argument. If the character is followed by two colons, then that option has an argument that is not required.

Note in this example that the value returned from getopt is cast to a char prior to printing. This is required in order to make the value display correctly as a character instead of an integer.

If the first character in the option string is a colon, for example ":abc::d", then getopt will return a ':' instead of a '?' when it encounters an option with a missing required argument. This allows the caller to distinguish between invalid options and valid options that are simply incomplete.

In the traditional Unix getopt(), -1 is returned when the first non-option charcter is encountered. In GNU getopt(), the default behavior is to allow options to appear anywhere on the command line. The getopt method permutes the argument to make it appear to the caller that all options were at the beginning of the command line, and all non-options were at the end. For example, calling getopt with command line argv of "-a foo bar -d" returns options 'a' and 'd', then sets optind to point to "foo". The program would read the last two argv elements as "foo" and "bar", just as if the user had typed "-a -d foo bar".

The user can force getopt to stop scanning the command line with the special argument "--" by itself. Any elements occuring before the "--" are scanned and permuted as normal. Any elements after the "--" are returned as is as non-option argv elements. For example, "foo -a -- bar -d" would return option 'a' then -1. optind would point to "foo", "bar" and "-d" as the non-option argv elements. The "--" is discarded by getopt.

There are two ways this default behavior can be modified. The first is to specify traditional Unix getopt() behavior (which is also POSIX behavior) in which scanning stops when the first non-option argument encountered. (Thus "-a foo bar -d" would return 'a' as an option and have "foo", "bar", and "-d" as non-option elements). The second is to allow options anywhere, but to return all elements in the order they occur on the command line. When a non-option element is ecountered, an integer 1 is returned and the value of the non-option element is stored in optarg is if it were the argument to that option. For example, "-a foo -d", returns first 'a', then 1 (with optarg set to "foo") then 'd' then -1. When this "return in order" functionality is enabled, the only way to stop getopt from scanning all command line elements is to use the special "--" string by itself as described above. An example is "-a foo -b -- bar", which would return 'a', then integer 1 with optarg set to "foo", then 'b', then -1. optind would then point to "bar" as the first non-option argv element. The "--" is discarded.

The POSIX/traditional behavior is enabled by either setting the application setting "Gnu.PosixlyCorrect" or by putting a '+' sign as the first character of the option string. The difference between the two methods is that setting the "Gnu.PosixlyCorrect" application setting also forces certain error messages to be displayed in POSIX format. To enable the "return in order" functionality, put a '-' as the first character of the option string. Note that after determining the proper behavior, Getopt strips this leading '+' or '-', meaning that a ':' placed as the second character after one of those two will still cause getopt to return a ':' instead of a '?' if a required option argument is missing.

In addition to traditional single character options, GNU Getopt also supports long options. These are preceeded by a "--" sequence and can be as long as desired. Long options provide a more user-friendly way of entering command line options. For example, in addition to a "-h" for help, a program could support also "--help".

Like short options, long options can also take a required or non-required argument. Required arguments can either be specified by placing an equals sign after the option name, then the argument, or by putting the argument in the next argv element. For example: "--outputdir=foo" and "--outputdir foo" both represent an option of "outputdir" with an argument of "foo", assuming that outputdir takes a required argument. If a long option takes a non-required argument, then the equals sign form must be used to specify the argument. In this case, "--outputdir=foo" would represent option outputdir with an argument of foo while "--outputdir foo" would represent the option outputdir with no argument and a first non-option argv element of "foo".

Long options can also be specified using a special POSIX argument format (one that I highly discourage). This form of entry is enabled by placing a "W;" (yes, 'W' then a semi-colon) in the valid option string. This causes getopt to treat the name following the "-W" as the name of the long option. For example, "-W outputdir=foo" would be equivalent to "--outputdir=foo". The name can immediately follow the "-W" like so: "-Woutputdir=foo". Option arguments are handled identically to normal long options. If a string follows the "-W" that does not represent a valid long option, then getopt returns 'W' and the caller must decide what to do. Otherwise getopt returns a long option value as described below.

While long options offer convenience, they can also be tedious to type in full. So it is permissible to abbreviate the option name to as few characters as required to uniquely identify it. If the name can represent multiple long options, then an error message is printed and getopt returns a '?'.

If an invalid option is specified or a required option argument is missing, getopt prints an error and returns a '?' or ':' exactly as for short options. Note that when an invalid long option is encountered, the optopt variable is set to integer 0 and so cannot be used to identify the incorrect option the user entered.

Long options are defined by LongOpt objects. These objects are created with a contructor that takes four params: a string representing the object name, a integer specifying what arguments the option takes (the value is one of the Argument enumeration: Argument.No, Argument.Required, or Argument.Optional), a System.Text.StringBuilder flag object (described below), and an integer value (described below).

To enable long option parsing, create an array of LongOpt's representing the legal options and pass it to the Getopt() constructor. WARNING: If all elements of the array are not populated with LongOpt objects, the getopt method will throw a NullReferenceException.

When getopt is called and a long option is encountered, one of two things can be returned. If the flag field in the LongOpt object representing the long option is non-null, then the integer value field is stored there and an integer 0 is returned to the caller. The val field can then be retrieved from the flag field. Note that since the flag field is a System.Text.StringBuilder, the appropriate string to integer converions must be performed in order to get the actual int value stored there. If the flag field in the LongOpt object is null, then the value field of the LongOpt is returned. This can be the character of a short option. This allows an app to have both a long and short option sequence (say, "-h" and "--help") that do the exact same thing.

With long options, there is an alternative method of determining which option was selected. The property Longind will return the index in the long option array (NOT argv) of the long option found. So if multiple long options are configured to return the same value, the application can use Longind to distinguish between them.

Here is an expanded Getopt example using long options and various techniques described above: int c; string arg; LongOpt[] longopts = new LongOpt[3]; StringBuffer sb = new StringBuffer(); longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'); longopts[1] = new LongOpt("outputdir", LongOpt.REQUIRED_ARGUMENT, sb, 'o'); longopts[2] = new LongOpt("maximum", LongOpt.OPTIONAL_ARGUMENT, null, 2); Getopt g = new Getopt("testprog", argv, "-:bc::d:hW;", longopts); g.Opterr = false; // We'll do our own error handling while ((c = g.getopt()) != -1) switch (c) { case 0: arg = g.getOptarg(); Console.WriteLine("Got long option with value '" + (char)(new Integer(sb.toString())).intValue() + "' with argument " + ((arg != null) ? arg : "null")); break; case 1: Console.WriteLine("I see you have return in order set and that " + "a non-option argv element was just found " + "with the value '" + g.Optarg + "'"); break; case 2: arg = g.getOptarg(); Console.WriteLine("I know this, but pretend I didn't"); Console.WriteLine("We picked option " + longopts[g.Longind].getName() + " with value " + ((arg != null) ? arg : "null")); break; case 'b': Console.WriteLine("You picked plain old option " + (char)c); break; case 'c': case 'd': arg = g.getOptarg(); Console.WriteLine("You picked option '" + (char)c + "' with argument " + ((arg != null) ? arg : "null")); break; case 'h': Console.WriteLine("I see you asked for help"); break; case 'W': Console.WriteLine("Hmmm. You tried a -W with an incorrect long " + "option name"); break; case ':': Console.WriteLine("Doh! You need an argument for option " + (char)g.getOptopt()); break; case '?': Console.WriteLine("The option '" + (char)g.getOptopt() + "' is not valid"); break; default: Console.WriteLine("getopt() returned " + c); break; } for (int i = g.getOptind(); i < argv.length ; i++) Console.WriteLine("Non option argv element: " + argv[i] );

The set of single-character options is often in one-to-one correspondence with the set of long options. The digest method is helpful in such cases: LongOpt [] longOpts = new LongOpt [7] { new LongOpt("verbose", Argument.No, null, 'v'), new LongOpt("version", Argument.No, null, 'r'), new LongOpt("input", Argument.Required, null, 'i'), new LongOpt("output", Argument.Required, null, 'o'), new LongOpt("help", Argument.No, null, 'h')}; Getopt getopt = new Getopt("filter", args, Getopt.digest(longOpts), longOpts);

There is an alternative form of the constructor used for long options above. This takes a trailing boolean flag. If set to false, Getopt performs identically to the example, but if the boolean flag is true then long options are allowed to start with a single '-' instead of "--". If the first character of the option is a valid short option character, then the option is treated as if it were the short option. Otherwise it behaves as if the option is a long option. Note that the name given to this option - longOnly - is very counter-intuitive. It does not cause only long options to be parsed but instead enables the behavior described above.

Note that the functionality and variable names used are driven from the C lib version as this object is a port of the C code, not a new implementation. This should aid in porting existing C/C++ code, as well as helping programmers familiar with the glibc version to adapt to the C#.NET version.

示例#1
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "f:r:s:tv") { Opterr = false };

            string funcname = null;
            string resourcesPath = null;
            string filesPath = null;
            bool topOnly = false;
            bool verbose = false;

            int option;
            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                    case 'f': funcname = getopt.Optarg; break;
                    case 'r': resourcesPath = getopt.Optarg; break;
                    case 's': filesPath = getopt.Optarg; break;
                    case 't': topOnly = true; break;
                    case 'v': verbose = true; break;

                    default: PrintUsage(); return;
                }
            }

            if (resourcesPath == null || filesPath == null)
            {
                PrintUsage();
                return;
            }

            var replacer = new Replacer(filesPath, resourcesPath, funcname, topOnly, verbose);
            replacer.Run();
        }
示例#2
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "i:o:") { Opterr = false };

            string input = null;
            string output = null;

            int option;
            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                    case 'i': input = getopt.Optarg; break;
                    case 'o': output = getopt.Optarg; break;

                    default: PrintUsage(); return;
                }
            }

            if (input == null || output == null)
            {
                PrintUsage();
                return;
            }

            try
            {
                if (!File.Exists(input))
                {
                    Console.WriteLine("File {0} not found", input);
                    return;
                }

                Dictionary<string, string> entries;
                var parser = new PoParser();
                using (var reader = new StreamReader(input))
                {
                    entries = parser.ParseIntoDictionary(reader);
                }

                using (var writer = new ResourceWriter(output))
                {
                    foreach (var kv in entries)
                    {
                        try { writer.AddResource(kv.Key, kv.Value); }
                        catch (Exception e) { Console.WriteLine("Error adding item {0}: {1}", kv.Key, e.Message); }
                    }
                    writer.Generate();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error during execution: {0}", ex.Message);
                return;
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "p:e:c:s:f:") { Opterr = false };

            string source = null;
            string pattern = null;
            string extension = null;
            string charset = null;
            string fromCharset = null;

            int option;
            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                    case 'e': extension = getopt.Optarg; break;
                    case 's': source = getopt.Optarg; break;
                    case 'c': charset = getopt.Optarg; break;
                    case 'p': pattern = getopt.Optarg; break;
                    case 'f': fromCharset = getopt.Optarg; break;

                    default: PrintUsage(); return;
                }
            }

            if (extension == null || source == null || charset == null)
            {
                PrintUsage(); 
                return;
            }

            try
            {
                foreach (var file in Directory.GetFiles(source, pattern, SearchOption.AllDirectories))
                {
                    var output = String.Format("{0}.{1}", file, extension);
                    using (var reader = new StreamReader(file, Encoding.GetEncoding(fromCharset)))
                    {
                        using (var writer = new StreamWriter(output, false, Encoding.GetEncoding(charset)))
                        {
                            writer.Write(reader.ReadToEnd());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failure processing files: {0}", ex.Message);
                return;
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            var g = new Getopt("Sorting", args, "a:f:o:");

            string algorithm = "", shuffledListsFileName = "", outputDirectory = ".";

            int c;
            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                    case 'a':
                        algorithm = g.Optarg;
                        break;
                    case 'f':
                        shuffledListsFileName = g.Optarg;
                        break;
                    case 'o':
                        outputDirectory = g.Optarg;
                        break;
                }
            }

            if (algorithm.Length > 0 && shuffledListsFileName.Length > 0 && outputDirectory.Length > 0)
            {
                var listsToSort = ParseShuffledListsFile(shuffledListsFileName);
                int[,] sortedLists = new int[listsToSort.NumberOfLists, listsToSort.SizeOfLists];

                switch (algorithm)
                {
                    case "built_in":
                        BuiltInSorting(listsToSort.Lists, ref sortedLists);
                        break;
                    default:
                        Console.WriteLine("Please set a valid sorting algorithm!");
                        break;
                }

                var output
                    = new StreamWriter(GetOutputFileName(algorithm, outputDirectory, listsToSort)
                    );
                PrintListOfLists(sortedLists, output);
                output.Close();
            }
            else
            {
                Console.WriteLine("Please set the algorith, shuffled lists file name and output directory!");
            }
        }
示例#5
0
        public static void ParseArguments(string[] args,
            out string input, out string output, out int[] pids, out string pidfile)
        {
            output = null;
            pids = null;
            pidfile = null;

            Getopt g = new Getopt(Utils.GetProgramName(), args, ":o:p:P:");
            g.Opterr = false;
            int c;

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                    case 'o':
                        output = g.Optarg;
                        break;

                    case 'p':
                        string[] strs = g.Optarg.Split(',');
                        pids = new int[strs.Length];

                        for (int i = 0; i < strs.Length; i++)
                            pids[i] = int.Parse(strs[i]);

                        break;

                    case 'P':
                        pidfile = g.Optarg;
                        break;

                    case ':':
                        throw new ArgumentException("Uncomplete argument: -" + (char)g.Optopt);
                    case '?':
                        throw new ArgumentException("Invalid argument: -" + (char)g.Optopt);
                    default:
                        break;
                }
            }

            if (args.Length > g.Optind)
                input = args[g.Optind];
            else
                input = null;
        }
示例#6
0
        public static void Main(string[] args)
        {
            int c;
            MainClass main = new MainClass();

            LongOpt[] longopts = new LongOpt[] {
                new LongOpt("help", Argument.No, null, 'h'),
                new LongOpt("verbose", Argument.No, null, 'v'),
                new LongOpt("conf", Argument.Required, null, 'c'),
                new LongOpt("tag", Argument.No, null, 2),
                new LongOpt("parse", Argument.No, null, 3),
                new LongOpt("knows", Argument.No, null, 4),
                new LongOpt("spell", Argument.No, null, 'z')
            };
            Getopt g = new Getopt("DataTemple", args, "hvszc:I:P:O:T:i:p:t:", longopts);

            bool acted = false;
            List<PatternTemplateSource> dicta = new List<PatternTemplateSource>();

            string input = null;
            string output = null;
            string template = null;
            while ((c = g.getopt()) != -1)
                switch (c) {
                case 1: {
                    Console.WriteLine("I see you have return in order set and that " +
                        "a non-option argv element was just found " +
                        "with the value '" + g.Optarg + "'");
                    break;
                }
                case 2: {
                    acted = true;
                    if (main.tagger == null) {
                        Console.WriteLine("Use the -c option before --tag or --parse");
                        continue;
                    }
                    List<KeyValuePair<string, string>> tokens = main.tagger.TagString(input);
                    foreach (KeyValuePair<string, string> token in tokens)
                        Console.Write(token.Key + "/" + token.Value + " ");
                    Console.WriteLine("");
                    break;
                }
                case 3: {
                    acted = true;
                    if (main.parser == null) {
                        Console.WriteLine("Use the -c option before --tag or --parse");
                        continue;
                    }
                    Console.WriteLine(main.parser.Parse(input));
                    break;
                }
                case 4: {
                    DictumMaker maker = new DictumMaker(main.basectx, "testing");
                    dicta.Add(maker.MakeDictum("%sentence %noun %is %adj", "@know %noun @HasProperty %adj @SubjectTense %is"));
                    dicta.Add(maker.MakeDictum("%sentence %event %attime", "@know %event @AtTime %attime"));
                    dicta.Add(maker.MakeDictum("%sentence %event %inall", "@know %event @InLocation %inall"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %inall", "@know %noun @InLocation %inall"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %is a %noun", "@know %noun1 @IsA %noun2 @SubjectTense %is"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %will %verb1 * to %verb2 *", "@know %verbx1 @Subject %noun @SubjectTense %will %verb1 @ActiveObjects *1 @know %verbx2 @Subject %noun @SubjectTense %verb2 @ActiveObjects *2 @know %verbx2 @Condition %verbx1"));
                    break;
                }
                case 'v': {
                    main.verbose++;
                    break;
                }
                case 'h': {
                    Console.WriteLine("The documentation is currently at \n" + DOCS_URL);
                    break;
                }
                case 's': {
                    main.serialmode = true;
                    break;
                }
                case 'z': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -z");
                        continue;
                    }

                    SpellingBeeWordComparer wordComparer = new SpellingBeeWordComparer(main.plugenv.GetConfigDirectory("datadirectory"));
                    main.basectx.Map["$Compare"] = wordComparer;
                    main.tryToRescueMatch = new CorrectSpellingsRescueMatch(main.tryToRescueMatch, wordComparer, main.parser, 100);
                    break;
                }
                case 'c': {
                    main.Initialize(g.Optarg);
                    break;
                }
                case 'I': {
                    input = g.Optarg;
                    break;
                }
                case 'i': {
                    StreamReader file = new StreamReader(g.Optarg);
                    input = file.ReadToEnd();
                    break;
                }
                case 'P': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -P");
                        continue;
                    }
                    Context context = Interpreter.ParseCommands(main.basectx, g.Optarg);
                    IContinuation cont = new Evaluator(100.0, ArgumentMode.ManyArguments, main, new NopCallable(), true);
                    cont.Continue(context, new NopCallable());

                    main.RunToEnd();
                    break;
                }
                case 'p': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -p");
                        continue;
                    }
                    foreach (string line in File.ReadAllLines(g.Optarg)) {
                        if (line.Trim().Length == 0 || line.Trim().StartsWith("#"))
                            continue;
                        Context context = Interpreter.ParseCommands(main.basectx, line);
                        IContinuation cont = new Evaluator(100.0, ArgumentMode.ManyArguments, main, new NopCallable(), true);
                        cont.Continue(context, new NopCallable());

                        main.RunToEnd();
                    }
                    break;
                }
                case 'T': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -T");
                        continue;
                    }
                    template = g.Optarg;
                    if (template != null && output != null) {
                        DictumMaker maker = new DictumMaker(main.basectx, "testing");
                        dicta.Add(maker.MakeDictum(template, output));

                        template = output = null;
                    }
                    break;
                }
                case 'O': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -O");
                        continue;
                    }

                    output = g.Optarg;
                    if (template != null && output != null) {
                        DictumMaker maker = new DictumMaker(main.basectx, "testing");
                        dicta.Add(maker.MakeDictum(template, output));

                        template = output = null;
                    }
                    break;
                }
                case 't': {
                    if (!main.initialized) {
                        Console.WriteLine("Use the -c option before -t");
                        continue;
                    }

                    bool nextTemplate = true;
                    foreach (string line in File.ReadAllLines(g.Optarg)) {
                        string trimline = line.Trim();
                        if (trimline.Length == 0 || trimline.StartsWith("#"))
                            continue;

                        if (nextTemplate) {
                            template = trimline;
                            nextTemplate = false;
                        } else {
                            output = trimline;
                            DictumMaker maker = new DictumMaker(main.basectx, "testing");
                            dicta.Add(maker.MakeDictum(template, output));
                            nextTemplate = true;
                        }
                    }

                    template = output = null;
                    break;
                }
            }

            if (dicta.Count != 0)
                main.DoMatching(dicta, input);
            else if (!acted)
                Console.WriteLine("Nothing to do.  Add -tag, -parse, or -t or -T and -O");
        }
示例#7
0
        private static ProgramContext ParseArgs(string[] args) {
            int c;
            Getopt g = new Getopt("ipnetwork", args, "inmcbfltud:Dhs:wWxC:o:S:");
            ProgramContext ac = new ProgramContext();

			while ((c = g.getopt()) != -1) {
                string optArg = g.Optarg;
                Program.Args[c].Run(ac, optArg);
            }

            List<string> ipnetworks = new List<string>();
            for (int i = g.Optind; i < args.Length; i++) {
                if (!string.IsNullOrEmpty(args[i])) {
                    ipnetworks.Add(args[i]);
                }
            }
            ac.NetworksString = ipnetworks.ToArray();
            Program.ParseIPNetworks(ac);

            if (ac.Networks.Length == 0) {
                Console.WriteLine("Provide at least one ipnetwork");
                ac.Action = ActionEnum.Usage;
            }

            if (ac.Action == ActionEnum.Supernet
                && ipnetworks.Count < 2) {
                Console.WriteLine("Supernet action required at least two ipnetworks");
                ac.Action = ActionEnum.Usage;
            }

            if (ac.Action == ActionEnum.WideSupernet
                && ipnetworks.Count < 2) {
                Console.WriteLine("WideSupernet action required at least two ipnetworks");
                ac.Action = ActionEnum.Usage;
            }

            if (Program.PrintNoValue(ac)) {
                Program.PrintAll(ac);
            }

            if (g.Optind == 0) {
                Program.PrintAll(ac);
            }

            return ac;
        }
示例#8
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "s:i:c:nadp") { Opterr = false };

            string input = null;
            string culture = null;

            bool dontDeleteSet = false;
            bool insertAll = false;
            bool skipValidation = false;
            bool onlyPrepare = false;

            string connString = ConfigurationManager.ConnectionStrings["Gettext"].ConnectionString;
            string insertSP = ConfigurationManager.AppSettings["SP.Insert"];
            string deleteSP = ConfigurationManager.AppSettings["SP.Delete"];
            string getSP = ConfigurationManager.AppSettings["SP.Get"];
            string tableName = ConfigurationManager.AppSettings["Table.Name"];
            string tableCulture = ConfigurationManager.AppSettings["Table.Fields.Culture"];
            string tableKey = ConfigurationManager.AppSettings["Table.Fields.Key"];
            string tableValue = ConfigurationManager.AppSettings["Table.Fields.Value"];

            int option;
            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                    case 'i': input = getopt.Optarg; break;
                    case 'c': culture = getopt.Optarg; break;
                    case 'n': dontDeleteSet = true; break;
                    case 's': connString = getopt.Optarg; break;
                    case 'a': insertAll = true; break;
                    case 'd': skipValidation = true; break;
                    case 'p': onlyPrepare = true; break;
                    default: PrintUsage(); return;
                }
            }

            if (input == null && !onlyPrepare)
            {
                PrintUsage();
                return;
            }

            if (connString == null || getSP == null || insertSP == null || deleteSP == null || tableName == null || tableKey == null || tableCulture == null || tableValue == null)
            {
                Console.Out.WriteLine("Ensure that connection string, table name, table fields, insert and delete stored procedures are set in app config.");
                Console.Out.WriteLine();
                Console.Out.WriteLine("Expected connection strings are:");
                Console.Out.WriteLine(" Gettext");
                Console.Out.WriteLine();
                Console.Out.WriteLine("Expected app settings are:");
                Console.Out.WriteLine(" SP.Get");
                Console.Out.WriteLine(" SP.Insert");
                Console.Out.WriteLine(" SP.Delete");
                Console.Out.WriteLine(" Table.Name");
                Console.Out.WriteLine(" Table.Fields.Key");
                Console.Out.WriteLine(" Table.Fields.Value");
                Console.Out.WriteLine(" Table.Fields.Culture");
                return;
            }

            try
            {
                using (var db = new DatabaseInterface(connString)
                    {
                        GetSP = getSP,
                        DeleteSP = deleteSP,
                        InsertSP = insertSP,
                        CultureField = tableCulture,
                        KeyField = tableKey,
                        ValueField = tableValue,
                        TableName = tableName
                    })
                {
                    db.Init();

                    // Check if table and sps exist
                    if (!skipValidation || onlyPrepare)
                    {
                        db.Prepare();
                    }

                    // If only prepare is set, do not use po file, just make sure everything is ready to use it later
                    if (onlyPrepare)
                    {
                        Console.Out.WriteLine("Table and stored procedures ready.");
                        db.Commit();
                        return;
                    }

                    // Delete previous resource set for the specified culture
                    if (!dontDeleteSet)
                    {
                        db.DeleteResourceSet(culture);
                    }

                    // Dump the file into the database
                    var requestor = new DatabaseParserRequestor(culture, db, insertAll);
                    new PoParser().Parse(new StreamReader(input), requestor);

                    db.Commit();
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Exception in program: {0}\n{1}", ex.Message, ex.StackTrace);
            }

        }
示例#9
0
        static void Main(string[] args)
        {
            /* flags */
            bool foundOpt   = false;
            bool has_R_flag = false; /* restore flag */
            bool has_B_flag = false; /* backup flag */
            bool has_S_flag = false; /* source flag */
            bool has_D_flag = false; /* destination flag */
            bool has_Q_flag = false; /* quit flag */
            bool has_I_flag = false; /* inetpub flag */
            bool has_P_flag = false; /* inetpub flag */

            /* variables to hold options */
            string sqlServerName = null;
            string destDir       = null;
            string sourceDir     = null;
            string selectedOpt   = null;
            string inetpubDir    = null;
            string rhevpath      = null;

            /* others */
            int c;

            main m = new main();

            if (args.Length < 9)
            {
                m.usage();
                Environment.Exit(-1);
            }

            Getopt g = new Getopt("rhevUP", args, "d:i:rbs:u:n:p:h:q");

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                    case 'd':
                        /* destination flag*/
                        foundOpt = true;
                        has_D_flag = true;

                        /* setting value */
                        destDir = g.Optarg;
                        break;

                    case 'r':
                        /* recover flag */
                        foundOpt = true;
                        has_R_flag = true;

                        /* setting value */
                        selectedOpt = "restore";
                        break;

                    case 'b':
                        /* backup flag */
                        foundOpt = true;
                        has_B_flag = true;

                        /* setting value */
                        selectedOpt = "backup";
                        break;

                    case 's':
                        /* source */
                        foundOpt = true;
                        has_S_flag = true;

                        /* setting value */
                        sourceDir = g.Optarg;
                        break;

                    case 'n':
                        /* SQL Server Name */
                        foundOpt = true;

                        /* setting */
                        sqlServerName = g.Optarg;
                        break;

                    case 'q':
                        has_Q_flag = true;
                        foundOpt   = true;
                        break;

                    case 'h':
                        m.usage();
                        break;

                    case 'i':
                        has_I_flag = true;
                        inetpubDir = g.Optarg;
                        foundOpt   = true;
                        break;

                    case 'p':
                        has_P_flag = true;
                        rhevpath = g.Optarg;
                        foundOpt = true;
                        break;

                    default:
                        Console.WriteLine("getopt() returned " + c);
                        m.usage();
                        break;
                }
            }

            /* In case customer doesn't provide '-' argument, print usage */
            if (foundOpt != true)
            {
                m.usage();
            }

            if (has_P_flag == false)
            {
                Console.WriteLine("Cannot proceed, you must specify -p (path RHEVM files) option, aborting..");
                Console.WriteLine("Ex.: -p c:\\Program Files\\RedHat\\RHEVManager");
                Environment.Exit(-1);
            }

            if (has_I_flag == false)
            {
                Console.WriteLine("Cannot proceed, you must specify -i (wwwroot) option, aborting..");
                Console.WriteLine("Ex.: -i c:\\inetpub\\wwwroot");
                Environment.Exit(-1);
            }

            /* quit and restore flags are not compatible */
            if ((has_R_flag == true) && (has_Q_flag == true))
            {
                Console.WriteLine("Cannot use flags -r and -q together, aborting..");
                Environment.Exit(-1);
            }

            /* backup and restore are not compatible flags */
            if ((has_B_flag == true) && (has_R_flag == true))
            {
                Console.WriteLine("Cannot use flags -b and -r together, aborting..");
                Environment.Exit(-1);
            }

            /* destionation and source are not compatible flags */
            if ((has_D_flag == true) && (has_S_flag == true))
            {
                Console.WriteLine("Cannot use flags -d and -s together, aborting..");
                Environment.Exit(-1);
            }

            Run r = new Run();

            if (selectedOpt == "backup")
            {
                if (destDir == null)
                {
                    Console.WriteLine("using backup mode, -d must be specified");
                    Console.WriteLine("aborting...");
                    Environment.Exit(-1);
                }
                r.backupRHEV(sqlServerName, destDir, has_Q_flag, inetpubDir, rhevpath);
            }
            else if (selectedOpt == "restore")
            {
                if (sourceDir == null)
                {
                    Console.WriteLine("using restore mode, -s must be specified");
                    Console.WriteLine("aborting...");
                    Environment.Exit(-1);
                }

                r.restoreRHEV(sqlServerName, sourceDir, inetpubDir, rhevpath);
            }
            else
            {
                Console.WriteLine("You must select restore or backup option");
                Environment.Exit(0);
            }
        }
示例#10
0
        static void Main(string[] args)
        {
            // Get CLI arguments
            bool verbose = false, silent = false, trusted = false;
            String server = null, username = null, password = null, login = null;
            var pids = new List<int>();
            int port = 0, seconds = 5;

            var getopt = new Getopt(AppName, args, "hvqP:Eu:p:s:L:S:t:");
            getopt.Opterr = false; // Suppress warning messages to stdout
            int c;
            while ((c = getopt.getopt()) != -1)
            {
                switch (c)
                {
                    case 'h': // Help
                        Usage();
                        break;
                    case 'v': // Verbose
                        if (silent)
                            Usage("invalid option: -v with -q");
                        verbose = true;
                        break;
                    case 'q': // Quiet
                        if (verbose)
                            Usage("invalid option: -q with -v");
                        silent = true;
                        break;
                    case 'S': // Server
                        server = getopt.Optarg;
                        break;
                    case 'P': // Port
                        port = int.Parse(getopt.Optarg);
                        if (port < 1)
                            Usage(String.Format(String.Format("invalid port for -P -- {0}", getopt.Optarg)));
                        break;
                    case 'E': // Trusted
                        if (username != null)
                            Usage("invalid option: -E with -u");
                        if (password != null)
                            Usage("invalid option: -E with -p");
                        trusted = true;
                        break;
                    case 'u': // Username
                        if (trusted)
                            Usage("invalid option: -u with -E");
                        username = getopt.Optarg;
                        break;
                    case 'p': // Password
                        if (trusted)
                            Usage("invalid option: -p with -E");
                        password = getopt.Optarg;
                        break;
                    case 's': // SPID(s) to monitor
                        if (login != null)
                            Usage("invalid option: -x with -L");
                        {
                            var pidList = getopt.Optarg;
                            if (String.IsNullOrEmpty(pidList))
                                Usage("pid or pids are missing");
                            foreach (String pidStr in pidList.Split(','))
                            {
                                var pid = int.Parse(pidStr);
                                if (pid < 1)
                                    Usage(String.Format("invalid spid(s) for -s -- {0}", pidStr));
                                pids.Add(pid);
                            }
                        }
                        break;
                    case 'L': // Login to monitor
                        if (pids.Count > 0)
                            Usage("invalid option: -L with -x");
                        login = getopt.Optarg;
                        break;
                    case 't': // Seconds to wait
                        seconds = int.Parse(getopt.Optarg);
                        if (seconds < 1)
                            Usage(String.Format("invalid timeout for -t -- {0}", getopt.Optarg));
                        break;
                    case '?':
                        Usage(String.Format("invalid argument -{0}", (char)getopt.Optopt));
                        break;
                }
            }

            // Default to trusted authentication
            if (!trusted && username == null)
                trusted = true;

            // Argument presence validation
            if ( (server == null) ||
                 (login == null && pids.Count == 0) )
                Usage("required argument(s) missing");

            if (!silent)
                Banner();

            // Start monitoring
            using (var conn = new SqlConnection(
                new SqlWaitFor.Util.SqlConnectionStringBuilder()
                    .Instance(server)
                    .Port(port)
                    .Username(username)
                    .Password(password)
                    .Application(AppName)
                    .Build()))
            {
            #if !DEBUG
                try
                {
            #endif
                    conn.Open();
                    var mySPID = DbUtils.GetSPID(conn);
                    if (!silent)
                        Console.WriteLine("SPID {0} is monitoring SQL Server processes (^C cancels)...", mySPID);

                    while (true)
                    {
                        var procs = SqlProcess.GetProcessList(conn, login);
                        var relevantProcs = pids.Count > 0 ?
                            procs.Where(p =>
                                p.SPID != mySPID &&
                                pids.Contains(p.SPID)
                            ) :
                            procs.Where(p => p.SPID != mySPID);
                        var liveProcs = relevantProcs.Where(p => !p.IsSleeping).ToList();
                        if (liveProcs.Count == 0)
                        {
                            if (!silent && verbose)
                            {
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine("*** [FINISH] No active queries found!");
                                Console.ResetColor();
            #if DEBUG
                                Console.WriteLine();
                                Console.WriteLine("Press any key to exit...");
                                Console.ReadKey();
            #endif
                            }
                            break;
                        }

                        if (!silent && verbose)
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("*** [WAIT] {0}/{1} queries active at {2}", liveProcs.Count, relevantProcs.Count(), DateTime.Now);
                            Console.ResetColor();
                            foreach (var liveProc in liveProcs)
                            {
                                Console.ForegroundColor = ConsoleColor.White;
                                Console.WriteLine("SPID {0} -> State: {1}, CPU: {2}, I/O: {3}, Memory: {4}, Database: {5}",
                                    liveProc.SPID,
                                    liveProc.Status.ToLower(),
                                    liveProc.CPU,
                                    liveProc.PhysicalIO,
                                    liveProc.Memory,
                                    liveProc.Database);
                                Console.ForegroundColor = ConsoleColor.Gray;
                                Console.WriteLine(liveProc.Command);
                            }
                            Console.ResetColor();
                            Console.WriteLine();
                        }

                        Thread.Sleep(seconds * 1000);
                    }
            #if !DEBUG
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Error.WriteLine("*** [ERROR] {0}", ex.Message);
                    Console.ResetColor();
                    Environment.Exit(1);
                }
            #endif
            }
        }
示例#11
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "t:k:e:p:f:c:d:") { Opterr = false };

            string tag = null;
            string keyword = null;
            string extension = null;
            string path = null;
            string function = null;
            string charset = null;
            string fromCharset = null;

            int option;
            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                    case 't': tag = getopt.Optarg; break;
                    case 'k': keyword = getopt.Optarg; break;
                    case 'e': extension = getopt.Optarg; break;
                    case 'p': path = getopt.Optarg; break;
                    case 'f': function = getopt.Optarg; break;
                    case 'c': charset = getopt.Optarg; break;
                    case 'd': fromCharset = getopt.Optarg; break;

                    default: PrintUsage(); return;
                }
            }

            if (keyword == null || extension == null || path == null)
            {
                PrintUsage(); return;
            }

            if (tag == null && function == null)
            {
                PrintUsage(); return;
            }

            try
            {
                IAspStringsParser tagParser = tag == null ? null : new AspStringsParser(tag);
                IAspStringsParser csParser = function == null ? null : new CSharpAspStringsParser(function);

                IAspStringsParser parser;
                if (tagParser != null && csParser != null)
                {
                    parser = new CompositeAspStringsParser(tagParser, csParser);
                }
                else
                {
                    parser = tagParser ?? csParser;
                }

                var extractor = new AspStringsExtractor(keyword, extension, charset, fromCharset, parser);
                extractor.Extract(path);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failure processing files: {0}", ex.Message);
                return;
            }
        }
        static void Main(string[] args)
        {
            int c;
            LongOpt[] longopts = new LongOpt[4];
            string param0placeholder = "@Name";
            string param1placeholder = "@BinArray";
            string dsn = System.Environment.GetEnvironmentVariable("DSN");
            string sql = System.Environment.GetEnvironmentVariable("SQL");
            string file = null;
            string name = null;
            byte[] fileArray;

            longopts[0] = new LongOpt("help", Argument.No, null, '?');
            longopts[1] = new LongOpt("dsn", Argument.Required, null, 'd');
            longopts[1] = new LongOpt("sql", Argument.Required, null, 's');
            longopts[2] = new LongOpt("file", Argument.Required, null, 'f');
            longopts[3] = new LongOpt("name", Argument.Required, null, 'n');

            Getopt g = new Getopt(System.AppDomain.CurrentDomain.FriendlyName, args, "?d:s:f:n:", longopts);

            while ((c = g.getopt()) != -1) {
                switch (c) {
                    case '?':
                        Help();
                        return;
                    case 'd':
                        dsn = g.Optarg;
                        break;
                    case 's':
                        sql = g.Optarg;
                        break;
                    case 'f':
                        file = g.Optarg;
                        break;
                    case 'n':
                        name = g.Optarg;
                        break;
                }
            }

            if ((dsn == null) || (sql == null) || (file == null)) {
                Help();
                return;
            }
            if (name == null) {
                name = Path.GetFileNameWithoutExtension(file);
            }

            try {
                fileArray = GetFileArray(file);
            } catch {
                Help();
                return;
            }

            sql = String.Format(sql, param0placeholder, param1placeholder);

            try {
                Save(dsn, sql, fileArray, name, param0placeholder, param1placeholder);
            } catch {
                Help();
                Debug(dsn, sql, file, fileArray);
            }
        }
示例#13
0
        static void Main(string[] args)
        {
            #if true	// Getopt sample
            Getopt g = new Getopt("testprog", args, "ab:c::d");

            int c;
            string arg;
            while ((c = g.getopt()) != -1)
            {
                switch(c)
                {
                    case 'a':
                    case 'd':
                        Console.WriteLine("You picked " + (char)c );
                        break;

                    case 'b':
                    case 'c':
                        arg = g.Optarg;
                        Console.WriteLine("You picked " + (char)c +
                            " with an argument of " +
                            ((arg != null) ? arg : "null") );
                        break;

                    case '?':
                        break; // getopt() already printed an error

                    default:
                        Console.WriteLine("getopt() returned " + c);
                        break;
                }
            }

            #else		// Getopt/LongOpt docu sample
            int c;
            String arg;
            LongOpt[] longopts = new LongOpt[3];

            StringBuilder sb = new StringBuilder();
            longopts[0] = new LongOpt("help", Argument.No, null, 'h');
            longopts[1] = new LongOpt("outputdir", Argument.Required, sb, 'o');
            longopts[2] = new LongOpt("maximum", Argument.Optional, null, 2);

            Getopt g = new Getopt("testprog", args, "-:bc::d:hW;", longopts);
            g.Opterr = false; // We'll do our own error handling

            while ((c = g.getopt()) != -1)
                switch (c)
                {
                    case 0:
                        arg = g.Optarg;
                        Console.WriteLine("Got long option with value '" +
                            (char)int.Parse(sb.ToString())
                            + "' with argument " +
                            ((arg != null) ? arg : "null"));
                        break;

                    case 1:
                        Console.WriteLine("I see you have return in order set and that " +
                            "a non-option argv element was just found " +
                            "with the value '" + g.Optarg + "'");
                        break;

                    case 2:
                        arg = g.Optarg;
                        Console.WriteLine("I know this, but pretend I didn't");
                        Console.WriteLine("We picked option " +
                            longopts[g.Longind].Name +
                            " with value " +
                            ((arg != null) ? arg : "null"));
                        break;

                    case 'b':
                        Console.WriteLine("You picked plain old option " + (char)c);
                        break;

                    case 'c':
                    case 'd':
                        arg = g.Optarg;
                        Console.WriteLine("You picked option '" + (char)c +
                            "' with argument " +
                            ((arg != null) ? arg : "null"));
                        break;

                    case 'h':
                        Console.WriteLine("I see you asked for help");
                        break;

                    case 'W':
                        Console.WriteLine("Hmmm. You tried a -W with an incorrect long " +
                            "option name");
                        break;

                    case ':':
                        Console.WriteLine("Doh! You need an argument for option " +
                            (char)g.Optopt);
                        break;

                    case '?':
                        Console.WriteLine("The option '" + (char)g.Optopt +
                            "' is not valid");
                        break;

                    default:
                        Console.WriteLine("getopt() returned " + c);
                        break;
                }

            for (int i = g.Optind; i < args.Length ; i++)
                Console.WriteLine("Non option argv element: " + args[i] + "\n");
            #endif
        }
示例#14
0
        public static void ParseArguments(string[] args, out string filename,
            out decimal readCost, out decimal writeCost, out uint[] npageses,
            out AlgorithmSpec[] algorithms, out RunModeInfo mode)
        {
            // Init
            readCost = 80;
            writeCost = 200;
            npageses = new uint[] { 1024 };

            bool verify = false, tracelog = false;
            bool fileop = false, fileopWithoutCheckSize = false;
            string opfilename = null, tracelogfile = null;
            Regex regexAlgo = new Regex(@"(\w+)(?:\(([^)]+)\))?");
            List<AlgorithmSpec> algos = new List<AlgorithmSpec>();

            // Parse
            Getopt g = new Getopt(Utils.ProgramName, args, ":a:cf:F:hp:r:t:w:");
            g.Opterr = false;
            int c;

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                    case 'a':
                        foreach (Match m in regexAlgo.Matches(g.Optarg))
                        {
                            string name = m.Groups[1].Value;
                            string[] arg = m.Groups[2].Value.Split(',');

                            if (m.Groups[2].Success)
                                algos.Add(new AlgorithmSpec(name, arg));
                            else
                                algos.Add(new AlgorithmSpec(name));
                        }
                        break;

                    case 'c':
                        verify = true;
                        break;

                    case 'f':
                        fileop = true;
                        fileopWithoutCheckSize = true;
                        opfilename = g.Optarg;
                        break;

                    case 'F':
                        fileop = true;
                        fileopWithoutCheckSize = false;
                        opfilename = g.Optarg;
                        break;

                    case 'h':
                        throw new CmdLineHelpException();

                    case 'p':
                        string[] strs = g.Optarg.Split(',');
                        npageses = new uint[strs.Length];

                        for (int i = 0; i < strs.Length; i++)
                        {
                            if (!uint.TryParse(strs[i], out npageses[i]) || npageses[i] == 0)
                                throw new InvalidCmdLineArgumentException(
                                    "Positive integer(s) are expected after -p");
                        }

                        break;

                    case 'r':
                        if (!decimal.TryParse(g.Optarg, out readCost) || readCost <= 0)
                            throw new InvalidCmdLineArgumentException(
                                "A positive integer is expected after -r");
                        break;

                    case 't':
                        tracelog = true;
                        tracelogfile = g.Optarg;
                        break;

                    case 'w':
                        if (!decimal.TryParse(g.Optarg, out writeCost) || writeCost <= 0)
                            throw new InvalidCmdLineArgumentException(
                                "A positive integer is expected after -w");
                        break;

                    case ':':
                        throw new InvalidCmdLineArgumentException(
                            "Uncomplete argument: -" + (char)g.Optopt);
                    case '?':
                        throw new InvalidCmdLineArgumentException(
                            "Invalid argument: -" + (char)g.Optopt);
                    default:
                        break;
                }
            }

            // Filename
            if (args.Length > g.Optind)
                filename = args[g.Optind];
            else
                filename = null;

            // Algorithm
            if (algos.Count == 0)
                algorithms = new AlgorithmSpec[] { new AlgorithmSpec("Trival") };
            else
                algorithms = algos.ToArray();

            // Run Mode
            if (fileop && (algorithms.Length > 1 || npageses.Length > 1))
                throw new InvalidCmdLineArgumentException(
                    "In -f mode, only ONE algorithm and only ONE npages is allowed.");

            if (verify && fileop)
                throw new InvalidCmdLineArgumentException(
                    "Cannot specify both -c and -f/-F");
            else if (verify && tracelog)
                throw new InvalidCmdLineArgumentException(
                    "Cannot specify both -c and -s");
            else if (fileop && tracelog)
                throw new InvalidCmdLineArgumentException(
                    "Cannot specify both -s and -f/-F");
            else if (verify)
                mode = new RunModeInfo(RunMode.Verify, null);
            else if (fileop)
                mode = new RunModeInfo(RunMode.File, new object[] {
                    opfilename, fileopWithoutCheckSize });
            else if (tracelog)
                mode = new RunModeInfo(RunMode.Trace, tracelogfile);
            else
                mode = new RunModeInfo(RunMode.Normal, null);
        }
示例#15
0
        static int Main(string[] args)
        {
            RegistrySettings rs = new RegistrySettings();
            Getopt go = new Getopt("profit", args, "hlc:br:x:i:a",
                new LongOpt[]
                {
                    new LongOpt("help", Argument.No, null, 'h'),
                    new LongOpt("list", Argument.No, null, 'l'),
                    new LongOpt("coin", Argument.Required, null, 'c'),
                    new LongOpt("bitcoin", Argument.No, null, 'b'),
                    new LongOpt("hashrate", Argument.Required, null, 'r'),
                    new LongOpt("exchange", Argument.Required, null, 'x'),
                    new LongOpt("interval", Argument.Required, null, 'i'),
                    new LongOpt("all", Argument.No, null, 'a')
                });
            int opt=-1;
            bool bLookUpAll = false;
            bool bIncomeInBTC = false;
            string szSelectedCoin = "";
            foreach (string name in rs.GetCoinTypes())
                if (name.ToLower()=="bitcoin")
                    szSelectedCoin = name;
            decimal hashrate = 0;
            string exchange = "";
            long interval = 86400;

            while ((opt=go.getopt())!=-1)
                switch (opt)
                {
                    case 'h':
                        Help();
                        return 0;
                    case 'l':
                        foreach (string name in rs.GetCoinTypes())
                            Console.WriteLine(name);
                        return 0;
                    case 'c':
                        szSelectedCoin = go.Optarg;
                        break;
                    case 'b':
                        bIncomeInBTC = true;
                        break;
                    case 'r':
                        hashrate = Convert.ToDecimal(go.Optarg);
                        break;
                    case 'x':
                        exchange = go.Optarg;
                        break;
                    case 'i':
                        interval = Convert.ToInt64(go.Optarg);
                        break;
                    case 'a':
                        bLookUpAll = true;
                        break;
                    default:
                        Help();
                        return -1;
                }
            if (bLookUpAll)
            {
                foreach (string name in rs.GetCoinTypes())
                {
                    Console.Write(name + ": ");
                    Lookup(name, hashrate, bIncomeInBTC, interval, exchange, rs);
                }
                return 0;
            }
            if (szSelectedCoin == "")
            {
                Console.WriteLine("No coin selected");
                return -1;
            }
            return Lookup(szSelectedCoin, hashrate, bIncomeInBTC, interval, exchange, rs);
        }
示例#16
0
        /// <summary>
        /// Surely get passed arguments using Getopt
        /// </summary>
        /// <param name="args">command line args</param>
        /// <returns>Key - argument name, value - option, if passed</returns>
        private Dictionary<string, string> GetArgumentsValues(string[] args)
        {
            var dic = new Dictionary<string, string>();

            Getopt g = new Getopt(ProgramName, args, AllowedArguments);
            g.Opterr = false;
            int c;
            while ((c = g.getopt()) != -1)
                switch (c)
                {
                    case 0:
                    case 1:
                    case 2:
                    case '?':
                        //Long options and errors go away
                        continue;
                    default:
                        dic.Add(GetArgumentName((char)c), g.Optarg);
                        break;
                }

            return dic;
        }