Example #1
0
        public static void Main(string[] args)
        {
            ProgramArguments arguments = ProgramArguments.Create(args);

            // No need to do anything when the value is null; Create already printed errors and usage to the console
            if (arguments != null)
            {
                // This application doesn't do anything useful, it's just a sample of using CommandLineParser after all. We use reflection to print
                // the values of all the properties of the sample's CommandLineArguments class, which correspond to the sample's command line arguments.

                // We use the LineWrappingTextWriter to neatly wrap console output.
                using (LineWrappingTextWriter writer = LineWrappingTextWriter.ForConsoleOut())
                {
                    // Print the full command line as received by the application
                    writer.WriteLine("The command line was: {0}", Environment.CommandLine);
                    writer.WriteLine();
                    // Print the values of the arguments, using reflection to get all the property values
                    writer.WriteLine("The following argument values were provided:");
                    writer.WriteLine("Source: {0}", arguments.Source ?? "(null)");
                    writer.WriteLine("Destination: {0}", arguments.Destination ?? "(null)");
                    writer.WriteLine("Index: {0}", arguments.Index);
                    writer.WriteLine("Date: {0}", arguments.Date == null ? "(null)" : arguments.Date.ToString());
                    writer.WriteLine("Count: {0}", arguments.Count);
                    writer.WriteLine("Verbose: {0}", arguments.Verbose);
                    writer.WriteLine("Values: {0}", arguments.Values == null ? "(null)" : "{ " + string.Join(", ", arguments.Values) + " }");
                    writer.WriteLine("Help: {0}", arguments.Help);
                }
            }
        }
 public void IndentTooSmallTest()
 {
     using (LineWrappingTextWriter target = LineWrappingTextWriter.ForStringWriter(80))
     {
         target.Indent = -1;
     }
 }
