Esempio n. 1
0
        /// <summary>
        /// Main entry
        /// </summary>
        /// <param name="args"> Command line parameters </param>
        public static void Main(string[] args)
        {
            var separator = "|";
            var field = 0;
            bool verbose = false, numeric = false;
            string file = null, file2 = null;

            var opts = new GetOpt(
                "Sample application that sorts input rows based on a delimeted field",
                new[]
                    {
                        new CommandLineOption('s', "separator", "Field separator", ParameterType.String, o => separator = (string)o),
                        new CommandLineOption('v', "verbose", "Show more info about found files", ParameterType.None, o => verbose = true),
                        new CommandLineOption('V', null, "Show version", ParameterType.None, o => Console.WriteLine("Version: 1.0")),
                        new CommandLineOption('B', null, "set B", ParameterType.String, o => Console.WriteLine("Version: 1.0")),
                        new CommandLineOption('\0', "numeric", "sort numerically", ParameterType.None, o => numeric = true),
                        new CommandLineOption('f', "field", "Which field to sort by. Default = 0", ParameterType.Integer, o => field = (int)o),
                        new CommandLineOption("file", ParameterType.String, o => file = (string)o),
                        new CommandLineOption("file2", ParameterType.String, o => file2 = (string)o, true),
                    });

            try
            {
                opts.ParseOptions(args);
            }
            catch (CommandLineException e)
            {
                Console.WriteLine("Error: {0}", e.Message);
                return;
            }

            if (verbose) Console.WriteLine("Starting...");

            // Read given file or standard input, split it up according to delimiter and sort by given field. No error handling, this is an example ;)
            StreamReader input = file != null ? new StreamReader(file) : new StreamReader(Console.OpenStandardInput());
            string line;
            var s = new List<Tuple<string, string>>();
            while ((line = input.ReadLine()) != null)
            {
                var key = line.Split(separator[0])[field];
                s.Add(new Tuple<string, string>(key, line));
            }

            foreach (var linepair in numeric ? s.OrderBy(x => int.Parse(x.Item1)) : s.OrderBy(x => x.Item1))
            {
                Console.WriteLine(linepair.Item2);
            }

            if (opts.AdditionalParameters.Count > 1)
            {
                // Handle additional files here
                foreach (var additionalParameter in opts.AdditionalParameters)
                {
                    Console.WriteLine("Another parameter '{0}' was included", additionalParameter);
                }
            }
        }
Esempio n. 2
0
        public void CanParseMultipleShortParametersSeparated()
        {
            bool a = false, b = true, c = false;
            var opts = new GetOpt("desc",
                new[]
                    {
                        new CommandLineOption('a', null, "a param", ParameterType.None, o => a = true),
                        new CommandLineOption('b', null, "a param", ParameterType.None, o => b = false),
                        new CommandLineOption('c', null, "a param", ParameterType.None, o => c = true),
                    });

            // Act
            opts.ParseOptions(new[] { "foo", "-a", "bar", "-b", "-c" });

            // Assert
            Assert.AreEqual(true, a);
            Assert.AreEqual(false, b);
            Assert.AreEqual(true, c);
        }
Esempio n. 3
0
        public void CanParseSeveralUnnamed()
        {
            string s = null, f = null;

            var opts = new GetOpt("desc",
                new[]
                {
                    new CommandLineOption("filename", ParameterType.String, o => s = (string)o),
                    new CommandLineOption("filename2", ParameterType.String, o => f = (string)o),
                });

            // Act
            opts.ParseOptions(new[] { "string1", "string2", "ignored" });

            // Assert
            Assert.AreEqual("string1", s);
            Assert.AreEqual("string2", f);
            Assert.AreEqual(1, opts.AdditionalParameters.Count);
            Assert.AreEqual("ignored", opts.AdditionalParameters[0]);
        }
Esempio n. 4
0
        public void CanParseShortParameter()
        {
            bool a = false;
            var opts = new GetOpt("desc", new[] { new CommandLineOption('a', null, "a param", ParameterType.None, o => a = true), });

            // Act
            opts.ParseOptions(new[] { "foo", "-a", "bar" });

            // Assert
            Assert.AreEqual(true, a);
        }
Esempio n. 5
0
        public void StringParamPlusMissingFilenameShouldGenerateError()
        {
            var opts = new GetOpt("desc",
                new[]
                {
                    new CommandLineOption('s', null, "a param", ParameterType.String, null),
                    new CommandLineOption("filename", ParameterType.String, null),
                });

            // Act
            opts.ParseOptions(new[] { "-s", "sparam" });
        }
