Beispiel #1
0
        public void ParseFloats()
        {
            ValueArgument <float> argument = new ValueArgument <float>("float", "Description")
            {
                Category      = "Category",
                IsOptional    = true,
                AllowMultiple = true,
            };

            Assert.AreEqual("float", argument.Name);
            Assert.AreEqual("Description", argument.Description);
            Assert.AreEqual("Category", argument.Category);
            Assert.IsFalse(string.IsNullOrEmpty(argument.GetSyntax()));
            Assert.IsFalse(string.IsNullOrEmpty(argument.GetHelp()));
            Assert.IsTrue(argument.AllowMultiple);

            int i = 1;

            string[] args   = { "other", "123.4", "-567.8", };
            var      result = (ArgumentResult <float>)argument.Parse(args, ref i);

            Assert.AreEqual(3, i);
            Assert.AreEqual(2, result.Values.Count);
            Assert.AreEqual(123.4f, result.Values[0]);
            Assert.AreEqual(-567.8f, result.Values[1]);
        }
Beispiel #2
0
        private static CommandLineParser.CommandLineParser CreateParser()
        {
            CommandLineParser.CommandLineParser parser = new CommandLineParser.CommandLineParser();
            ValueArgument<SqlConnectionStringBuilder> connectionStringArgument = new ValueArgument<SqlConnectionStringBuilder>('c', "connectionString", "ConnectionString of the documented database")
            {
                Optional = false,
                ConvertValueHandler = (stringValue) =>
                {
                    SqlConnectionStringBuilder connectionStringBuilder;
                    try
                    {
                        connectionStringBuilder = new SqlConnectionStringBuilder(stringValue);
                    }
                    catch
                    {
                        throw new InvalidConversionException("invalid connection string", "connectionString");
                    }
                    if (String.IsNullOrEmpty(connectionStringBuilder.InitialCatalog))
                    {
                        throw new InvalidConversionException("no InitialCatalog was specified", "connectionString");
                    }

                    return connectionStringBuilder;
                }
            };
            FileArgument inputFileArgument = new FileArgument('i', "input", "original edmx file") { FileMustExist = true, Optional = false };
            FileArgument outputFileArgument = new FileArgument('o', "output", "output edmx file - Default : original edmx file") { FileMustExist = false, Optional = true };

            parser.Arguments.Add(connectionStringArgument);
            parser.Arguments.Add(inputFileArgument);
            parser.Arguments.Add(outputFileArgument);

            parser.IgnoreCase = true;
            return parser;
        }
Beispiel #3
0
        private CommandLineParser.CommandLineParser InitIgnoreCase()
        {
            var commandLineParser = new CommandLineParser.CommandLineParser();

            commandLineParser.IgnoreCase = true;
            commandLineParser.ShowUsageOnEmptyCommandline = true;

            SwitchArgument showArgument = new SwitchArgument('s', "show", "Set whether show or not", true);

            SwitchArgument hideArgument = new SwitchArgument('h', "hide", "Set whether hid or not", false);

            ValueArgument <string> level = new ValueArgument <string>('l', "level", "Set the level");

            ValueArgument <decimal> version = new ValueArgument <decimal>('v', "version", "Set desired version");

            ValueArgument <Point> point = new ValueArgument <Point>('p', "point", "specify the point");

            BoundedValueArgument <int> optimization = new BoundedValueArgument <int>('o', "optimization", 0, 3);

            EnumeratedValueArgument <string> color = new EnumeratedValueArgument <string>('c', "color", new[] { "red", "green", "blue" });

            FileArgument inputFile = new FileArgument('i', "input", "Input file");

            inputFile.FileMustExist = false;
            FileArgument outputFile = new FileArgument('x', "output", "Output file");

            outputFile.FileMustExist = false;

            DirectoryArgument inputDirectory = new DirectoryArgument('d', "directory", "Input directory");

            inputDirectory.DirectoryMustExist = false;

            point.ConvertValueHandler = delegate(string stringValue)
            {
                if (stringValue.StartsWith("[") && stringValue.EndsWith("]"))
                {
                    string[] parts =
                        stringValue.Substring(1, stringValue.Length - 2).Split(';', ',');
                    Point p = new Point();
                    p.x = int.Parse(parts[0]);
                    p.y = int.Parse(parts[1]);
                    return(p);
                }

                throw new CommandLineArgumentException("Bad point format", "point");
            };

            commandLineParser.Arguments.Add(showArgument);
            commandLineParser.Arguments.Add(hideArgument);
            commandLineParser.Arguments.Add(level);
            commandLineParser.Arguments.Add(version);
            commandLineParser.Arguments.Add(point);
            commandLineParser.Arguments.Add(optimization);
            commandLineParser.Arguments.Add(color);
            commandLineParser.Arguments.Add(inputFile);
            commandLineParser.Arguments.Add(outputFile);
            commandLineParser.Arguments.Add(inputDirectory);

            return(commandLineParser);
        }
Beispiel #4
0
        public static void Main(string [] args)
        {
            var parser    = new CommandLineParser.CommandLineParser();
            var algorithm = new EnumeratedValueArgument <string> (
                'a',
                "algorithm",
                "available algorithms for computing hash, default to SHA1",
                new [] { Md2Hash.ALGORITHM_NAME,
                         Md5Hash.ALGORITHM_NAME,
                         Sha1Hash.ALGORITHM_NAME,
                         Sha256Hash.ALGORITHM_NAME,
                         Sha384Hash.ALGORITHM_NAME,
                         Sha512Hash.ALGORITHM_NAME });

            algorithm.DefaultValue = Sha1Hash.ALGORITHM_NAME;
            var source = new ValueArgument <string> (
                's',
                "source",
                "source to compute hash");

            source.Optional = false;
            var salt = new ValueArgument <string> (
                't',
                "salt",
                "salt for computing hash");
            var iterations = new ValueArgument <int> (
                'i',
                "iterations",
                "iterations when compute hash");

            iterations.DefaultValue = 1;
            parser.Arguments.AddRange(
                new Argument [] { algorithm, source, salt, iterations });

            parser.ParseCommandLine(args);

            if (!source.Parsed || string.IsNullOrEmpty(source.Value))
            {
                parser.ShowUsage();
                return;
            }

            SimpleHash hash = null;

            if (algorithm.Parsed)
            {
                hash = new SimpleHash(algorithm.Value, source.Value, salt.Value, iterations.Value);
            }
            if (hash == null)
            {
                hash = new Sha1Hash(source.Value, salt.Value, iterations.Value);
            }

            Console.WriteLine("algorithms  :" + hash.AlgorithmName);
            Console.WriteLine("source      :" + source.Value);
            Console.WriteLine("salt        :" + salt.Value);
            Console.WriteLine("iterations  :" + iterations.Value);
            Console.WriteLine("hash(hex)   :" + hash.ToHex());
            Console.WriteLine("hash(base64):" + hash.ToBase64());
        }