Example #3
0
 /// <summary>
 /// Utility method used by the commands to write exception data to the console.
 /// </summary>
 /// <param name="message"></param>
 public static void WriteErrorMessage(string message)
 {
     using (LineWrappingTextWriter writer = LineWrappingTextWriter.ForConsoleError())
     {
         writer.WriteLine(message);
     }
 }
 public void IndentTooLargeTest()
 {
     using (LineWrappingTextWriter target = LineWrappingTextWriter.ForStringWriter(80))
     {
         target.Indent = target.MaximumLineLength;
     }
 }
 public override void Run()
 {
     // This method is invoked after all command line arguments have been parsed
     try
     {
         // We use a LineWrappingTextWriter to neatly wrap console output
         using (LineWrappingTextWriter writer = LineWrappingTextWriter.ForConsoleOut())
             using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding(EncodingName)))
             {
                 // Write the contents of the file to the console
                 string line;
                 while ((line = reader.ReadLine()) != null)
                 {
                     writer.WriteLine(line);
                 }
             }
     }
     catch (ArgumentException ex)  // Happens if the encoding name is invalid
     {
         Program.WriteErrorMessage(ex.Message);
         // The Main method will return the exit status to the operating system. The numbers are made up for the sample, they don't mean anything.
         // Usually, 0 means success, and any other value indicates an error.
         ExitCode = 2;
     }
     catch (IOException ex)
     {
         Program.WriteErrorMessage(ex.Message);
         ExitCode = 2;
     }
     catch (UnauthorizedAccessException ex)
     {
         Program.WriteErrorMessage(ex.Message);
         ExitCode = 2;
     }
 }
 public static CommandLineParser Parse(string[] args)
 {
     Request = null;
     Ookii.CommandLine.CommandLineParser parser = new Ookii.CommandLine.CommandLineParser(typeof(CommandLineParser));
     parser.ArgumentParsed += CommandLineParser_ArgumentParsed;
     try
     {
         try
         {
             Request = (CommandLineParser)parser.Parse(args);
         }
         finally
         {
             MaybeShowLicense(args);
         }
     }
     catch (CommandLineArgumentException ex)
     {
         using (LineWrappingTextWriter writer = LineWrappingTextWriter.ForConsoleError())
         {
             Logger.Log(Logger.Level.Error, ex.Message);
         }
     }
     if (Request == null)
     {
         WriteUsageOptions options = new WriteUsageOptions()
         {
             IncludeDefaultValueInDescription = true, IncludeAliasInDescription = true
         };
         parser.WriteUsageToConsole(options);
         Logger.Log(Logger.Level.Info, "Example:");
         Logger.Log(Logger.Level.Info, "    SqlProcScaffold.exe \"Server=my...\" MyNameSpace dbo.sp% C:\\src\\MyProj");
     }
     return(Request);
 }
        public void WriteCharArrayTest()
        {
            TextWriter             baseWriter        = new StringWriter();
            int                    maximumLineLength = 80;
            bool                   disposeBaseWriter = true;
            LineWrappingTextWriter target            = new LineWrappingTextWriter(baseWriter, maximumLineLength, disposeBaseWriter);

            char[] buffer = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est, porttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh egestas eu facilisis lorem condimentum volutpat.".ToCharArray();
            int    index  = 0;
            int    count  = buffer.Length;

            target.Write(buffer, index, count);
            target.Flush();

            // write it again, in pieces exactly as long as the max line length
            for (int x = 0; x < buffer.Length; x += maximumLineLength)
            {
                target.Write(buffer, x, Math.Min(buffer.Length - x, maximumLineLength));
            }
            target.Flush();

            // And again, in pieces less than the max line length
            for (int x = 0; x < buffer.Length; x += 50)
            {
                target.Write(buffer, x, Math.Min(buffer.Length - x, 50));
            }
            target.Flush();

            string result = baseWriter.ToString();

            Assert.AreEqual("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\nporttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\nporttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\nporttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\n", result);

            baseWriter = new StringWriter();
            target     = new LineWrappingTextWriter(baseWriter, maximumLineLength, disposeBaseWriter);

            // With line endings embedded.
            buffer = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est, porttitor eget posuere in,\r\n hendrerit in tortor.\r\nNulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\n".ToCharArray();
            count  = buffer.Length;

            target.Write(buffer, 0, count);
            target.Flush();
            result = baseWriter.ToString();
            Assert.AreEqual("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\nporttitor eget posuere in,\r\n hendrerit in tortor.\r\nNulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\n", result);

            baseWriter = new StringWriter();
            target     = new LineWrappingTextWriter(baseWriter, maximumLineLength, disposeBaseWriter);

            // With no place to wrap.
            buffer = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789".ToCharArray();
            count  = buffer.Length;
            target.Write(buffer, 0, count);
            target.Flush();
            result = baseWriter.ToString();
            Assert.AreEqual("01234567890123456789012345678901234567890123456789012345678901234567890123456789\r\n01234567890123456789\r\n", result);
        }
        public void WriteStringTest()
        {
            int    maximumLineLength = 80;
            bool   disposeBaseWriter = true;
            string value;

            using (TextWriter baseWriter = new StringWriter())
                using (LineWrappingTextWriter target = new LineWrappingTextWriter(baseWriter, maximumLineLength, disposeBaseWriter))
                {
                    value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est, porttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh egestas eu facilisis lorem condimentum volutpat.";
                    target.Write(value);
                    target.Flush();

                    // write it again, in pieces exactly as long as the max line length
                    for (int x = 0; x < value.Length; x += maximumLineLength)
                    {
                        target.Write(value.Substring(x, Math.Min(value.Length - x, maximumLineLength)));
                    }
                    target.Flush();

                    // And again, in pieces less than the max line length
                    for (int x = 0; x < value.Length; x += 50)
                    {
                        target.Write(value.Substring(x, Math.Min(value.Length - x, 50)));
                    }
                    target.Flush();

                    string result = baseWriter.ToString();
                    Assert.AreEqual("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\nporttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\nporttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\nporttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\n", result);
                }

            using (var baseWriter = new StringWriter())
                using (var target = new LineWrappingTextWriter(baseWriter, maximumLineLength, disposeBaseWriter))
                {
                    // With line endings embedded.
                    value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est, porttitor eget posuere in,\r\n hendrerit in tortor.\r\nNulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\n";

                    target.Write(value);
                    target.Flush();
                    string result = baseWriter.ToString();
                    Assert.AreEqual("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\nporttitor eget posuere in,\r\n hendrerit in tortor.\r\nNulla adipiscing turpis id nibh\r\negestas eu facilisis lorem condimentum volutpat.\r\n", result);
                }

            using (var baseWriter = new StringWriter())
                using (var target = new LineWrappingTextWriter(baseWriter, maximumLineLength, disposeBaseWriter))
                {
                    // With no place to wrap.
                    value = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
                    target.Write(value);
                    target.Flush();
                    string result = baseWriter.ToString();
                    Assert.AreEqual("01234567890123456789012345678901234567890123456789012345678901234567890123456789\r\n01234567890123456789\r\n", result);
                }
        }
        public void WriteStringUnixLineEndingTest()
        {
            using (LineWrappingTextWriter target = LineWrappingTextWriter.ForStringWriter(80))
            {
                target.NewLine            = "\n";
                target.BaseWriter.NewLine = "\n";
                string value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est, porttitor eget posuere in,\n hendrerit in tortor.\nNulla adipiscing turpis id nibh\negestas eu facilisis lorem condimentum volutpat.\n";

                target.Write(value);
                target.Flush();
                string result = target.BaseWriter.ToString();
                Assert.AreEqual("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\nporttitor eget posuere in,\n hendrerit in tortor.\nNulla adipiscing turpis id nibh\negestas eu facilisis lorem condimentum volutpat.\n", result);
            }
        }
        public void DisposeBaseWriterFalseTest()
        {
            using (TextWriter baseWriter = new StringWriter())
            {
                using (LineWrappingTextWriter target = new LineWrappingTextWriter(baseWriter, 80, false))
                {
                    target.Write("test");
                }

                // This will throw if the base writer was disposed.
                baseWriter.Write("foo");

                Assert.AreEqual("test\r\nfoo", baseWriter.ToString());
            }
        }
        public void ConstructorTest()
        {
            int  maximumLineLength = 85;
            bool disposeBaseWriter = true;

            using (TextWriter baseWriter = new StringWriter())
                using (LineWrappingTextWriter target = new LineWrappingTextWriter(baseWriter, maximumLineLength, disposeBaseWriter))
                {
                    Assert.AreEqual(baseWriter, target.BaseWriter);
                    Assert.AreEqual(maximumLineLength, target.MaximumLineLength);
                    Assert.AreEqual(0, target.Indent);
                    Assert.AreEqual(baseWriter.Encoding, target.Encoding);
                    Assert.AreEqual(baseWriter.FormatProvider, target.FormatProvider);
                    Assert.AreEqual(baseWriter.NewLine, target.NewLine);
                }
        }
 public override void Run()
 {
     // This method is invoked after all command line arguments have been parsed
     try
     {
         // Check if we're allowed to overwrite the file.
         if (!Overwrite && File.Exists(FileName))
         {
             // The Main method will return the exit status to the operating system. The numbers are made up for the sample, they don't mean anything.
             // Usually, 0 means success, and any other value indicates an error.
             Program.WriteErrorMessage("File already exists.");
             ExitCode = 3;
         }
         else
         {
             // We use a LineWrappingTextWriter to neatly wrap the output.
             using (StreamWriter writer = new StreamWriter(FileName, false, Encoding.GetEncoding(EncodingName)))
                 using (LineWrappingTextWriter lineWriter = new LineWrappingTextWriter(writer, MaximumLineLength, true))
                 {
                     // Write the specified content to the file
                     foreach (string line in GetLines())
                     {
                         lineWriter.WriteLine(line);
                     }
                 }
         }
     }
     catch (ArgumentException ex)  // Happens if the encoding name is invalid
     {
         Program.WriteErrorMessage(ex.Message);
         ExitCode = 2;
     }
     catch (IOException ex)
     {
         Program.WriteErrorMessage(ex.Message);
         ExitCode = 2;
     }
     catch (UnauthorizedAccessException ex)
     {
         Program.WriteErrorMessage(ex.Message);
         ExitCode = 2;
     }
 }
        public void DisposeBaseWriterTrueTest()
        {
            using (TextWriter baseWriter = new StringWriter())
            {
                using (LineWrappingTextWriter target = new LineWrappingTextWriter(baseWriter, 80, true))
                {
                    target.Write("test");
                }

                try
                {
                    baseWriter.Write("foo");
                    Assert.Fail("base writer not disposed");
                }
                catch (ObjectDisposedException)
                {
                }

                Assert.AreEqual("test\r\n", baseWriter.ToString());
            }
        }
