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;
     }
 }
Esempio n. 2
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);
     }
 }
Esempio n. 3
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);
        }
        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);
        }
 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;
     }
 }
Esempio n. 6
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);
                }
            }
        }
Esempio n. 7
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);
        }