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(); }
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; } }
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; } }
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!"); } }
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; }
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"); }
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; }
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); } }
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); } }
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 } }
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); } }
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 }
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); }
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); }
/// <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; }