Example #14
0
        public static ProgramArguments Create(string[] args)
        {
            // Using a static creation function for a command line arguments class is not required, but it's a convenient
            // way to place all command-line related functionality in one place. To parse the arguments (eg. from the Main method)
            // you then only need to call this function.
            CommandLineParser parser = new CommandLineParser(typeof(ProgramArguments));

            // The ArgumentParsed event is used by this sample to stop parsing after the -Help argument is specified.
            parser.ArgumentParsed += CommandLineParser_ArgumentParsed;
            try
            {
                // The Parse function returns null only when the ArgumentParsed event handler cancelled parsing.
                ProgramArguments result = (ProgramArguments)parser.Parse(args);
                if (result != null)
                {
                    return(result);
                }
            }
            catch (CommandLineArgumentException ex)
            {
                // We use the LineWrappingTextWriter to neatly wrap console output.
                using (LineWrappingTextWriter writer = LineWrappingTextWriter.ForConsoleError())
                {
                    // Tell the user what went wrong.
                    writer.WriteLine(ex.Message);
                    writer.WriteLine();
                }
            }

            // If we got here, we should print usage information to the console.
            // By default, aliases and default values are not included in the usage descriptions; for this sample, I do want to include them.
            WriteUsageOptions options = new WriteUsageOptions()
            {
                IncludeDefaultValueInDescription = true, IncludeAliasInDescription = true
            };

            // WriteUsageToConsole automatically uses a LineWrappingTextWriter to properly word-wrap the text.
            parser.WriteUsageToConsole(options);
            return(null);
        }
