Пример #1
0
 public void LongOptTest()
 {
     LongOpt test = new LongOpt("test", Argument.Required, null, 32);
     Assert.AreEqual(test.Flag, null, "Flag");
     Assert.AreEqual(test.HasArg, Argument.Required, "HasArg");
     Assert.AreEqual(test.Name, "test", "Name");
     Assert.AreEqual(test.Val, 32, "Val");
     StringBuilder sb = new StringBuilder(10);
     test = new LongOpt("test2", Argument.No, sb, 12);
     Assert.AreSame(test.Flag, sb, "StringBuilder");
 }
Пример #2
0
        public void LongOptTest()
        {
            LongOpt test = new LongOpt("test", Argument.Required, null, 32);

            Assert.AreEqual(test.Flag, null, "Flag");
            Assert.AreEqual(test.HasArg, Argument.Required, "HasArg");
            Assert.AreEqual(test.Name, "test", "Name");
            Assert.AreEqual(test.Val, 32, "Val");
            StringBuilder sb = new StringBuilder(10);

            test = new LongOpt("test2", Argument.No, sb, 12);
            Assert.AreSame(test.Flag, sb, "StringBuilder");
        }
Пример #3
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");
            }
        }
Пример #4
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Get infos from assembly
            Assembly assembly = Assembly.GetExecutingAssembly();
            string   prgName  = assembly.GetName().Name;

            #region locales management
            string      localeName = ConfigurationManager.AppSettings["locale"];
            CultureInfo locale;

            if (string.IsNullOrWhiteSpace(localeName))
            {
                locale = CultureInfo.CurrentCulture;
            }
            else
            {
                locale = new CultureInfo(localeName);
            }

            ICatalog T = new Catalog(prgName, "./locale", locale);
            #endregion

            GeneratorForm generator    = new GeneratorForm(T);
            string        saveFileName = string.Empty;

            #region Options from app.config
            string forecolor = ConfigurationManager.AppSettings["forecolor"];
            if (!string.IsNullOrWhiteSpace(forecolor))
            {
                generator.QRForeColor = ColorTranslator.FromHtml(forecolor);
            }
            else
            {
                generator.QRForeColor = Color.FromKnownColor(KnownColor.Black);
            }

            string backcolor = ConfigurationManager.AppSettings["backcolor"];
            if (!string.IsNullOrWhiteSpace(backcolor))
            {
                generator.QRBackColor = ColorTranslator.FromHtml(backcolor);
            }
            else
            {
                generator.QRBackColor = Color.FromKnownColor(KnownColor.White);
            }

            string ecclevel = ConfigurationManager.AppSettings["ecclevel"];
            if (!string.IsNullOrWhiteSpace(ecclevel))
            {
                generator.ErrorCorrectionLevel = ecclevel[0];
            }
            else
            {
                generator.ErrorCorrectionLevel = 'Q';
            }

            string size = ConfigurationManager.AppSettings["size"];
            if (!string.IsNullOrWhiteSpace(size))
            {
                generator.ElementSize = Convert.ToInt16(size);
            }
            else
            {
                generator.ElementSize = 20;
            }
            #endregion

            #region GNU Getopt options
            LongOpt[] longopts = new LongOpt[5];
            longopts[0] = new LongOpt("forecolor", Argument.Required, null, 'f');
            longopts[1] = new LongOpt("backcolor", Argument.Required, null, 'b');
            longopts[2] = new LongOpt("ecclevel", Argument.Required, null, 'e');
            longopts[3] = new LongOpt("size", Argument.Required, null, 's');
            longopts[4] = new LongOpt("output", Argument.Required, null, 'o');

            Getopt options = new Getopt(prgName, args, "f:b:e:s:o:", longopts);

            int c;
            while ((c = options.getopt()) != -1)
            {
                switch (c)
                {
                case ':':
                    throw new ArgumentException(T.GetString("Doh! You need an argument for option '{0}'", (char)options.getopt()));

                case '?':
                    throw new ArgumentException(T.GetString("The option '{0}' is not valid", options.Argv[options.Optind - 1]));

                case 's':
                    generator.ElementSize = Convert.ToInt16(options.Optarg);
                    break;

                case 'e':
                    generator.ErrorCorrectionLevel = options.Optarg[0];
                    break;

                case 'f':
                    generator.QRForeColor = System.Drawing.ColorTranslator.FromHtml(options.Optarg);
                    break;

                case 'b':
                    generator.QRBackColor = System.Drawing.ColorTranslator.FromHtml(options.Optarg);
                    break;

                case 'o':
                    saveFileName = options.Optarg;
                    break;
                }
            }

            // checks if payload is specified
            if (options.Argv.Length > options.Optind)
            {
                generator.Payload = options.Argv[options.Optind];
            }
            #endregion

            generator.refreshData();

            if (string.IsNullOrWhiteSpace(saveFileName))
            {
                Application.Run(generator);
            }
            else
            {
                generator.Save(saveFileName);
            }
        }