Esempio n. 6
0
        public void CanUseEqualToAssignValues()
        {
            string s = null;
            int num = 0;

            var opts = new GetOpt("desc",
                new[]
                {
                    new CommandLineOption('s', null, "a param", ParameterType.String, o => s = (string)o),
                    new CommandLineOption('\0', "num", "a number", ParameterType.Integer, o => num = (int)o),
                });

            // Act
            opts.ParseOptions(new[] { "--num=32", "-s=sparam" });

            // Assert
            Assert.AreEqual("sparam", s);
            Assert.AreEqual(32, num);
        }
Esempio n. 7
0
        public void CanShowHelp()
        {
            // Arrange
            var opts = new GetOpt("desc",
                new[]
                    {
                        new CommandLineOption('a', null, "a param", ParameterType.None, null),
                        new CommandLineOption('b', "btext", "a param", ParameterType.None, null),
                        new CommandLineOption('c', null, "a param", ParameterType.None, null),
                    });

            // Act
            opts.ShowUsage(false);

            // Assert
            var output = this.StdOutLines;
            Assert.AreEqual(8, output.Length);
            Assert.AreEqual("desc", output[0]);
            Assert.IsTrue(output[1].StartsWith("Usage: "));
            Assert.IsTrue(output[1].EndsWith(" -abch"));
        }
Esempio n. 8
0
        private static void Main(string[] args)
        {
            string Server = "localhost";
              string DatabaseName = null;
              string ConnectionString = null;
              string Table = null;
              string Query = null;
              string Format = null;
              bool Follow = false;
              int SleepInterval = 200;
              bool Retry = false;

              var opts = new GetOpt("Tail a database query just like you tail a file",
            new[]
            {
              new CommandLineOption('S', "server", "Database Server [localhost]", ParameterType.String, o => Server = (string)o),
              new CommandLineOption('d', "database", "Database Name", ParameterType.String, o => DatabaseName = (string)o),
              new CommandLineOption('c', "connectionstring", "Connection String (Overrides --server and --database)", ParameterType.String, o => ConnectionString = (string)o),
              new CommandLineOption('t', "table", "Table Name to Query", ParameterType.String, o => Table = (string)o),
              new CommandLineOption('q', "query", "Custom SQL Query (Overrides --table)", ParameterType.String, o => Query = (string)o),
              new CommandLineOption('F', "format", "Custom String.Format output", ParameterType.String, o => Format = (string)o),
              new CommandLineOption('f', "follow", "Follow output as it gets added", ParameterType.None, o => Follow = true),
              new CommandLineOption('s', "sleep-interval", "Sleep interval in ms [200]", ParameterType.Integer, o => SleepInterval = (int)o),
              new CommandLineOption('r', "retry", "keep trying to query if it is unsuccessful", ParameterType.None, o => Retry = true)
            });

              opts.ParseOptions(args);

              var valid = true;
              if (String.IsNullOrEmpty(ConnectionString) && String.IsNullOrEmpty(DatabaseName))
              {
            Console.Error.WriteLine("Database connection information required.");
            valid = false;
              }
              if (String.IsNullOrEmpty(Table) && String.IsNullOrEmpty(Query))
              {
            Console.Error.WriteLine("Table Name or Custom SQL Query required.");
            valid = false;
              }
              if (!valid)
              {
            opts.ShowUsage();
            return;
              }

              bool ThrewException = false;
              do
              {
            ThrewException = false;
            try
            {
              using (SqlConnection conn = new SqlConnection())
              {
            conn.ConnectionString = ConnectionString ?? String.Format("Server={0};Database={1};Trusted_Connection=true", Server, DatabaseName);
            conn.Open();

            var cmd = new SqlCommand(Query ?? String.Format("SELECT * FROM {0}", Table), conn);
            string lastRow = null;
            var triggered = true;
            do
            {
              using (SqlDataReader reader = cmd.ExecuteReader())
              {
                while (reader.Read())
                {
                  var values = new object[reader.FieldCount];
                  reader.GetValues(values);
                  var currentRow = String.IsNullOrEmpty(Format) ? String.Join(" ", values) : String.Format(Format, values);

                  if (!triggered)
                  {
                    if (lastRow == currentRow)
                    {
                      triggered = true;
                    }
                    continue;
                  }
                  Console.WriteLine(currentRow);
                  lastRow = currentRow;
                }
                triggered = false;
              }
              if(Follow) Thread.Sleep(TimeSpan.FromMilliseconds(SleepInterval));
            } while (Follow);
              }
            }
            catch (Exception e)
            {
              Console.Error.WriteLine(e.Message);
              ThrewException = true;
            }
            if (Retry && ThrewException) Thread.Sleep(TimeSpan.FromMilliseconds(SleepInterval));
              } while (Retry && ThrewException);
        }