Example #15
0
        /// <summary>
        /// コマンドライン引数の生成
        /// </summary>
        /// <param name="args">コマンドライン引数</param>
        /// <returns></returns>
        public static CommandLineArgs Create(string[] args)
        {
            var parser = new CommandLineParser(typeof(CommandLineArgs));

            //
            parser.ArgumentParsed += Parser_ArgumentParsed;
            //
            try
            {
                var result = (CommandLineArgs)parser.Parse(args);
                if (result != null)
                {
                    return(result);
                }
            }
            catch (CommandLineArgumentException ex)
            {
                using (var writer = LineWrappingTextWriter.ForConsoleError())
                {
                    NativeMethods.AttachConsole(uint.MaxValue);
                    writer.WriteLine(GetParsingErrorMessage(ex));
                    writer.WriteLine();
                }
                return(new CommandLineArgs());
            }
            //
            var options = new WriteUsageOptions()
            {
                IncludeAliasInDescription        = true,
                IncludeDefaultValueInDescription = true
            };

            if (NativeMethods.AttachConsole(uint.MaxValue))
            {
                parser.WriteUsageToConsole(options);
            }
            return(null);
        }
        public void IndentStringTest()
        {
            TextWriter             baseWriter        = new StringWriter();
            int                    maximumLineLength = 80;
            bool                   disposeBaseWriter = true;
            LineWrappingTextWriter target            = new LineWrappingTextWriter(baseWriter, maximumLineLength, disposeBaseWriter)
            {
                Indent = 10
            };

            target.WriteLine(); // Writing an empty line should not cause the second line to be indented
            string value = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est, porttitor eget posuere in, hendrerit in tortor. Nulla adipiscing turpis id nibh egestas eu facilisis lorem condimentum volutpat.";

            target.Write(value);
            target.ResetIndent(); // Should add a new line

            // write it again, in pieces exactly as long as the max line length
            for (int x = 0; x < value.Length; x += maximumLineLength)
            {
                target.Write(value.Substring(x, Math.Min(value.Length - x, maximumLineLength)));
            }
            target.WriteLine();
            target.ResetIndent(); // Should not add an additional new line


            // And again, in pieces less than the max line length
            for (int x = 0; x < value.Length; x += 50)
            {
                target.Write(value.Substring(x, Math.Min(value.Length - x, 50)));
            }
            target.Flush();

            string result = baseWriter.ToString();

            Assert.AreEqual("\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\n          porttitor eget posuere in, hendrerit in tortor. Nulla adipiscing\r\n          turpis id nibh egestas eu facilisis lorem condimentum volutpat.\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\n          porttitor eget posuere in, hendrerit in tortor. Nulla adipiscing\r\n          turpis id nibh egestas eu facilisis lorem condimentum volutpat.\r\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dolor est,\r\n          porttitor eget posuere in, hendrerit in tortor. Nulla adipiscing\r\n          turpis id nibh egestas eu facilisis lorem condimentum volutpat.\r\n", result);
        }