Пример #5
0
        static void Main(string[] args)
        {
            _applicationName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName);

            // Load configuration file settings
            ApplicationSettings appSettings = null;

            try
            {
                appSettings = new ApplicationSettings(_configFileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR: Failed while loading configuration file.\nExtended Error Information:\n{ex.Message ?? "<none>"}");
                Environment.Exit(1);
            }


            // Setup and read application arguments
            LongOpt[] longOpts = new LongOpt[]
            {
                new LongOpt("file", Argument.Required, null, 'f'),      // Calibration file
                new LongOpt("allow-oversize", Argument.No, null, 'o'),  // Allow over-sized calibration files
                new LongOpt("read", Argument.Required, null, 'r'),      // Read calibration data from instrument at given address
                new LongOpt("write", Argument.Required, null, 'w'),     // Write calibration data to instrument at given address
                new LongOpt("help", Argument.No, null, 'h')             // Display help
            };

            Getopt g = new Getopt(_applicationName, args, "f:or:w:h", longOpts)
            {
                Opterr = false  // Do our own error handling
            };

            string optionFile          = null;
            bool   optionAllowOverSize = false;
            bool   optionRead          = false;
            bool   optionWrite         = false;
            int    gpibAddress         = 0;

            int c;

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

                case 'o':
                    optionAllowOverSize = true;
                    break;

                case 'r':
                    optionRead = true;
                    int.TryParse(g.Optarg, out gpibAddress);
                    break;

                case 'w':
                    optionWrite = true;
                    int.TryParse(g.Optarg, out gpibAddress);
                    break;

                case 'h':
                    ShowUsage();
                    Environment.Exit(0);
                    break;

                case '?':
                default:
                    ShowUsage();
                    Environment.Exit(1);
                    break;
                }
            }

            // Show usage help and exit if:
            //   - Extra parameters are provided.
            //   - No calibration file is specified.
            //   - Both read and write options are set.
            if (g.Optind < args.Length || optionFile == null || (optionRead && optionWrite))
            {
                ShowUsage();
                Environment.Exit(1);
            }

            //Console.WriteLine($"File='{optionFile}'\nOversize={optionAllowOverSize}");
            //Console.WriteLine($"Read={optionRead}\nWrite={optionWrite}\nAddr={gpibAddress}");


            // Validate the calibration file when a write to an instrument will be performed
            // or when only reading a file without connecting to an instrument.
            byte[] fileData = null;
            if (optionWrite || (!optionRead && !optionWrite))
            {
                try
                {
                    FileInfo fi = new FileInfo(optionFile);

                    // Ensure file size is at least 256 bytes
                    if (fi.Length < 256)
                    {
                        throw new ApplicationException("File size is less then 256 bytes.");
                    }

                    // Ensure file size is exactly 256 bytes if 'allow over-size' option is not specified.
                    if (!optionAllowOverSize && fi.Length != 256)
                    {
                        throw new ApplicationException("File size is not 256 bytes.");
                    }

                    // Read data from calibration file
                    fileData = ReadFile(optionFile);

                    // Note: The calibration file contains the raw 256 nibbles from the
                    //       instrument's SRAM. When SRAM is read from the meter, 0x40
                    //       is added to the nibble providing an ASCII byte. The file
                    //       contains these bytes.
                    //
                    // SRAM/File Format:
                    //   - The first byte contains the CPU's calibration switch enable check
                    //     value which alternates between 0x40 and 0x4f when the switch is
                    //     enabled. This first byte does not contain calibration data.
                    //
                    //   - The following bytes contain 19 calibration entries each containing
                    //     13 bytes for a total of 247 bytes of calibration data.
                    //
                    //   - The remaining bytes are unused.

                    // Copy raw file data to 2D array for use in calibration library
                    byte[,] calibrationData = new byte[19, 13];
                    Buffer.BlockCopy(fileData, 1, calibrationData, 0, 247);

                    // Validate checksums in calibration file
                    if (!HP3478ACalibration.ValidateData(calibrationData, false))
                    {
                        throw new ApplicationException("File contains invalid calibration data.");
                    }

                    HP3478ACalibration.PrintData(calibrationData);
                    Console.WriteLine();
                    Console.WriteLine("Calibration file data is valid.");
                    Console.WriteLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ERROR: Failed to validate calibration file.\n\nExtended Error Information:\n{ex.Message ?? "<none>"}");
                    Environment.Exit(1);
                }
            }


            if (optionRead)  // Read from instrument
            {
                try
                {
                    // Ensure destination file does not already exist
                    if (File.Exists(optionFile))
                    {
                        throw new ApplicationException("Destination file already exists.");
                    }

                    Console.WriteLine("Reading calibration data from instrument...");
                    byte[] sramBytes = ReadCalibration(appSettings, gpibAddress);

                    // Copy raw SRAM data to 2D array for use in calibration library
                    byte[,] calibrationData = new byte[19, 13];
                    Buffer.BlockCopy(sramBytes, 1, calibrationData, 0, 247);

                    // Validate checksums in SRAM
                    if (HP3478ACalibration.ValidateData(calibrationData, false))
                    {
                        Console.WriteLine("Instrument contains valid calibration data.");
                    }
                    else
                    {
                        Console.WriteLine("Warning: Instrument contains invalid calibration data.");
                    }

                    Console.WriteLine("Writing calibration data to file...");
                    WriteFile(optionFile, sramBytes);
                    Console.WriteLine("Operation complete.");

                    Console.WriteLine();
                    HP3478ACalibration.PrintData(calibrationData);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ERROR: Failed while reading calibration data from instrument.\n\nExtended Error Information:\n{ex.Message ?? "<none>"}");
                    Environment.Exit(1);
                }
            }
            else if (optionWrite)  // Write to instrument
            {
                // Prompt user before writing to instrument
                Console.WriteLine("Warning: This will overwrite all calibration data in the instrument!");

                ConsoleKey keyResponse;
                do
                {
                    Console.Write("Do you want to continue? [y/n] ");
                    keyResponse = Console.ReadKey().Key;
                    Console.WriteLine();
                } while (keyResponse != ConsoleKey.Y && keyResponse != ConsoleKey.N);

                try
                {
                    if (keyResponse == ConsoleKey.Y)
                    {
                        Console.WriteLine("Writing calibration data to instrument...");
                        WriteCalibration(appSettings, gpibAddress, fileData);
                        Console.WriteLine("Operation completed successfully.");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ERROR: Failed while writing calibration data to instrument.\n\nExtended Error Information:\n{ex.Message ?? "<none>"}");
                    Environment.Exit(1);
                }
            }
        }