Beispiel #5
0
        public void SerializationTest()
        {
            var argument = new ValueArgument<string>("arg", "");
            const string message = "message";
            const string innerMessage = "Inner exception";
            var innerException = new Exception(innerMessage);
            var exception = new DuplicateArgumentException(argument, message, innerException);

            using (var memoryStream = new MemoryStream())
            {
                // Serialize exception.
                var formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, exception);

                memoryStream.Position = 0;

                // Deserialize exception.
                formatter = new BinaryFormatter();
                var deserializedException = (DuplicateArgumentException)formatter.Deserialize(memoryStream);

                Assert.AreEqual(argument.Name, deserializedException.Argument);
                Assert.AreEqual(message, deserializedException.Message);
                Assert.AreEqual(innerMessage, deserializedException.InnerException.Message);
            }
        }
Beispiel #6
0
        public static CommandLineParser.CommandLineParser Get()
        {
            try
            {
                var parser = new CommandLineParser.CommandLineParser();

                ValueArgument <string> project = new ValueArgument <string>(
                    'p', "project", "Specify the project path file");
                project.Optional = false;

                ValueArgument <string> github = new ValueArgument <string>(
                    'g', "github", "Specify the username/repository of github");
                github.Optional = false;

                SwitchArgument force = new SwitchArgument('f', "force", "Force recreate file", false);

                parser.Arguments.Add(project);
                parser.Arguments.Add(force);
                parser.Arguments.Add(github);

                return(parser);
            }
            catch (CommandLineArgumentException ex)
            {
                if (args.Count() > 0)
                {
                    Console.WriteLine(ex.Message);
                }
                parser.ShowUsage();
            }
        }
        public void ParseInteger1()
        {
            var valueArgument = new ValueArgument <int>("i", "")
            {
                AllowMultiple = true
            };
            var argument = new SwitchValueArgument <int>("Value", valueArgument, "Description", null, new[] { 'v' })
            {
                Category   = "Category",
                IsOptional = true,
            };

            Assert.AreEqual("Value", argument.Name);
            Assert.AreEqual('v', argument.ShortAliases[0]);
            Assert.AreEqual("Description", argument.Description);
            Assert.AreEqual("Category", argument.Category);
            Assert.IsFalse(string.IsNullOrEmpty(argument.GetSyntax()));
            Assert.IsFalse(string.IsNullOrEmpty(argument.GetHelp()));

            int i = 0;

            string[] args   = { "--value:1", "23", "4", };
            var      result = (ArgumentResult <int>)argument.Parse(args, ref i);

            Assert.AreEqual(3, i);
            Assert.IsNotNull(result.Values);
            Assert.AreEqual(3, result.Values.Count);
            Assert.AreEqual(1, result.Values[0]);
            Assert.AreEqual(23, result.Values[1]);
            Assert.AreEqual(4, result.Values[2]);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            CommandLineParser.CommandLineParser parser = new CommandLineParser.CommandLineParser();
            ValueArgument <string> path = new ValueArgument <string>('p', "path", "Folder with the contents");

            parser.Arguments.Add(path);
            try
            {
                parser.ParseCommandLine(args);
                var extractedFolder = string.Empty;
                if (path.Parsed)
                {
                    extractedFolder = path.Value;
                }
                if (String.IsNullOrWhiteSpace(extractedFolder))
                {
                    parser.ShowUsage();
                }
                var worker = new Worker("correspondences.json");
                worker.Work(extractedFolder);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void ConstructorTest3()
        {
            var argument  = new ValueArgument <string>("arg", "");
            var exception = new DuplicateArgumentException(argument);

            Assert.AreEqual(argument.Name, exception.Argument);
        }
Beispiel #10
0
        /// Add a command-line argument for an ISetting
        protected void AddSettingAsArg(ISetting setting)
        {
            if (!setting.IsVersioned || setting.IsCurrent(HFM.HFM.Version))
            {
                if (setting is DynamicSettingAttribute)
                {
                    // Instruct parser to include unrecognised args, since these
                    // may correspond to dynamic setting values
                    _cmdLine.Definition.IncludeUnrecognisedKeywordArgs = true;
                    _cmdLine.Definition.IncludeUnrecognisedFlagArgs    = true;
                }
                else
                {
                    var key = setting.Name.Capitalize();
                    if (_cmdLine.Definition[key] == null)
                    {
                        _log.DebugFormat("Adding command-line arg {0}", key);

                        // Add a keyword argument for this setting
                        ValueArgument arg = setting.HasUda("PositionalArg") ?
                                            (ValueArgument)_cmdLine.AddPositionalArgument(key, setting.Description) :
                                            (ValueArgument)_cmdLine.AddKeywordArgument(key, setting.Description);
                        arg.Alias = setting.Alias;
                        // TODO: Argument should only be optional if prompting is valid (i.e. not headless)
                        arg.IsRequired = false;
                        // arg.IsRequired = !setting.HasDefaultValue;
                        arg.IsSensitive = setting.IsSensitive;
                        if (setting.HasDefaultValue && setting.DefaultValue != null)
                        {
                            arg.DefaultValue = setting.DefaultValue.ToString();
                        }
                    }
                }
            }
        }
Beispiel #11
0
        public void ParseInteger1()
        {
            var valueArgument = new ValueArgument<int>("i", "") { AllowMultiple = true };
            var argument = new SwitchValueArgument<int>("Value", valueArgument, "Description", null, new[] { 'v' })
            {
                Category = "Category",
                IsOptional = true,
            };

            Assert.AreEqual("Value", argument.Name);
            Assert.AreEqual('v', argument.ShortAliases[0]);
            Assert.AreEqual("Description", argument.Description);
            Assert.AreEqual("Category", argument.Category);
            Assert.IsFalse(string.IsNullOrEmpty(argument.GetSyntax()));
            Assert.IsFalse(string.IsNullOrEmpty(argument.GetHelp()));

            int i = 0;
            string[] args = { "--value:1", "23", "4", };
            var result = (ArgumentResult<int>)argument.Parse(args, ref i);
            Assert.AreEqual(3, i);
            Assert.IsNotNull(result.Values);
            Assert.AreEqual(3, result.Values.Count);
            Assert.AreEqual(1, result.Values[0]);
            Assert.AreEqual(23, result.Values[1]);
            Assert.AreEqual(4, result.Values[2]);
        }
        public void SerializationTest()
        {
            var          argument       = new ValueArgument <string>("arg", "");
            const string message        = "message";
            const string innerMessage   = "Inner exception";
            var          innerException = new Exception(innerMessage);
            var          exception      = new DuplicateArgumentException(argument, message, innerException);

            using (var memoryStream = new MemoryStream())
            {
                // Serialize exception.
                var formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, exception);

                memoryStream.Position = 0;

                // Deserialize exception.
                formatter = new BinaryFormatter();
                var deserializedException = (DuplicateArgumentException)formatter.Deserialize(memoryStream);

                Assert.AreEqual(argument.Name, deserializedException.Argument);
                Assert.AreEqual(message, deserializedException.Message);
                Assert.AreEqual(innerMessage, deserializedException.InnerException.Message);
            }
        }
        /// <summary>
        /// Entry point of the CLI.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        private static void Main(string[] args)
        {
            var cliParser         = new CommandLineParser.CommandLineParser();
            var directoryArgument = new DirectoryArgument('d', "directory", "The directory containing the files to match.")
            {
                DirectoryMustExist = true, Optional = true, DefaultValue = new DirectoryInfo(Environment.CurrentDirectory)
            };
            var fileExtensionArgument = new ValueArgument <string>('x', "extension", "The file extension (without dot) to match as a regular expression pattern, e.g. \"^(pdf|jpe?g)$\" or \"db$\". Matches all extensions if omitted.")
            {
                Optional = true, DefaultValue = string.Empty
            };
            var startDateArgument = new ValueArgument <DateTime>('s', "start-date", "The range start date (YYYY-MM-DD).")
            {
                Optional = false
            };
            var endDateArgument = new ValueArgument <DateTime>('e', "end-date", "The range end date (YYYY-MM-DD).")
            {
                Optional = false
            };

            cliParser.ShowUsageHeader = "Check if a directory containing files with named date ranges is missing any dates from a given range.";
            cliParser.Arguments.Add(directoryArgument);
            cliParser.Arguments.Add(fileExtensionArgument);
            cliParser.Arguments.Add(startDateArgument);
            cliParser.Arguments.Add(endDateArgument);
            cliParser.ShowUsageOnEmptyCommandline = true;

            try
            {
                cliParser.ParseCommandLine(args);
            }
            catch (CommandLineException cle)
            {
                Console.WriteLine(cle.Message);
                cliParser.ShowUsage();
                return;
            }
            catch (DirectoryNotFoundException dnfe)
            {
                Console.WriteLine(dnfe.Message.EndsWith(" and DirectoryMustExist flag is set to true.")
                    ? dnfe.Message.Substring(0, dnfe.Message.Length - 44)
                    : dnfe.Message);
                return;
            }

            if (!cliParser.ParsingSucceeded)
            {
                return;
            }

            if (startDateArgument.Value > endDateArgument.Value)
            {
                Console.WriteLine("The start date of the range cannot be later than the end date.");
                return;
            }

            Console.BackgroundColor = ConsoleColor.Black;

            if (HasMissingRanges(directoryArgument.Value, fileExtensionArgument.Value, (startDateArgument.Value, endDateArgument.Value), out (DateTime, DateTime)[] missingRanges))
Beispiel #14
0
        public void GetArgumentSyntax_WhenUsingStringValueAndArgumentTypePath_ShouldGetCodeThatContainsQuotesAndAtSign()
        {
            var argument = new ValueArgument("test", StringType.Path);
            var syntax   = argument.GetArgumentSyntax();

            Assert.IsInstanceOf <ArgumentSyntax>(syntax);
            Assert.AreEqual("@\"test\"", syntax.ToString());
        }
Beispiel #15
0
        public void GetArgumentSyntax_WhenUsingStringValue_ShouldGetCodeThatContainsQuotes()
        {
            var argument = new ValueArgument("test");
            var syntax   = argument.GetArgumentSyntax();

            Assert.IsInstanceOf <ArgumentSyntax>(syntax);
            Assert.AreEqual("\"test\"", syntax.ToString());
        }
Beispiel #16
0
        public void GetArgumentSyntax_WhenUsingBooleanValue_ShouldGetCorrectFormat()
        {
            var argument = new ValueArgument(true);
            var syntax   = argument.GetArgumentSyntax();

            Assert.IsInstanceOf <ArgumentSyntax>(syntax);
            Assert.AreEqual("true", syntax.ToString());
        }
Beispiel #17
0
        public void GetArgumentSyntax_WhenUsingNumberValueAsNamedArgument_ShouldGetCode()
        {
            var argument = new ValueArgument(1, "namedArgument");
            var syntax   = argument.GetArgumentSyntax();

            Assert.IsInstanceOf <ArgumentSyntax>(syntax);
            Assert.AreEqual("namedArgument:1", syntax.ToString());
        }
Beispiel #18
0
 public void ConstructorTest3()
 {
     var argument = new ValueArgument<string>("arg", "");
     const string message = "message";
     var exception = new CommandLineParserException(argument, message);
     Assert.AreEqual(argument.Name, exception.Argument);
     Assert.AreEqual(message, exception.Message);
 }
Beispiel #19
0
 public void ConstructorTest3()
 {
     var argument = new ValueArgument<string>("arg", "");
     const string value = "value";
     var exception = new InvalidArgumentValueException(argument, value);
     Assert.AreEqual(argument.Name, exception.Argument);
     Assert.AreEqual(value, exception.Value);
 }
Beispiel #20
0
        private static void Main(string[] args)
        {
            CommandLineParser.CommandLineParser parser = new CommandLineParser.CommandLineParser();

            ValueArgument <string> inputLogFile = new ValueArgument <string>('i', "input", "Specify filepath of CSV file to process");

            inputLogFile.Optional = false;
            ValueArgument <string> outputLogFile = new ValueArgument <string>('o', "output", "Specify filepath to save CSV file");

            outputLogFile.Optional = false;
            ValueArgument <string> connectionString = new ValueArgument <string>('c', "connection", "Specify connection string");

            connectionString.Optional = false;

            parser.Arguments.Add(inputLogFile);
            parser.Arguments.Add(outputLogFile);
            parser.Arguments.Add(connectionString);

            //parser.ShowUsageHeader = "Welcome to EventParser!";
            //parser.ShowUsageFooter = "Thank you for using the application.";
            //parser.ShowUsage();

            try
            {
                parser.ParseCommandLine(args);
                if (inputLogFile.Parsed)
                {
                    Arguments.input = inputLogFile.Value;
                }
                if (outputLogFile.Parsed)
                {
                    Arguments.output = outputLogFile.Value;
                }
                if (connectionString.Parsed)
                {
                    Arguments.connString = connectionString.Value;
                }
            }
            catch (CommandLineException e)
            {
                Console.WriteLine(e.Message);
                parser.ShowUsage();
            }

            // Validation
            if (Arguments.input != null && Arguments.output != null && Arguments.connString != null)
            {
                Console.WriteLine($"PROCESSING: {Arguments.input}");
                Stopwatch sw = Stopwatch.StartNew();

                AddMissingHeader();
                ParseLog();
                ImportToMSSQL();

                Console.WriteLine("Success.");
                Console.WriteLine($"Time elapsed: {sw.ElapsedMilliseconds} ms");
            }
        }
        public void ConstructorTest3()
        {
            var          argument  = new ValueArgument <string>("arg", "");
            const string value     = "value";
            var          exception = new InvalidArgumentValueException(argument, value);

            Assert.AreEqual(argument.Name, exception.Argument);
            Assert.AreEqual(value, exception.Value);
        }
        public void ConstructorTest4()
        {
            var          argument  = new ValueArgument <string>("arg", "");
            const string message   = "message";
            var          exception = new DuplicateArgumentException(argument, message);

            Assert.AreEqual(argument.Name, exception.Argument);
            Assert.AreEqual(message, exception.Message);
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            var parser   = new CommandLineParser.CommandLineParser();
            var send     = new SwitchArgument('s', "send", "Whether to automatically send the messages or not", false);
            var template = new ValueArgument <string>('t', "template", "The path to the html template (title = subject)");
            var csv      = new ValueArgument <string>('c', "csv", "The path to the CSV file");

            parser.Arguments.Add(template);
            parser.Arguments.Add(csv);
            parser.Arguments.Add(send);

            try
            {
                parser.ParseCommandLine(args);
                parser.ShowParsedArguments();
            }
            catch (System.Exception exc)
            {
                Console.WriteLine(exc.Message);
                return;
            }


            var reader  = new CsvReader(new StreamReader(new FileStream(csv.Value, FileMode.Open)));
            var content = File.ReadAllText(template.Value);

            var title = XElement.Parse(content).Descendants("title").First().Value;

            while (reader.Read())
            {
                var body = content;
                foreach (var f in reader.FieldHeaders)
                {
                    body = body.Replace("{" + f.ToLower() + "}", reader.GetField <string>(f));
                }

                var app = new Application();
                var ns  = app.GetNamespace("MAPI");
                ns.Logon(null, null, false, false);
                var       outbox  = ns.GetDefaultFolder(OlDefaultFolders.olFolderOutbox);
                _MailItem message = app.CreateItem(OlItemType.olMailItem);
                message.To                    = reader.GetField <string>(reader.FieldHeaders.Single(fh => string.Equals(fh, "email", StringComparison.InvariantCultureIgnoreCase)));
                message.Subject               = title;
                message.BodyFormat            = OlBodyFormat.olFormatHTML;
                message.HTMLBody              = body;
                message.SaveSentMessageFolder = outbox;
                if (send.Value)
                {
                    message.Send();
                }
                else
                {
                    message.Save();
                }
            }
        }
Beispiel #24
0
 public void ConstructorTest5()
 {
     var argument = new ValueArgument<string>("arg", "");
     const string message = "message";
     var innerException = new Exception();
     var exception = new DuplicateArgumentException(argument, message, innerException);
     Assert.AreEqual(argument.Name, exception.Argument);
     Assert.AreEqual(message, exception.Message);
     Assert.AreEqual(innerException, exception.InnerException);
 }
Beispiel #25
0
        static int Main(string[] args)
        {
            bool isElevated;

            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            if (!isElevated)
            {
                Console.Error.WriteLine("You must be Administrator to run this.");
                return(-2);
            }
            CommandLineParser.CommandLineParser parser = new CommandLineParser.CommandLineParser
            {
                ShowUsageHeader = "ProcSurgeon - Minimal ProcMon logs for when a process starts."
            };
            FileArgument procMon = new FileArgument('p', "procmon", "Path of the procmon executable")
            {
                FileMustExist = true,
                Optional      = false
            };
            FileArgument target = new FileArgument('t', "target", "Path of the target executable")
            {
                FileMustExist = true,
                Optional      = false
            };
            ValueArgument <string> output = new ValueArgument <string>('o', "output", "Path of the output")
            {
                Optional = false
            };
            ValueArgument <int> time = new ValueArgument <int>('m', "millis", "How many milliseconds to log after starting the target." +
                                                               " If you do not include this parameter, ProcSurgeon will wait for the target process to exit.")
            {
                DefaultValue = 0
            };

            parser.Arguments.Add(procMon);
            parser.Arguments.Add(target);
            parser.Arguments.Add(output);
            parser.Arguments.Add(time);
            try
            {
                parser.ParseCommandLine(args);
            }
            catch (CommandLineException e)
            {
                Console.Error.WriteLine(e.Message);
                parser.ShowUsage();
                return(-1);
            }
            Execute(procMon.Value.FullName, target.Value.FullName, output.Value, time.Value);
            return(0);
        }
Beispiel #26
0
 private void AddCommandLineArguments()
 {
     // Add command-line argument "<file>"
     _fileArgument = new ValueArgument<string>("file", "Specifies the file to open on startup.")
     {
         IsOptional = true,
         AllowMultiple = true,
         Category = "Documents"
     };
     Editor.CommandLineParser.Arguments.Add(_fileArgument);
 }
 private void AddCommandLineArguments()
 {
     // Add command-line argument "<file>"
     _fileArgument = new ValueArgument <string>("file", "Specifies the file to open on startup.")
     {
         IsOptional    = true,
         AllowMultiple = true,
         Category      = "Documents"
     };
     Editor.CommandLineParser.Arguments.Add(_fileArgument);
 }
Beispiel #28
0
        public void ValueArgument_ShouldParseDate()
        {
            var commandLineParser             = new CommandLineParser.CommandLineParser();
            ValueArgument <DateTime> dateTime = new ValueArgument <DateTime>('d', "date");

            commandLineParser.Arguments.Add(dateTime);

            commandLineParser.ParseCommandLine(new [] { "-d", "2008-11-01" });

            Assert.Equal(new DateTime(2008, 11, 01), dateTime.Value);
        }
        public void ConstructorTest5()
        {
            var          argument       = new ValueArgument <string>("arg", "");
            const string message        = "message";
            var          innerException = new Exception();
            var          exception      = new MissingArgumentException(argument, message, innerException);

            Assert.AreEqual(argument.Name, exception.Argument);
            Assert.AreEqual(message, exception.Message);
            Assert.AreEqual(innerException, exception.InnerException);
        }
Beispiel #30
0
 public void ConstructorTest6()
 {
     var argument = new ValueArgument<string>("arg", "");
     const string value = "value";
     const string message = "message";
     var innerException = new Exception();
     var exception = new InvalidArgumentValueException(argument, value, message, innerException);
     Assert.AreEqual(argument.Name, exception.Argument);
     Assert.AreEqual(value, exception.Value);
     Assert.AreEqual(innerException, exception.InnerException);
     Assert.AreEqual(message, exception.Message);
 }
        public void ConstructorTest6()
        {
            var          argument       = new ValueArgument <string>("arg", "");
            const string value          = "value";
            const string message        = "message";
            var          innerException = new Exception();
            var          exception      = new InvalidArgumentValueException(argument, value, message, innerException);

            Assert.AreEqual(argument.Name, exception.Argument);
            Assert.AreEqual(value, exception.Value);
            Assert.AreEqual(innerException, exception.InnerException);
            Assert.AreEqual(message, exception.Message);
        }
Beispiel #32
0
        public void ParseCustomType()
        {
            ValueArgument<CustomType> argument = new ValueArgument<CustomType>("Custom", "")
            {
                AllowMultiple = true
            };

            int i = 1;
            string[] args = { "other", "Xyz", "12345" };
            var result = (ArgumentResult<CustomType>)argument.Parse(args, ref i);
            Assert.AreEqual(3, i);
            Assert.AreEqual(2, result.Values.Count);
            Assert.AreEqual("Xyz", result.Values[0].Value);
            Assert.AreEqual("12345", result.Values[1].Value);
        }
Beispiel #33
0
        // Defines the standard command-line arguments
        protected void SetupCommandLine()
        {
            ValueArgument arg = _cmdLine.AddPositionalArgument("CommandOrFile",
                                                               "The name of the command to execute, or the path to a file containing commands to execute");

            arg.IsRequired = true;
            arg.Validate   = ValidateCommand;

            arg = _cmdLine.AddKeywordArgument("LogLevel", "Set logging to the specified log level",
                                              (_, val) => Log(val, null));
            arg.AddValidator(new ListValidator("NONE", "SEVERE", "ERROR", "WARN",
                                               "INFO", "FINE", "TRACE", "DEBUG"));

            _cmdLine.AddFlagArgument("Debug", "Enable debug logging",
                                     (_, val) => Log("DEBUG", null));
        }
Beispiel #34
0
        static int Main(string[] args)
        {
            var settings = Properties.Settings.Default;

            CommandLineParser.CommandLineParser parser = new CommandLineParser.CommandLineParser(); //switch argument is meant for true/false logic
            FileArgument inputFile = new FileArgument('i', "input", "Input Excellon file");

            inputFile.FileMustExist = true;
            inputFile.Optional      = false;
            FileArgument outputFile = new FileArgument('o', "output", "Output GRBL file");

            outputFile.FileMustExist = false;
            outputFile.Optional      = false;
            ValueArgument <double> maximumZ = new ValueArgument <double>("zmax");

            maximumZ.DefaultValue = settings.zmax;
            ValueArgument <double> minimumZ = new ValueArgument <double>("zmin");

            minimumZ.DefaultValue = settings.zmin;
            parser.Arguments.Add(inputFile);
            parser.Arguments.Add(outputFile);
            parser.Arguments.Add(minimumZ);
            parser.Arguments.Add(maximumZ);
            try
            {
                parser.ParseCommandLine(args);
                var xlnConfig = new ExcellonToGCodeConverterConfig(
                    settings.drillFeed,
                    settings.moveFeed,
                    settings.spindle,
                    minimumZ.Value,
                    maximumZ.Value);
                var xlnConverter = new ExcellonToGCodeConverter(xlnConfig);
                using (var reader = inputFile.Value.OpenText())
                    using (var writer = new StreamWriter(outputFile.Value.OpenWrite()))
                    {
                        xlnConverter.Convert(reader, writer);
                    }

                return(0);
            }
            catch (CommandLineException e)
            {
                Console.WriteLine(e.Message);
                return(-1);
            }
        }
Beispiel #35
0
        public void ParseCustomType()
        {
            ValueArgument <CustomType> argument = new ValueArgument <CustomType>("Custom", "")
            {
                AllowMultiple = true
            };

            int i = 1;

            string[] args   = { "other", "Xyz", "12345" };
            var      result = (ArgumentResult <CustomType>)argument.Parse(args, ref i);

            Assert.AreEqual(3, i);
            Assert.AreEqual(2, result.Values.Count);
            Assert.AreEqual("Xyz", result.Values[0].Value);
            Assert.AreEqual("12345", result.Values[1].Value);
        }
Beispiel #36
0
        public Moflon2Parser(String[] args)
        {
            eapFile = new ValueArgument <string>('a', "eap", "eap file");
            xmiFile = new ValueArgument <string>('x', "xmi", "xmi file");
            export  = new SwitchArgument('e', "export", false);
            import  = new SwitchArgument('i', "import", false);
            codegen2compatibility = new SwitchArgument('c', "codegen2", false);
            validate = new SwitchArgument('v', "validate", false);

            eapFile.AllowMultiple = true;
            parser.AdditionalArgumentsSettings.AcceptAdditionalArguments = true;

            parser.Arguments.Add(eapFile);
            parser.Arguments.Add(xmiFile);
            parser.Arguments.Add(export);
            parser.Arguments.Add(import);
            parser.Arguments.Add(codegen2compatibility);
            parser.Arguments.Add(validate);
            try
            {
                parser.ParseCommandLine(args);
            }
            catch (UnknownArgumentException e)
            {
                Console.Out.WriteLine("EXCEPTION:" + e.Message + "#");
            }
            doImport();
            doExport();

            if (validate.Value)
            {
                EA.Repository repository = null;
                String        filename   = eapFile.Value;
                repository = new EA.Repository();
                repository.OpenFile(filename);
                ConsistencyModule cM = new ConsistencyModule();
                cM.initializeRules();

                SQLRepository sqlRep = new SQLRepository(repository, false);

                cM.dispatchFullRulecheck(ref sqlRep, true);
            }
        }
Beispiel #37
0
        static void Main(string[] args)
        {
            using var parser = new CommandLineParser.CommandLineParser();

            args = args.Select(s => s.ToLower()).ToArray();

            SwitchArgument verbose = new SwitchArgument('v', "verbose", "Show verbose debugging info", false);

            verbose.Optional = true;

            ValueArgument <H3Index> h3 = new ValueArgument <H3Index>
                                             ('h', "h3index", "H3Index (in hexadecimal) to examine");

            h3.ConvertValueHandler = value => value.ToH3Index();

            parser.Arguments.Add(verbose);
            parser.Arguments.Add(h3);

            try
            {
                var argParser = new H3ToComponentsParser();
                parser.ExtractArgumentAttributes(argParser);
                parser.ParseCommandLine(args);

                if (h3.Parsed)
                {
                    var data = new H3ToComponentsParser {
                        Verbose = verbose.Value, H3 = h3.Value
                    };
                    ProcessData(data);
                }
                else
                {
                    Console.WriteLine("Unable to parse input.");
                    parser.ShowUsage();
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to parse input.");
                parser.ShowUsage();
            }
        }
        public void EqualSignSyntax_ShouldAcceptEmptyListOfValues_whenValueOptional()
        {
            string[] args = new[] { "-n=", "-n=" };

            var commandLineParser = new CommandLineParser.CommandLineParser();

            commandLineParser.AcceptEqualSignSyntaxForValueArguments = true;
            ValueArgument <int> lines = new ValueArgument <int>('n', "lines", "Specific lines")
            {
                AllowMultiple = true, ValueOptional = true
            };

            commandLineParser.Arguments.Add(lines);

            // ACT
            commandLineParser.ParseCommandLine(args);

            // ASSERT
            Assert.Equal(new List <int>(), lines.Values);
        }
Beispiel #39
0
        /// <summary>
        /// Validates the installations.
        /// </summary>
        /// <returns></returns>
        void ValidateInstallations(ValueArgument <string> IgnoredArgument)
        {
            InstallList = new Scanner().Scan();
            foreach (Package error in InstallList.Where(iap => !iap.ValidateInstall()).ToList())
            {
                InstallList.Remove(error);
            }

            InvalidPackages = InstallList.Where(iap => !iap.ValidateInstall()).ToList();

            foreach (Package invalidPackage in InvalidPackages)
            {
                NLogger.Debug($"{invalidPackage.Packagename} is invalid.");
            }


            if (InvalidPackages.Count > 0)
            {
                ProgressChanged?.Invoke(InvalidPackages.Select(invalid => invalid.Packagename).ToList(),
                                        NotificationType.Installaltioninvalid);
            }

            InstallList.Sort();

            if (string.IsNullOrEmpty(IgnoredArgument?.Value))
            {
                return;
            }

            foreach (var packagename in IgnoredArgument.Value.Split(';'))
            {
                IgnoredList?.Add(
                    InstallList.Find(
                        x => string.Equals(x.Packagename, packagename, StringComparison.CurrentCultureIgnoreCase)));
                NLogger.Debug($"{packagename} is ignored.");
            }

            InstallList = Utils.Remove(InstallList, IgnoredList);

            InstallList.Sort();
        }
Beispiel #40
0
        public void ParseFloat()
        {
            ValueArgument<float> argument = new ValueArgument<float>("float", "Description")
            {
                Category = "Category",
                IsOptional = true,
            };

            Assert.AreEqual("float", argument.Name);
            Assert.AreEqual("Description", argument.Description);
            Assert.AreEqual("Category", argument.Category);

            Assert.IsFalse(string.IsNullOrEmpty(argument.GetSyntax()));
            Assert.IsFalse(string.IsNullOrEmpty(argument.GetHelp()));
            Assert.IsFalse(argument.AllowMultiple);

            int i = 1;
            string[] args = { "other", "123.4", "-456", "other" };
            var result = (ArgumentResult<float>)argument.Parse(args, ref i);
            Assert.AreEqual(2, i);
            Assert.AreEqual(1, result.Values.Count);
            Assert.AreEqual(123.4f, result.Values[0]);
        }
Beispiel #41
0
        static int Main(string[] args)
        {
            CommandLineParser parser = new CommandLineParser
            {
                AllowUnknownArguments = true,
            };

            parser.Description = "This is just a test application that demonstrates the usage of the CommandLineParser.";

            parser.HelpHeader =
            @"DESCRIPTION
            Here is a very detailed description of this app. Yadda, yadda, yadda...
            Yadda, yadda, yadda...
            Yadda, yadda, yadda...";

            parser.HelpFooter =
            @"EXAMPLES
            Show the help text:
            CommandLineApp --help

            Do something else:
            CommandLineApp --Enum Value1 Foo";

            var helpArgument = new SwitchArgument("help", "Show help.", null, new[] { 'h', '?' })
            {
                Category = "Help",
                IsOptional = true,
            };
            parser.Arguments.Add(helpArgument);

            var fileArgument = new ValueArgument<string>("file", "The file to load.")
            {
                IsOptional = false,
                AllowMultiple = true,
            };
            parser.Arguments.Add(fileArgument);

            var recursiveArgument = new SwitchArgument(
                "Recursive",
                "Enables recursive mode. \n This is just a demo text to test the formatting capabilities of the CommandLineParser.",
                null,
                new[] { 'R' })
            {
                IsOptional = true,
            };
            parser.Arguments.Add(recursiveArgument);

            var switchArgument1 = new SwitchArgument(
                "Switch1",
                "Another test switch. This is just a demo text to test the formatting capabilities of the CommandLineParser.")
            {
                Category = "Test Category",
                IsOptional = true,
            };
            parser.Arguments.Add(switchArgument1);

            var switchArgument2 = new SwitchArgument(
                "Switch2",
                "Yet another test switch. This is just a demo text to test the formatting capabilities of the CommandLineParser. abcdefghijklmnopqrstuvw0123456789ABCDEFRGHIJKLMNOPQRSTUVWXYZ0123456789",
                null,
                new[] { 'S' })
            {
                Category = "Test Category",
                IsOptional = true,
            };
            parser.Arguments.Add(switchArgument2);

            SwitchArgument longArgument = new SwitchArgument(
                "extremelyLongCommandLineArgumentToTestFormatting",
                "Extremely long argument. This is just a demo text to test the formatting capabilities of the CommandLineParser.",
                null,
                new[] { 'e' })
            {
                Category = "Test Category",
                IsOptional = true,
            };
            parser.Arguments.Add(longArgument);

            var echoArgument = new SwitchValueArgument<string>(
                "echo",
                new ValueArgument<string>("text", null),
                "Prints the given text.")
            {
                Category = null,
                IsOptional = true,
            };
            parser.Arguments.Add(echoArgument);

            var valueArgument = new SwitchValueArgument<int>(
                "value",
                new ValueArgument<int>("value", null) { AllowMultiple = true },
                "This switch has an integer value.",
                null,
                new[] { 'v' })
            {
                Category = "Test Category 2",
                IsOptional = true,
            };
            parser.Arguments.Add(valueArgument);

            var boundedArgument = new SwitchValueArgument<float>(
                "bounded",
                new BoundedValueArgument<float>("boundedValue", null, 1, 5) { AllowMultiple = true, IsOptional = true },
                "This is a bounded integer value.",
                null,
                new[] { 'b' })
            {
                Category = "Test Category 2",
                IsOptional = true,
            };
            parser.Arguments.Add(boundedArgument);

            var enumArgument = new SwitchValueArgument<MyEnum>(
                "Enum",
                new EnumArgument<MyEnum>("MyEnum", null) { IsOptional = true },
                "This is an enumeration.",
                null,
                new[] { 'e' })
            {
                Category = "Test Category 2",
                IsOptional = true,
            };
            parser.Arguments.Add(enumArgument);

            var flagsArgument = new SwitchValueArgument<MyFlags>(
                "Flags",
                new EnumArgument<MyFlags>("MyFlags", "The value."),
                "This is a combination of flags (= enumeration with FlagsAttribute).",
                null,
                new[] { 'f' })
            {
                Category = "Test Category 2",
                IsOptional = true,
            };
            parser.Arguments.Add(flagsArgument);

            ParseResult parseResult;
            try
            {
                parseResult = parser.Parse(args);

                if (parseResult.ParsedArguments[helpArgument] != null)
                {
                    // Show help and exit.
                    Console.WriteLine(parser.GetHelp());
                    return ERROR_SUCCESS;
                }

                parser.ThrowIfMandatoryArgumentIsMissing(parseResult);
            }
            catch (CommandLineParserException exception)
            {
                Console.Error.WriteLine("ERROR");
                Console.Error.WriteLineIndented(exception.Message, 4);
                Console.Error.WriteLine();
                Console.Out.WriteLine("SYNTAX");
                Console.Out.WriteLineIndented(parser.GetSyntax(), 4);
                Console.Out.WriteLine();
                Console.Out.WriteLine("Try 'CommandLineApp --help'�for�more�information.");
                return ERROR_BAD_ARGUMENTS;
            }

            var echo = parseResult.ParsedArguments["echo"] as ArgumentResult<string>;
            if (echo != null)
            {
                Console.Out.WriteLineWrapped(echo.Values[0]);
                return ERROR_SUCCESS;
            }

            Console.WriteLine("----- Raw arguments");
            foreach (var arg in parseResult.RawArguments)
                Console.WriteLine(arg);

            Console.WriteLine();

            Console.WriteLine("----- Unknown arguments");
            foreach (var arg in parseResult.UnknownArguments)
                Console.WriteLine(arg);

            Console.WriteLine();

            Console.WriteLine("----- Parsed arguments");
            foreach (var arg in parseResult.ParsedArguments)
            {
                Console.Write("--");
                Console.Write(arg.Argument.Name);

                var values = arg.Values.Cast<object>().ToArray();

                if (values.Length > 0)
                {
                    Console.WriteLine(":");
                    foreach (var value in values)
                    {
                        Console.Write("    ");
                        Console.WriteLine(value);
                    }
                }
                else
                {
                    Console.WriteLine();
                }
            }

            return ERROR_SUCCESS;
        }
Beispiel #42
0
        public void ParseInteger2()
        {
            var valueArg = new ValueArgument<int>("i", "") { AllowMultiple = false, IsOptional = true };
            var argument = new SwitchValueArgument<int>("Value", valueArg, "Description", null, new[] { 'v' })
            {
                Category = "Category",
                IsOptional = true,
            };

            int i = 0;
            string[] args = { "--value:1", "23", "4", "other" };
            var result = (ArgumentResult<int>)argument.Parse(args, ref i);
            Assert.AreEqual(1, i);
            Assert.AreEqual(1, result.Values.Count);
            Assert.AreEqual(1, result.Values[0]);
        }
Beispiel #43
0
 public void ConstructorTest3()
 {
     var argument = new ValueArgument<string>("arg", "");
     var exception = new DuplicateArgumentException(argument);
     Assert.AreEqual(argument.Name, exception.Argument);
 }
Beispiel #44
0
        public void SerializationTest2()
        {
            var argument = new ValueArgument<string>("arg", "");
            const string value = null;
            var exception = new InvalidArgumentValueException(argument, value);

            using (var memoryStream = new MemoryStream())
            {
                // Serialize exception.
                var formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, exception);

                memoryStream.Position = 0;

                // Deserialize exception.
                formatter = new BinaryFormatter();
                var deserializedException = (InvalidArgumentValueException)formatter.Deserialize(memoryStream);

                Assert.AreEqual(argument.Name, deserializedException.Argument);
                Assert.AreEqual(value, deserializedException.Value);
            }
        }
Beispiel #45
0
        private static CommandLineParser ConfigureCommandLine()
        {
            var parser = new CommandLineParser
            {
                AllowUnknownArguments = false,

                Description =
            @"This command-line tool can be used to pack files and directories into a single
            package. The resulting package file uses the ZIP format and can be read with
            standard ZIP tools.",

                HelpHeader =
            @"If no package exists at the target location, a new file is created.
            When the package already exists, it is updated.The input files are compared
            with the packaged files. New files are added, modified files are updated, and
            missing files are removed from the package. Files are compared by checking the
            ""Last Modified"" time and the file size.",

                HelpFooter =
            @"Credits
            -------
            Pack.exe - Copyright (C) 2014 DigitalRune GmbH. All rights reserved.
            DotNetZip - Copyright (C) 2006-2011 Dino Chiesa. All rights reserved.
            jzlib - Copyright (C) 2000-2003 ymnk, JCraft,Inc. All rights reserved.
            zlib - Copyright (C) 1995-2004 Jean-loup Gailly and Mark Adler."
            };

            var categoryMandatory = "Mandatory";
            var categoryOptional = "Optional";

            // ----- Mandatory arguments

            // Input files
            _inputArgument = new ValueArgument<string>(
                "files",
            @"Defines the files and directories to add to the package.
            The specified files and directories are relative to the current working copy or the base directory, which can be specified with /directory.
            Wildcards ('?', '*') are supported.")
            {
                Category = categoryMandatory,
                AllowMultiple = true,
            };
            parser.Arguments.Add(_inputArgument);

            // --output, --out, -o
            _outputArgument = new SwitchValueArgument<string>(
                "output",
                new ValueArgument<string>("package", "The filename incl. path of package."),
                "Defines the package to create or update.",
                new[] { "out" },
                new[] { 'o' })
            {
                Category = categoryMandatory,
            };
            parser.Arguments.Add(_outputArgument);

            // ----- Optional arguments

            // --directory, --dir, -d
            _directoryArgument = new SwitchValueArgument<string>(
                "directory",
                new ValueArgument<string>("directory", "The base directory."),
                "Specifies the base directory where to search for files.",
                new[] { "dir" },
                new[] { 'd' })
            {
                Category = categoryOptional,
                IsOptional = true,
            };
            parser.Arguments.Add(_directoryArgument);

            // --recursive, --rec, -r
            _recursiveArgument = new SwitchArgument(
                "recursive",
                "Adds subdirectories to package.",
                new[] { "rec" },
                new[] { 'r' })
            {
                Category = categoryOptional,
                IsOptional = true,
            };
            parser.Arguments.Add(_recursiveArgument);

            // --password, --pwd, -p
            _passwordArgument = new SwitchValueArgument<string>(
                "password",
                new ValueArgument<string>("password", "The password to use."),
                "Encrypts the package with a password.",
                new[] { "pwd" },
                new[] { 'p' })
            {
                Category = categoryOptional,
                IsOptional = true,
            };
            parser.Arguments.Add(_passwordArgument);

            // --encryption, --enc, -e
            _encryptionArgument = new SwitchValueArgument<PackageEncryption>(
                "encryption",
                new EnumArgument<PackageEncryption>("method", "The default encryption method is ZipCrypto."),
                "Defines the encryption method in case a password is set.",
                new[] { "enc" },
                new[] { 'e' })
            {
                Category = categoryOptional,
                IsOptional = true,
            };
            parser.Arguments.Add(_encryptionArgument);

            // --test, -t
            _testArgument = new SwitchArgument(
                "test",
                "Makes a test run without creating/updating the actual package.",
                null,
                new[] { 't' })
            {
                Category = categoryOptional,
                IsOptional = true,
            };
            parser.Arguments.Add(_testArgument);

            // --help, -h, -?
            _helpArgument = new SwitchArgument(
                "help",
                "Shows help information.",
                null,
                new[] { 'h', '?' })
            {
                Category = "Help",
                IsOptional = true,
            };
            parser.Arguments.Add(_helpArgument);

            return parser;
        }