Example #17
0
        public static ProgramArguments Create(string[] args)
        {
            // Using a static creation function for a command line arguments class is not required, but it's a convenient
            // way to place all command-line related functionality in one place. To parse the arguments (eg. from the Main method)
            // you then only need to call this function.
            CommandLineParser parser = new CommandLineParser(typeof(ProgramArguments));
            ProgramArguments  result = null;
            bool showFullHelp        = false;

            try
            {
                // The Parse function returns null only when the ArgumentParsed event handler cancelled parsing.
                result       = (ProgramArguments)parser.Parse(args);
                showFullHelp = result.Help;
                if (result.Help)
                {
                    showFullHelp = false;
                    switch (result.Command)
                    {
                    case Command.Add:
                        Console.WriteLine("Help specific to Add command here.");
                        break;

                    case Command.Delete:
                        Console.WriteLine("Help specific to Delete command here.");
                        break;

                    case Command.Update:
                        Console.WriteLine("Help specific to Update command here.");
                        break;

                    default:
                        showFullHelp = true;
                        break;
                    }
                }
            }
            catch (CommandLineArgumentException ex)
            {
                // We use the LineWrappingTextWriter to neatly wrap console output.
                using (LineWrappingTextWriter writer = LineWrappingTextWriter.ForConsoleError())
                {
                    // Tell the user what went wrong.
                    writer.WriteLine(ex.Message);
                    writer.WriteLine();
                }
            }

            if (showFullHelp)
            {
                // If we got here, we should print usage information to the console.
                // By default, aliases and default values are not included in the usage descriptions; for this sample, I do want to include them.
                WriteUsageOptions options = new WriteUsageOptions()
                {
                    IncludeDefaultValueInDescription = true, IncludeAliasInDescription = true
                };
                // WriteUsageToConsole automatically uses a LineWrappingTextWriter to properly word-wrap the text.
                parser.WriteUsageToConsole(options);
            }
            return(result);
        }
 public void ConstructorTestBaseWriterNull()
 {
     LineWrappingTextWriter target = new LineWrappingTextWriter(null, 0, false);
 }