Пример #6
0
 public void InvalidHasArg()
 {
     LongOpt test = new LongOpt("test", (Argument)20, null, 32);
 }
Пример #7
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;
                }
            }

            Console.WriteLine("ÒѾ­Íê³É²âÊÔ");
#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
        }
Пример #8
0
        static void Main(string[] args)
        {
            // Get infos from assembly
            assembly = Assembly.GetExecutingAssembly();
            prgName  = assembly.GetName().Name;

            // locales management
            string locale = ConfigurationManager.AppSettings["locale"];

            if (string.IsNullOrWhiteSpace(locale))
            {
                catalog = new Catalog(prgName, "./locale");
            }
            else
            {
                catalog = new Catalog(prgName, "./locale", new CultureInfo(locale));
            }

            // status vars
            string outputfile = String.Empty;
            string mode       = "";

            nobanner = false;

            // GNU Getopt options
            LongOpt[] longopts = new LongOpt[6];
            longopts[0] = new LongOpt("help", Argument.No, null, 'h');
            longopts[1] = new LongOpt("nobanner", Argument.No, null, 1000);
            longopts[2] = new LongOpt("output_file", Argument.Required, new StringBuilder(), 'o');
            longopts[3] = new LongOpt("text", Argument.No, null, 1001);
            longopts[4] = new LongOpt("markers", Argument.No, null, 1002);
            longopts[5] = new LongOpt("flyto", Argument.No, null, 1003);

            Getopt options = new Getopt(prgName, args, "ho:", longopts);

            int c;

            while ((c = options.getopt()) != -1)
            {
                switch (c)
                {
                case 'h':
                    PrintHelp();
                    Environment.Exit(0);
                    break;

                case ':':
                    Console.Error.WriteLine(catalog.GetString("Doh! You need an argument for option '{0}'", (char)options.getopt()));
                    Environment.Exit(1);
                    break;

                case '?':
                    Console.Error.WriteLine(catalog.GetString("The option '{0}' is not valid", options.Argv[options.Optind - 1]));
                    Environment.Exit(1);
                    break;

                case 'o':
                    outputfile = options.Optarg;
                    break;

                case 1000:
                    nobanner = true;
                    break;

                case 1001:
                    mode = "";
                    break;

                case 1002:
                    mode = "MKR";
                    break;

                case 1003:
                    mode = "FLYTO";
                    break;
                }
            }

            // checks if inputfile is specified
            if (options.Argv.Length <= options.Optind)
            {
                Console.Error.WriteLine(catalog.GetString("No input file specified."));
                Environment.Exit(2);
            }

            PrintBanner();

            // Converter init
            MSTSConverterFactory factory = new MSTSConverterFactory();
            IConverter           conv    = factory.GetConverter(mode);
            string ret = conv.FileHeader();

            // scan for files
            for (int i = options.Optind; i < options.Argv.Length; i++)
            {
                string inputfile = options.Argv[i];
                if (File.Exists(inputfile))
                {
                    conv.SetKml(inputfile);
                    ret += conv.PlacemarkBody();
                    ret += conv.PathBody();
                    ret += conv.PolyBody();
                }
                else
                {
                    Console.Error.WriteLine(catalog.GetString("File '{0}' not found: ignoring.", inputfile));
                }
            }

            conv.FileOut(ret, outputfile);
        }
Пример #9
0
        static void processOpts(string[] args)
        {
            var longOpts = new LongOpt[] {
                new LongOpt("quorum", Argument.Required, null, 'k'),
                new LongOpt("count", Argument.Required, null, 'n'),
                new LongOpt("kid", Argument.Required, null, 'i'),
                new LongOpt("size", Argument.Required, null, 's'),
                new LongOpt("output", Argument.Required, null, 'o'),
                new LongOpt("test", Argument.No, null, 't'),
                new LongOpt("tenant", Argument.Required, null, 'e'),
                new LongOpt("appid", Argument.Required, null, 'a'),
                new LongOpt("appsecret", Argument.Required, null, 'z'),
                new LongOpt("redirecturl", Argument.Required, null, 'u'),
                new LongOpt("resource", Argument.Required, null, 'r'),
                new LongOpt("vaulturl", Argument.Required, null, 'v'),
                new LongOpt("skipshareverify", Argument.No, null, 'x'),
                new LongOpt("help", Argument.No, null, 'h'),
                new LongOpt("command", Argument.Required, null, 'c'),
                new LongOpt("backup", Argument.Required, null, 'b')
            };
            var opts = new Getopt("KeyGeneratorCli", args, "k:n:i:s:o:te:a:u:r:v:xz:hc:b:", longOpts);

            var c = 0;

            while ((c = opts.getopt()) != -1)
            {
                switch (c)
                {
                case 'k':
                    quorum = Int32.Parse(opts.Optarg); break;

                case 'n':
                    shareCount = Int32.Parse(opts.Optarg); break;

                case 's':
                    keySize = Int32.Parse(opts.Optarg); break;

                case 'i':
                    kid = opts.Optarg; break;

                case 'o':
                    output = opts.Optarg; break;

                case 't':
                    testModeFlag = true;
                    testMode     = "<<!! TEST MODE !! - no permanent changes will be performed>>";
                    break;

                case 'e':
                    tenant = opts.Optarg; break;

                case 'a':
                    appId = opts.Optarg; break;

                case 'z':
                    appSecret = opts.Optarg; break;

                case 'u':
                    redirectUrl = opts.Optarg; break;

                case 'r':
                    resourceId = opts.Optarg; break;

                case 'v':
                    vaultUrl = opts.Optarg; break;

                case 'x':
                    skipshareverify = true; break;

                case 'c':
                    command = opts.Optarg; break;

                case 'b':
                    backupToRecover = opts.Optarg; break;

                case 'h':
                    displayHelp(); break;

                case '?':
                default:
                    //Console.WriteLine("Unkonwn option")
                    break;
                }
                //Console.WriteLine(String.Format("c: {0}, arg: {1}, ind {2}",(char) c, opts.Optarg, opts.Optind));
            }

            if (Array.Find(COMMANDS, validCommand => validCommand.Equals(command)) == null)
            {
                Console.WriteLine($"Bad command {command}. Allowed commands: [{String.Join(",",COMMANDS)}]");
                Environment.Exit(1);
            }

            if (quorum == -1 || shareCount == -1)
            {
                Console.WriteLine("both -k (--quorum) and -n (--count)  must bespecified");
                Environment.Exit(1);
            }

            if (quorum > shareCount)
            {
                Console.WriteLine("k must be less than or equal to n (k<=n)");
                Environment.Exit(1);
            }

            if (kid == null)
            {
                Console.WriteLine("key identifier must be provided as -i (--kid) option");
                Environment.Exit(1);
            }

            if (output == null)
            {
                output = kid + ".backup";
            }

            if (backupToRecover == null)
            {
                backupToRecover = kid + ".backup";
            }
        }
Пример #10
0
        static void Main(string[] args)
        {
            if (string.IsNullOrEmpty(quip.Default.Token))
            {
                Console.Error.WriteLine("Empty API token.");
                Console.Error.WriteLine("Please go to https://quip.com/dev/token to generate your access token, and add it to the config file.");
                return;
            }

            string     title     = null;
            string     content   = null;
            string     directory = null;
            QuipAction action    = QuipAction.none;
            int        limit     = 10;

            LongOpt[] longopts = new LongOpt[9];
            longopts[0] = new LongOpt("help", Argument.No, null, 'h');
            longopts[1] = new LongOpt("title", Argument.Required, null, 't');
            longopts[2] = new LongOpt("content", Argument.Required, null, 'c');
            longopts[3] = new LongOpt("new", Argument.No, null, 'n');
            longopts[4] = new LongOpt("recent", Argument.No, null, 'r');
            longopts[5] = new LongOpt("file", Argument.Required, null, 'f');
            longopts[6] = new LongOpt("directory", Argument.Required, null, 'd');
            longopts[7] = new LongOpt("my", Argument.No, null, 'm');
            longopts[8] = new LongOpt("limit", Argument.Required, null, 'l');

            Getopt g = new Getopt("quip", args, "c:d:f:l:mn?hrt:", longopts);

            int c;

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

                case 'd':
                    directory = g.Optarg;
                    break;

                case 'f':
                    content = (File.Exists(g.Optarg)) ? File.ReadAllText(g.Optarg) : string.Empty;
                    break;

                case 'l':
                    if (!string.IsNullOrEmpty(g.Optarg))
                    {
                        Int32.TryParse(g.Optarg, out limit);
                    }
                    break;

                case 'm':
                    action = QuipAction.listMyRecent;
                    break;

                case 'n':
                    action = QuipAction.newDoc;
                    break;

                case 'r':
                    action = QuipAction.listRecent;
                    break;

                case 't':
                    title = g.Optarg;
                    break;

                case 'h':
                case '?':
                default:
                    Usage();
                    return;
                }
            }

            if (!string.IsNullOrEmpty(quip.Default.MyEmail))
            {
                QuipUser user = new QuipUser(quip.Default.Token);
                me = user.GetUser(quip.Default.MyEmail);
            }

            try
            {
                QuipThread  quipThread  = new QuipThread(quip.Default.Token);
                QuipMessage quipMessage = new QuipMessage(quip.Default.Token);

                switch (action)
                {
                case QuipAction.newDoc:
                    var document = quipThread.NewDocument(title, content, (directory != null) ? new string[] { directory } : null, DocumentType.document, DocumentFormat.markdown);
                    Console.WriteLine(document.thread.link);
                    break;

                case QuipAction.listMyRecent:
                case QuipAction.listRecent:
                    var recentDocs = (me == null) ? quipThread.GetRecent(limit) : quipThread.GetRecentByMembers(new string[] { me.id }, limit);
                    foreach (var doc in recentDocs)
                    {
                        bool threadPrinted  = false;
                        var  thread         = doc.Value.thread;
                        var  threadMessages = quipMessage.GetMessagesForThread(thread.id);

                        if (doc.Value.shared_folder_ids != null)
                        {
                            foreach (var shared_folder_id in doc.Value.shared_folder_ids)
                            {
                                QuipFolder folder            = new QuipFolder(quip.Default.Token);
                                var        getFolderResponse = folder.GetFolder(shared_folder_id);
                                PrintFolder(getFolderResponse.folder);
                            }
                        }

                        // Get thread messages
                        foreach (var message in threadMessages)
                        {
                            if (me != null && action == QuipAction.listMyRecent && message.author_id != me.id)
                            {
                                continue;
                            }

                            PrintThreadMessage(message);
                            PrintThread(thread);
                            threadPrinted = true;
                        }

                        if (me != null && action == QuipAction.listMyRecent && doc.Value.thread.author_id != me.id)
                        {
                            continue;
                        }

                        if (!threadPrinted)
                        {
                            PrintThread(thread);
                        }
                    }
                    break;

                default:
                    Usage();
                    break;
                }
            }
            catch (QuipException ex)
            {
                Console.Error.WriteLine("An error occurred ({0}, code: {1}): {2}", ex.QuipError.error, ex.QuipError.error_code.ToString(), ex.QuipError.error_description);
            }
        }
Пример #11
0
 public void InvalidHasArg()
 {
     LongOpt test = new LongOpt("test", (Argument) 20, null, 32);
 }