### Install PrettyConsole via NuGet Source: https://context7.com/dusrdev/prettyconsole/llms.txt Use the .NET CLI to add the PrettyConsole package to your project. ```bash dotnet add package PrettyConsole ``` -------------------------------- ### Display Numbered Menu and Get Multiple Selections Source: https://context7.com/dusrdev/prettyconsole/llms.txt Presents a list of options as a numbered menu, allowing the user to select multiple items by entering their numbers separated by spaces. Returns an array of the selected strings. ```csharp using PrettyConsole; using static PrettyConsole.Color; string[] services = ["API", "Worker", "Scheduler", "Cache"]; string[] selected = Console.MultiSelection(services, $"{Cyan}Services to restart:{Default}"); // Output: // Services to restart: // 1) API // 2) Worker // 3) Scheduler // 4) Cache // // Enter your choices separated with spaces: 1 3 4 if (selected.Length == 0) { Console.WriteLineInterpolated($"{Yellow}No services selected.{Default}"); } else { foreach (var service in selected) { Console.WriteLineInterpolated($"Restarting {Cyan}{service}{Default}..."); } } ``` -------------------------------- ### Basic Input Reading Source: https://github.com/dusrdev/prettyconsole/wiki/2.-Basic-Inputs The `ReadLine` and `ReadLine` methods are the primary ways to get string and parsed input from the user. They support `ColoredOutput` for styling and generic parsing for custom types. ```APIDOC ## ReadLine and ReadLine ### Description Reads a line of text from the console. `ReadLine` attempts to parse the input into a specified type `T`. ### Method `ReadLine()` `ReadLine()` ### Parameters #### Query Parameters - **message** (string) - Optional - The prompt message to display to the user. - **output** (ColoredOutput) - Optional - The colored output to display as the prompt message. #### Request Body None ### Response #### Success Response (200) - **string** - The line of text entered by the user. - **T** - The parsed input of type `T`. ### Request Example ```csharp string name = ReadLine("Enter your name: "); int age = ReadLine("Enter your age: "); ``` ### Response Example ```json { "name": "John Doe", "age": 30 } ``` ``` -------------------------------- ### Display Numbered Menu and Get Single Selection Source: https://context7.com/dusrdev/prettyconsole/llms.txt Presents a list of options to the user as a numbered menu and returns the selected string. Returns an empty string if the user's input does not correspond to a valid selection. ```csharp using PrettyConsole; using static PrettyConsole.Color; string[] environments = ["Development", "Staging", "Production"]; string choice = Console.Selection(environments, $"{Cyan}Select environment:{Default}"); // Output: // Select environment: // 1) Development // 2) Staging // 3) Production // // Enter your choice: _ if (choice.Length == 0) { Console.WriteLineInterpolated($"{Red}Invalid selection.{Default}"); } else { Console.WriteLineInterpolated($"Deploying to {Green}{choice}{Default}..."); } ``` -------------------------------- ### Overwrite console output with Console.Overwrite Source: https://context7.com/dusrdev/prettyconsole/llms.txt Use to create live-updating displays by returning the cursor to the starting position. The state-based overload helps minimize closure allocations. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Basic overwrite loop for (int i = 0; i <= 100; i += 5) { Console.Overwrite(() => { Console.WriteInterpolated(OutputPipe.Error, $"Progress: {Cyan}{i}%{Default}"); }, lines: 1, pipe: OutputPipe.Error); await Task.Delay(100); } Console.ClearNextLines(1, OutputPipe.Error); // Overwrite with state to avoid closure allocations for (int i = 0; i <= 100; i += 4) { Console.Overwrite(i, static percent => { ProgressBar.Render(OutputPipe.Error, percent, Color.Cyan, maxLineWidth: 40); Console.NewLine(OutputPipe.Error); Console.WriteInterpolated(OutputPipe.Error, $"Downloading... {Color.Cyan}{percent}%"); }, lines: 2, pipe: OutputPipe.Error); await Task.Delay(70); } Console.ClearNextLines(2, OutputPipe.Error); Console.WriteLineInterpolated($"{Green}Download complete!{Default}"); ``` -------------------------------- ### Confirm Boolean Choice with PrettyConsole Source: https://github.com/dusrdev/prettyconsole/wiki/2.-Basic-Inputs Use Confirm to get a boolean confirmation from the user. It handles input with a message and supports custom true values, ignoring case. The default true values are 'y', 'yes', and an empty string. ```csharp Confirm(ColoredOutput message); ``` ```csharp Confirm(ColoredOutput message, ReadOnlySpan trueValues, bool emptyIsTrue = true) ``` -------------------------------- ### Handle console input Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Input helpers support IParsable, enums, and default values. ```csharp if (!Console.TryReadLine(out int port, $"Port ({Green}5000{Default}): ")) { port = 5000; } // `TryReadLine` and `TryReadLine` with defaults if (!Console.TryReadLine(out DayOfWeek day, ignoreCase: true, $"Day? ")) { day = DayOfWeek.Monday; } var apiKey = Console.ReadLine($"Enter API key ({DarkGray}optional{Default}): "); ``` -------------------------------- ### Implementing Progress Bars Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Utilize the `ProgressBar` class for visual progress indication. Customize appearance with `ProgressChar`, `ForegroundColor`, and `ProgressColor`. Use `Update` for continuous refreshing and `Render` for one-off displays. `sameLine: false` allows separate status text. ```csharp var progress = new ProgressBar { ProgressChar = '■', ForegroundColor = Color.DarkGray, ProgressColor = Color.Green, }; for (int i = 0; i <= 100; i += 5) { progress.Update(i, $"Downloading chunk {i / 5}"); await Task.Delay(50); } // Need separate status + bar lines? sameLine: false progress.Update(42.5, "Syncing", sameLine: false); // One-off render without state ProgressBar.Render(OutputPipe.Error, 75, Color.Magenta, '*', maxLineWidth: 32); ``` -------------------------------- ### Create ColoredOutput with mathematical operators Source: https://github.com/dusrdev/prettyconsole/wiki/1.-Basic-Outputs Use the multiplication and division operators with strings and Color objects to define foreground and background colors. These operators allow for fluid syntax while maintaining performance. ```csharp WriteLine("Test" * Color.Red / Color.Blue); // Red foreground and blue background WriteLine("Test" * Color.Red); // Red foreground and default background (black) WriteLine("Test" / Color.Blue); // Blue background and default foreground (gray) ``` -------------------------------- ### Request Any Input with PrettyConsole Source: https://github.com/dusrdev/prettyconsole/wiki/2.-Basic-Inputs Use RequestAnyInput to prompt the user with a message and wait for them to press Enter. This is similar to Console.ReadKey(). ```csharp RequestAnyInput(string message = "Press any key to continue"); ``` ```csharp RequestAnyInput(ColoredOutput output); ``` -------------------------------- ### Define and use custom ANSI tokens in C# Source: https://context7.com/dusrdev/prettyconsole/llms.txt Demonstrates creating 256-color and RGB ANSI tokens and applying them within interpolated strings. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Create custom 256-color token var rose = new AnsiToken(""); var orange = new AnsiToken(""); Console.WriteLineInterpolated($"{rose}Rose colored text{Default}"); Console.WriteLineInterpolated($"{orange}Orange accent{Default}"); // Create RGB color (true color terminals) var customBlue = new AnsiToken(""); Console.WriteLineInterpolated($"{customBlue}Cornflower blue{Default}"); ``` -------------------------------- ### Creating Menus and Tables Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Generate interactive menus for single or multiple selections using `Selection`, `MultiSelection`, and `TreeMenu`. Display structured data in a tabular format with `Console.Table`, which handles column alignment automatically. ```csharp var choice = Console.Selection("Pick an environment:", ["Dev", "QA", "Prod"]); var multi = Console.MultiSelection("Services to restart:", ["API", "Worker", "Scheduler"]); var (area, action) = Console.TreeMenu("Actions", new Dictionary> { ["Users"] = ["List", "Create", "Disable"], ["Jobs"] = ["Queue", "Retry"] }); Console.Table( headers: ["Name", "Status"], columns: [ ["API", "Worker"], ["Running", "Stopped"] ] ); ``` -------------------------------- ### Console.MultiSelection Source: https://context7.com/dusrdev/prettyconsole/llms.txt Displays a numbered menu allowing multiple selections separated by spaces. Returns an array of selected strings. ```APIDOC ## Console.MultiSelection ### Description Displays a numbered menu allowing multiple selections separated by spaces. Returns an array of selected strings. ### Method `MultiSelection` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using PrettyConsole; using static PrettyConsole.Color; string[] services = ["API", "Worker", "Scheduler", "Cache"]; string[] selected = Console.MultiSelection(services, $"{Cyan}Services to restart:{Default}"); // Output: // Services to restart: // 1) API // 2) Worker // 3) Scheduler // 4) Cache // // Enter your choices separated with spaces: 1 3 4 if (selected.Length == 0) { Console.WriteLineInterpolated($"{Yellow}No services selected.{Default}"); } else { foreach (var service in selected) { Console.WriteLineInterpolated($"Restarting {Cyan}{service}{Default}..."); } } ``` ### Response #### Success Response (200) Returns an array of strings representing the user's selections. #### Response Example ``` ["API", "Scheduler", "Cache"] ``` ``` -------------------------------- ### Static Import for PrettyConsole Source: https://github.com/dusrdev/prettyconsole/wiki/4.-Useful-additions Use this static import to access all PrettyConsole features without prefixing the namespace. Be aware of potential naming conflicts with System.Console. ```csharp using static PrettyConsole.Console ``` -------------------------------- ### Utilize console rendering helpers Source: https://context7.com/dusrdev/prettyconsole/llms.txt Provides utilities for cursor positioning, clearing lines, and managing console colors. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Clear next N lines (useful after progress bars) Console.ClearNextLines(3, OutputPipe.Error); // Get and restore cursor position int startLine = Console.GetCurrentLine(); // ... do some output ... Console.GoToLine(startLine); // Return to starting line // Skip lines to keep overwritten content visible Console.WriteLineInterpolated($"Status: {Green}Complete{Default}"); Console.SkipLines(2); // Move cursor down, preserving output // Write padding/whitespace Console.WriteWhiteSpaces(10, OutputPipe.Out); // NewLine helper Console.NewLine(OutputPipe.Error); // Set console colors directly Console.SetColors(ConsoleColor.White, ConsoleColor.DarkBlue); Console.WriteLineInterpolated($"Header Bar"); Console.ResetColor(); ``` -------------------------------- ### Requesting Various Inputs Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Use `RequestAnyInput` for simple key presses, `Confirm` for boolean prompts with optional custom truth values, and `Selection`/`MultiSelection`/`TreeMenu` for structured choices. `Confirm` with custom truths allows for flexible affirmative responses. ```csharp Console.RequestAnyInput($"Press {Yellow}any key{Default} to continue…"); if (!Console.Confirm($"Deploy to production? ({Green}y{Default}/{Red}n{Default}) ")) { return; } string[] customTruths = ["sure", "do it"]; bool overwrite = Console.Confirm(customTruths, $"Overwrite existing files? ", emptyIsTrue: false); ``` -------------------------------- ### Use Interpolated String Handler for Colored Output Source: https://github.com/dusrdev/prettyconsole/blob/stable/Versions.md Demonstrates how to use the PrettyConsoleInterpolatedStringHandler to apply colors within interpolated strings. ```csharp WriteLine($"This is in {Color.Green}green{Color.Default} and this is in {Color.Red}red{Color.Default}."); ``` -------------------------------- ### Basic User Confirmation with Console.Confirm Source: https://context7.com/dusrdev/prettyconsole/llms.txt Prompts the user for a yes/no confirmation using default true values ('y', 'yes'). Returns true if the user confirms, false otherwise. Useful for critical operations. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Basic confirmation (default true values: "y", "yes") if (Console.Confirm($"Continue? ({Green}y{Default}/{Red}n{Default}): ")) { Console.WriteLineInterpolated($"{Green}Proceeding...{Default}"); } else { Console.WriteLineInterpolated($"{Yellow}Cancelled.{Default}"); } ``` -------------------------------- ### Create Animated Console Progress Bar Source: https://context7.com/dusrdev/prettyconsole/llms.txt Instantiate a ProgressBar to display an animated progress bar. Use the Update method to refresh the display with current progress and status text. Call ClearNextLines to clean up previous output. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Basic progress bar var progress = new ProgressBar { ProgressChar = '■', ProgressColor = Green, ForegroundColor = DarkGray }; for (int i = 0; i <= 100; i += 5) { progress.Update(i, $"Downloading file {i / 5 + 1}/20..."); await Task.Delay(100); } Console.ClearNextLines(1, OutputPipe.Error); Console.WriteLineInterpolated($"{Green}Download complete!{Default}"); // Progress bar with status on separate line var buildProgress = new ProgressBar { ProgressColor = Cyan }; for (int i = 0; i <= 100; i += 10) { buildProgress.Update(i, $"Compiling module {i / 10}", sameLine: false); await Task.Delay(200); } Console.ClearNextLines(2, OutputPipe.Error); // Static one-off render without state ProgressBar.Render(OutputPipe.Error, 75, Magenta, '*', maxLineWidth: 40); // Output: [*********************** ] 75% ``` -------------------------------- ### Live Console Regions for Streaming Updates Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Employ `LiveConsoleRegion` to manage a dedicated area of the console for continuously updating information, such as progress or status messages, while allowing other console output to scroll normally. Use `Render` for transient snapshots and `WriteLine` for scrollable messages. ```csharp using var live = new LiveConsoleRegion(OutputPipe.Error); live.Render($"Resolving graph"); live.WriteLine($"Updated package-a"); live.WriteLine($"Updated package-b"); live.RenderProgress(42, (builder, out handler) => handler = builder.Build(OutputPipe.Error, $"Compiling")); live.Render($"Linking {elapsed:duration}"); live.Clear(); ``` -------------------------------- ### Manage transient regions with LiveConsoleRegion Source: https://context7.com/dusrdev/prettyconsole/llms.txt Maintains a pinned console region for transient updates while allowing durable lines to scroll above it. ```csharp using PrettyConsole; using static PrettyConsole.Color; using var live = new LiveConsoleRegion(OutputPipe.Error); // Render transient content that can be updated live.Render($"Resolving dependencies..."); await Task.Delay(500); // Write durable lines that scroll above the live region live.WriteLine($" {Green}✓{Default} package-a@1.0.0"); live.WriteLine($" {Green}✓{Default} package-b@2.1.0"); live.WriteLine($" {Green}✓{Default} package-c@0.5.0"); // Update the transient region live.Render($"Compiling..."); await Task.Delay(500); // Render progress bar in the live region for (int i = 0; i <= 100; i += 10) { live.RenderProgress(i, (builder, out handler) => handler = builder.Build(OutputPipe.Error, $"Building"), progressColor: Cyan); await Task.Delay(100); } // Clear the live region when done live.Clear(); Console.WriteLineInterpolated($"{Green}Build succeeded!{Default}"); ``` -------------------------------- ### Apply inline decorations with Markup Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Use Markup tokens for bold, underline, italic, and strikethrough effects. ```csharp Console.WriteLineInterpolated($"{Markup.Bold}Build{Markup.ResetBold} {Markup.Underline}completed{Markup.ResetUnderline} in {elapsed:duration}"); // e.g. "completed in 2h 3m 17s" ``` -------------------------------- ### Bring PrettyConsole APIs into Scope Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Include these using directives to make PrettyConsole extension members and static helpers available in your code. ```csharp using PrettyConsole; using static System.Console; using static PrettyConsole.Color; ``` -------------------------------- ### Render multiple progress bars with tasks and channels Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Uses System.Threading.Channels to coordinate multiple concurrent tasks updating individual progress bars in a stacked layout. ```csharp using System.Linq; using System.Threading.Channels; string[] downloads = ["Video.mp4", "Archive.zip", "Assets.pak"]; var progress = new double[downloads.Length]; var updates = Channel.CreateUnbounded<(int index, double percent)>(); // Producers push progress updates var producers = downloads .Select((name, index) => Task.Run(async () => { for (int p = 0; p <= 100; p += Random.Shared.Next(5, 15)) { await updates.Writer.WriteAsync((index, p)); await Task.Delay(Random.Shared.Next(40, 120)); } })) .ToArray(); // Consumer renders stacked bars each time an update arrives var consumer = Task.Run(async () => { await foreach (var (index, percent) in updates.Reader.ReadAllAsync()) { progress[index] = percent; Console.Overwrite(progress, state => { for (int i = 0; i < state.Length; i++) { Console.WriteInterpolated(OutputPipe.Error, $"Task {i + 1} ({downloads[i]}): "); ProgressBar.Render(OutputPipe.Error, state[i], Color.Cyan); } }, lines: downloads.Length, pipe: OutputPipe.Error); } }); await Task.WhenAll(producers); updates.Writer.Complete(); await consumer; Console.ClearNextLines(downloads.Length, OutputPipe.Error); // ensure no artifacts remain ``` -------------------------------- ### Perform basic console output Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Standard methods for writing interpolated strings to the console or error pipe. ```csharp // Interpolated text Console.WriteInterpolated($"Processed {items} items in {elapsed:duration}"); // Processed 42 items in 3h 44m 9s Console.WriteLineInterpolated(OutputPipe.Error, $"{Magenta}debug{Default}"); ``` -------------------------------- ### Spinner for Indeterminate Progress Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Use the `Spinner` class for indeterminate progress, rendering animated frames. The `RunAsync` method with a factory overload allows for dynamic per-frame headers that can reflect changing status, such as the current time. ```csharp var spinner = new Spinner(); await spinner.RunAsync(workTask, (builder, out handler) => handler = builder.Build(OutputPipe.Error, $"Syncing {DateTime.Now:T}")); ``` -------------------------------- ### Console.Selection Source: https://context7.com/dusrdev/prettyconsole/llms.txt Displays a numbered menu and returns the user's selected string. Returns empty string if the selection is invalid. ```APIDOC ## Console.Selection ### Description Displays a numbered menu and returns the user's selected string. Returns empty string if the selection is invalid. ### Method `Selection` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using PrettyConsole; using static PrettyConsole.Color; string[] environments = ["Development", "Staging", "Production"]; string choice = Console.Selection(environments, $"{Cyan}Select environment:{Default}"); // Output: // Select environment: // 1) Development // 2) Staging // 3) Production // // Enter your choice: _ if (choice.Length == 0) { Console.WriteLineInterpolated($"{Red}Invalid selection.{Default}"); } else { Console.WriteLineInterpolated($"Deploying to {Green}{choice}{Default}..."); } ``` ### Response #### Success Response (200) Returns the selected string from the menu, or an empty string if the selection is invalid. #### Response Example ``` "Development" ``` ``` -------------------------------- ### User Confirmation with Custom True Values Source: https://context7.com/dusrdev/prettyconsole/llms.txt Prompts for user confirmation using a custom array of strings that are considered 'true'. Allows for flexible confirmation phrases and specifies whether an empty input should be treated as true. ```csharp // Custom true values string[] customTruths = ["sure", "do it", "ok"]; bool proceed = Console.Confirm(customTruths, "Overwrite files? ", emptyIsTrue: false); ``` -------------------------------- ### Align console output Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Standard C# interpolation alignment syntax is supported for columnar output. ```csharp Console.WriteInterpolated($"|{"Label",-10}|{value,10:0.00}|"); ``` -------------------------------- ### User Confirmation with Empty Input as True Source: https://context7.com/dusrdev/prettyconsole/llms.txt Prompts for user confirmation where pressing Enter without typing any input is considered a 'yes'. Useful for simple confirmations where the default action is to proceed. ```csharp // Confirm with emptyIsTrue = true (pressing Enter confirms) if (Console.Confirm("Deploy to production? [Y/n]: ")) { Console.WriteLineInterpolated($"Deploying..."); } ``` -------------------------------- ### Console.RequestAnyInput Source: https://context7.com/dusrdev/prettyconsole/llms.txt Waits for the user to press any key before continuing. ```APIDOC ## Console.RequestAnyInput ### Description Waits for the user to press any key before continuing. ### Method `RequestAnyInput` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using PrettyConsole; using static PrettyConsole.Color; Console.WriteLineInterpolated($"Installation complete!"); Console.RequestAnyInput($"Press {Yellow}any key{Default} to exit..."); // Use in menus Console.WriteLineInterpolated($"{Red}Error:{Default} Connection failed."); Console.RequestAnyInput($"Press any key to retry..."); ``` ### Response #### Success Response (200) This method does not return a value; it pauses execution until a key is pressed. #### Response Example (No specific response example provided, behavior is indicated by pausing execution) ``` -------------------------------- ### Apply Markup Tokens Source: https://context7.com/dusrdev/prettyconsole/llms.txt Applies text decorations such as bold, underline, italic, and strikethrough using guarded ANSI tokens. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Bold text Console.WriteLineInterpolated($"{Markup.Bold}Important{Markup.ResetBold} information"); // Underlined text Console.WriteLineInterpolated($"Click {Markup.Underline}here{Markup.ResetUnderline} to continue"); // Italic text Console.WriteLineInterpolated($"This is {Markup.Italic}emphasized{Markup.ResetItalic} text"); // Strikethrough text Console.WriteLineInterpolated($"Price: {Markup.Strikethrough}$100{Markup.ResetStrikethrough} $75"); // Combine decorations with colors Console.WriteLineInterpolated($"{Markup.Bold}{Green}BUILD{Markup.ResetBold}{Default} {Markup.Underline}completed{Markup.ResetUnderline}"); // Reset all decorations and colors at once Console.WriteLineInterpolated($"{Markup.Bold}{Red}Alert!{Markup.Reset} Normal text"); ``` -------------------------------- ### Parse Integer Input with TryReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads integer input from the user, providing a default value if parsing fails. Useful for obtaining numerical configuration values. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Parse integer input if (!Console.TryReadLine(out int port, $("Enter port ({Green}5000{Default}): "))) { port = 5000; // Use default on parse failure } Console.WriteLineInterpolated($"Using port: {Cyan}{port}{Default}"); ``` -------------------------------- ### TryReadLine Methods Source: https://github.com/dusrdev/prettyconsole/wiki/2.-Basic-Inputs The `TryReadLine` variants provide a way to attempt parsing input and return a boolean indicating success, along with the parsed value via an `out` parameter. ```APIDOC ## TryReadLine ### Description Attempts to read and parse a line of text from the console into a specified type `T`. Returns `true` if successful, `false` otherwise. ### Method `TryReadLine(out T value)` `TryReadLine(string message, out T value)` `TryReadLine(ColoredOutput output, out T value)` ### Parameters #### Query Parameters - **message** (string) - Optional - The prompt message to display to the user. - **output** (ColoredOutput) - Optional - The colored output to display as the prompt message. #### Request Body None ### Response #### Success Response (200) - **bool** - `true` if the input was successfully parsed, `false` otherwise. - **out T value** - The parsed value if successful. ### Request Example ```csharp if (TryReadLine("Enter a number: ", out int number)) { Console.WriteLine($"You entered: {number}"); } else { Console.WriteLine("Invalid input."); } ``` ### Response Example ```json { "success": true, "value": 123 } ``` ``` -------------------------------- ### Console.TryReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads user input with automatic parsing for any IParsable type or enum. Returns true if parsing succeeds. ```APIDOC ## Console.TryReadLine ### Description Reads user input with automatic parsing for any `IParsable` type or enum. Returns true if parsing succeeds. ### Method `TryReadLine` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using PrettyConsole; using static PrettyConsole.Color; // Parse integer input if (!Console.TryReadLine(out int port, $"Enter port ({Green}5000{Default}): ")) { port = 5000; // Use default on parse failure } Console.WriteLineInterpolated($"Using port: {Cyan}{port}{Default}"); // Parse with default value Console.TryReadLine(out int count, 10, $"Enter count (default 10): "); Console.WriteLineInterpolated($"Count: {count}"); // Parse enum with case-insensitive matching if (!Console.TryReadLine(out DayOfWeek day, ignoreCase: true, $"Enter day: ")) { day = DayOfWeek.Monday; } Console.WriteLineInterpolated($"Selected: {day}"); // Parse double if (Console.TryReadLine(out double temperature, $"Temperature (°C): ")) { Console.WriteLineInterpolated($"Temperature set to {temperature:F1}°C"); } ``` ### Response #### Success Response (200) Returns `true` if parsing succeeds, `false` otherwise. #### Response Example (No specific response example provided, behavior is indicated by the boolean return value and output to console) ``` -------------------------------- ### Render Formatted Console Table Source: https://context7.com/dusrdev/prettyconsole/llms.txt Use Console.Table to display data in a structured table format with headers and columns. Ensure headers and columns arrays are correctly aligned. ```csharp using PrettyConsole; string[] headers = ["Name", "Status", "CPU", "Memory"]; string[][] columns = [ ["API", "Worker", "Scheduler"], ["Running", "Running", "Stopped"], ["12%", "45%", "0%"], ["256 MB", "512 MB", "0 MB"] ]; Console.Table(headers, columns); // Output: // Name | Status | CPU | Memory // --------------------------------- // API | Running | 12% | 256 MB // Worker | Running | 45% | 512 MB // Scheduler | Stopped | 0% | 0 MB // --------------------------------- ``` -------------------------------- ### Console.Confirm Source: https://context7.com/dusrdev/prettyconsole/llms.txt Prompts for user confirmation with customizable true values. Returns true if the user confirms. ```APIDOC ## Console.Confirm ### Description Prompts for user confirmation with customizable true values. Returns true if the user confirms. ### Method `Confirm` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using PrettyConsole; using static PrettyConsole.Color; // Basic confirmation (default true values: "y", "yes") if (Console.Confirm($"Continue? ({Green}y{Default}/{Red}n{Default}): ")) { Console.WriteLineInterpolated($"{Green}Proceeding...{Default}"); } else { Console.WriteLineInterpolated($"{Yellow}Cancelled.{Default}"); } // Custom true values string[] customTruths = ["sure", "do it", "ok"]; bool proceed = Console.Confirm(customTruths, $"Overwrite files? ", emptyIsTrue: false); // Confirm with emptyIsTrue = true (pressing Enter confirms) if (Console.Confirm($"Deploy to production? [Y/n]: ")) { Console.WriteLineInterpolated($"Deploying..."); } ``` ### Response #### Success Response (200) Returns `true` if the user confirms, `false` otherwise. #### Response Example (No specific response example provided, behavior is indicated by the boolean return value and output to console) ``` -------------------------------- ### Configure Payload Policy for PrettyConsole Expert Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Configure the payload policy to control the copying of the PrettyConsole expert skill into your repository during build. ```xml ``` -------------------------------- ### Apply Color Tokens Source: https://context7.com/dusrdev/prettyconsole/llms.txt Uses guarded ANSI tokens for foreground and background colors with automatic reset capabilities. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Foreground colors Console.WriteLineInterpolated($"{Red}Error{Default} | {Yellow}Warning{Default} | {Green}Success{Default}"); // Background colors Console.WriteLineInterpolated($"{WhiteBackground}{Black}Highlighted text{Default}"); // Combined foreground and background Console.WriteLineInterpolated($"{CyanBackground}{White}Status Bar{Default}"); // Available foreground tokens: Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, // DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White // Background tokens: BlackBackground, DarkBlueBackground, etc. // Reset tokens: Default (both), DefaultForeground, DefaultBackground ``` -------------------------------- ### Display Animated Console Spinner Source: https://context7.com/dusrdev/prettyconsole/llms.txt Use the Spinner class to show an animated indicator for indeterminate tasks. The RunAsync method can take a task and a status message or a builder function for dynamic status updates. Use ClearNextLines to remove spinner output. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Basic spinner with static header var spinner = new Spinner(); var result = await spinner.RunAsync( SomeLongRunningTask(), "Processing data..." ); Console.ClearNextLines(1, OutputPipe.Error); Console.WriteLineInterpolated($"{Green}Done!{Default}"); // Spinner with dynamic header using factory var step = 0; string[] steps = ["Connecting", "Authenticating", "Syncing", "Finalizing"]; var workTask = Task.Run(async () => { for (int i = 0; i < steps.Length; i++) { Interlocked.Exchange(ref step, i); await Task.Delay(800); } }); var animatedSpinner = new Spinner { Pattern = Spinner.Patterns.Braille, ForegroundColor = Cyan, DisplayElapsedTime = true }; await animatedSpinner.RunAsync(workTask, (builder, out handler) => { var currentStep = Volatile.Read(ref step); handler = builder.Build(OutputPipe.Error, $"Step {currentStep + 1}/4: {steps[currentStep]}"); }); Console.ClearNextLines(1, OutputPipe.Error); // Available patterns: Twirl, Braille, RunningPerson, SadSmiley, LoadingBar, PingPong ``` -------------------------------- ### RequestAnyInput Source: https://github.com/dusrdev/prettyconsole/wiki/2.-Basic-Inputs Waits for the user to press Enter, similar to `Console.ReadKey()`, with an optional custom message. ```APIDOC ## RequestAnyInput ### Description Displays a message and waits for the user to press Enter to continue. ### Method `RequestAnyInput(string message = "Press any key to continue")` `RequestAnyInput(ColoredOutput output)` ### Parameters #### Query Parameters - **message** (string) - Optional - The message to display to the user. - **output** (ColoredOutput) - Optional - The colored output to display as the prompt message. #### Request Body None ### Response #### Success Response (200) Void (operation completes when Enter is pressed). ### Request Example ```csharp RequestAnyInput("Processing complete. Press Enter to exit."); ``` ``` -------------------------------- ### Console Rendering Helpers Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Manipulate the console cursor and colors using `ClearNextLines`, `GetCurrentLine`, `GoToLine`, `SetColors`, `ResetColors`, and `SkipLines`. `SkipLines` is useful for maintaining visibility of UI elements like progress bars. ```csharp Console.ClearNextLines(3, OutputPipe.Error); int line = Console.GetCurrentLine(); // … draw something … Console.GoToLine(line); Console.SetColors(ConsoleColor.White, ConsoleColor.DarkBlue); Console.ResetColors(); Console.SkipLines(2); // keep multi-line UIs (progress bars, dashboards) and continue writing below them ``` ```csharp Console.WriteWhiteSpaces(8, OutputPipe.Error); // pad status blocks ConsoleContext.Error.WriteWhiteSpaces(4); // same via writer ``` -------------------------------- ### Set Payload Root Directory for .NET 10 Apps Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md For .NET 10 file-based apps, explicitly set the PayloadRootDirectory if repo-root detection is unavailable. ```csharp #:property PayloadRootDirectory=. ``` -------------------------------- ### Parse Input with Default Value using TryReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads integer input, automatically applying a default value if the user provides no input or invalid input. Suitable for settings where a fallback is acceptable. ```csharp // Parse with default value Console.TryReadLine(out int count, 10, "Enter count (default 10): "); Console.WriteLineInterpolated($"Count: {count}"); ``` -------------------------------- ### Display Hierarchical Console Menu Source: https://context7.com/dusrdev/prettyconsole/llms.txt Use Console.TreeMenu to display a nested menu from a dictionary. It returns the selected main option and sub-option. Handle ArgumentException for invalid selections. ```csharp using PrettyConsole; using static PrettyConsole.Color; var menu = new Dictionary> { ["Users"] = new[] { "List", "Create", "Delete", "Disable" }, ["Jobs"] = new[] { "Queue", "Retry", "Cancel" }, ["Settings"] = new[] { "View", "Edit", "Reset" } }; try { var (area, action) = Console.TreeMenu(menu, $"{Cyan}Admin Actions:{Default}"); // Output: // Admin Actions: // 1) Users 1) List // 2) Create // 3) Delete // 4) Disable // // 2) Jobs 1) Queue // 2) Retry // 3) Cancel // ... // Enter your main choice and sub choice separated with space: 1 2 Console.WriteLineInterpolated($"Executing: {Green}{area}{Default} -> {Cyan}{action}{Default}"); } catch (ArgumentException) { Console.WriteLineInterpolated($"{Red}Invalid selection.{Default}"); } ``` -------------------------------- ### Create typewriter effects with Console.TypeWrite Source: https://context7.com/dusrdev/prettyconsole/llms.txt Outputs text character by character with a configurable delay. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Typewriter effect with colors await Console.TypeWrite("Initializing systems", (Green, BlackBackground), delay: 50); Console.NewLine(); // TypeWriteLine includes the newline await Console.TypeWriteLine("Boot sequence complete.", (Cyan, DefaultBackground), delay: 30); // Dramatic effect await Console.TypeWrite("ACCESS GRANTED", (Green, BlackBackground), delay: 100); Console.NewLine(); ``` -------------------------------- ### Advanced Console Outputs with Overwrite and Typewriting Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Use `Console.Overwrite` to replace a specified number of lines with new content, ideal for dynamic status updates. `Console.TypeWrite` and `Console.TypeWriteLine` simulate typing effects for a more engaging user experience. ```csharp Console.Overwrite(() => { Console.WriteLineInterpolated(OutputPipe.Error, $"{Cyan}Working…{Default}"); Console.WriteInterpolated(OutputPipe.Error, $"{DarkGray}Elapsed:{Default} {stopwatch.Elapsed:duration}"); // Elapsed: 0h 1m 12s }, lines: 2); ``` ```csharp // Prevent closure allocations with state + generic overload Console.Overwrite((left, right), tuple => { Console.WriteInterpolated($"{tuple.left} ←→ {tuple.right}"); }, lines: 1); ``` ```csharp await Console.TypeWrite("Booting systems…", (Color.Green, Color.BlackBackground)); await Console.TypeWriteLine("Ready.", (Color.DefaultForeground, Color.DefaultBackground)); ``` -------------------------------- ### Pause Execution with RequestAnyInput Source: https://context7.com/dusrdev/prettyconsole/llms.txt Halts program execution until the user presses any key. Displays a customizable prompt message. Useful for allowing users to review output before continuing or exiting. ```csharp using PrettyConsole; using static PrettyConsole.Color; Console.WriteLineInterpolated($"Installation complete!"); Console.RequestAnyInput($"Press {Yellow}any key{Default} to exit..."); ``` ```csharp // Use in menus Console.WriteLineInterpolated($"{Red}Error:{Default} Connection failed."); Console.RequestAnyInput("Press any key to retry..."); ``` -------------------------------- ### Console.ReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads user input with optional type parsing. Returns the parsed value or a default. ```APIDOC ## Console.ReadLine ### Description Reads user input with optional type parsing. Returns the parsed value or a default. ### Method `ReadLine` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using PrettyConsole; using static PrettyConsole.Color; // Read string input (never returns null) string name = Console.ReadLine($"Enter your name: "); Console.WriteLineInterpolated($"Hello, {Green}{name}{Default}!"); // Read with typed default int age = Console.ReadLine(18, $"Enter age (default 18): "); Console.WriteLineInterpolated($"Age: {age}"); // Read nullable type int? optionalValue = Console.ReadLine($"Optional number: "); if (optionalValue.HasValue) { Console.WriteLineInterpolated($"You entered: {optionalValue.Value}"); } ``` ### Response #### Success Response (200) Returns the parsed input or a default value. #### Response Example (No specific response example provided, behavior is indicated by the return value and output to console) ``` -------------------------------- ### Write Styled Lines with Interpolation Source: https://context7.com/dusrdev/prettyconsole/llms.txt Writes styled content followed by a line terminator, supporting custom format specifiers like :duration and :bytes. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Basic line output with colors Console.WriteLineInterpolated($"Processing {Cyan}42{Default} items..."); // Combine multiple colors in one line Console.WriteLineInterpolated($"{Green}[SUCCESS]{Default} Build completed in {Magenta}2.5s{Default}"); // Use TimeSpan :duration format var elapsed = TimeSpan.FromHours(5) + TimeSpan.FromMinutes(32) + TimeSpan.FromSeconds(12); Console.WriteLineInterpolated($"Elapsed: {elapsed:duration}"); // Output: Elapsed: 5h 32m 12s // Use double :bytes format for file sizes double fileSize = 12_884_901d; Console.WriteLineInterpolated($"Downloaded: {fileSize:bytes}"); // Output: Downloaded: 12.3 MB ``` -------------------------------- ### Read Integer Input with Typed Default using ReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads an integer value from the user, providing a specified default if no input is given or if the input is invalid. This simplifies handling optional numerical inputs. ```csharp // Read with typed default int age = Console.ReadLine(18, "Enter age (default 18): "); Console.WriteLineInterpolated($"Age: {age}"); ``` -------------------------------- ### Access console streams via ConsoleContext Source: https://context7.com/dusrdev/prettyconsole/llms.txt Provides access to underlying console streams, useful for testing or redirecting output. ```csharp using PrettyConsole; // Access streams directly TextWriter stdout = ConsoleContext.Out; TextWriter stderr = ConsoleContext.Error; TextReader stdin = ConsoleContext.In; // Write directly to streams ConsoleContext.Out.WriteLine("Direct output"); ConsoleContext.Error.WriteWhiteSpaces(20); // Mock streams for testing var mockOutput = new StringWriter(); ConsoleContext.Out = mockOutput; Console.WriteLineInterpolated($"Test output"); string captured = mockOutput.ToString(); // Restore original ConsoleContext.Out = Console.Out; ``` -------------------------------- ### Confirm Source: https://github.com/dusrdev/prettyconsole/wiki/2.-Basic-Inputs Prompts the user for a boolean confirmation, accepting custom true values and handling case-insensitivity. ```APIDOC ## Confirm ### Description Prompts the user for a yes/no confirmation. It handles custom values for 'true' and ignores case. ### Method `Confirm(ColoredOutput message)` `Confirm(ColoredOutput message, ReadOnlySpan trueValues, bool emptyIsTrue = true)` ### Parameters #### Query Parameters - **message** (ColoredOutput) - Required - The confirmation message to display. - **trueValues** (ReadOnlySpan) - Optional - A collection of strings that will be considered as 'true'. Defaults to `["y", "yes"]`. - **emptyIsTrue** (bool) - Optional - Determines if an empty input (pressing Enter) should be considered true. Defaults to `true`. #### Request Body None ### Response #### Success Response (200) - **bool** - `true` if the user confirmed, `false` otherwise. ### Request Example ```csharp if (Confirm("Do you want to save the changes?")) { // Save changes } if (Confirm("Proceed with deletion?", new string[] {"yes", "y", "ok"}, false)) { // Proceed with deletion } ``` ### Response Example ```json { "confirmation": true } ``` ``` -------------------------------- ### Read String Input with ReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads a line of text input from the user. This method guarantees a non-null string, returning an empty string if the user presses Enter without typing. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Read string input (never returns null) string name = Console.ReadLine($"Enter your name: "); Console.WriteLineInterpolated($"Hello, {Green}{name}{Default}!"); ``` -------------------------------- ### Use WhiteSpace struct for padding Source: https://context7.com/dusrdev/prettyconsole/llms.txt Enables zero-allocation whitespace padding directly within interpolated strings. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Inline padding in interpolated strings Console.WriteLineInterpolated($"Name:{new WhiteSpace(10)}Value"); // Output: Name: Value // Use for columnar alignment Console.WriteLineInterpolated($"| {"Status",-10} | {new WhiteSpace(5)}{Green}OK{Default} |"); // Combine with alignment specifiers string label = "Total"; int value = 42; Console.WriteLineInterpolated($"{label,-15}{new WhiteSpace(3)}{Cyan}{value,8}{Default}"); ``` -------------------------------- ### Parse Enum Input with Case-Insensitive Matching using TryReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads enum input from the console, allowing for case-insensitive matching. Provides a fallback to a default enum value if parsing fails. Ideal for user selections from a predefined set of options. ```csharp // Parse enum with case-insensitive matching if (!Console.TryReadLine(out DayOfWeek day, ignoreCase: true, "Enter day: ")) { day = DayOfWeek.Monday; } Console.WriteLineInterpolated($"Selected: {day}"); ``` -------------------------------- ### Define custom ANSI tokens Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Wrap custom ANSI escape sequences in an AnsiToken to ensure safe handling by the library. ```csharp var rose = new AnsiToken("\u001b[38;5;213m"); // custom 256-color escape Console.WriteInterpolated($"{rose}accent text{Color.Default}"); ``` -------------------------------- ### Write Styled Interpolated Content Source: https://context7.com/dusrdev/prettyconsole/llms.txt Writes styled text to the console using zero-allocation handlers. Returns the number of visible characters written for layout calculations. ```csharp using PrettyConsole; using static PrettyConsole.Color; // Basic styled output Console.WriteInterpolated($"Hello {Green}world{Default}!"); // Output: Hello world! (with "world" in green) // Write to error pipe with styling string message = "disk space low"; Console.WriteInterpolated(OutputPipe.Error, $"{Yellow}warning{Default}: {message}"); // Output: warning: disk space low (with "warning" in yellow) // Use the return value for alignment calculations int written = Console.WriteInterpolated($"Status: {Cyan}OK{Default}"); Console.WriteWhiteSpaces(20 - written); // Pad to 20 characters Console.WriteInterpolated($"| Next column"); ``` -------------------------------- ### Format TimeSpan and byte values Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Use custom format specifiers :duration for time spans and :bytes for human-friendly binary sizes. ```csharp var elapsed = stopwatch.Elapsed; Console.WriteInterpolated($"Completed in {elapsed:duration}"); // Completed in 12h 5m 33s ``` ```csharp var transferred = 12_884_901d; Console.WriteInterpolated($"Uploaded {transferred:bytes}"); // Uploaded 12.3 MB Console.WriteInterpolated($"Remaining {remaining,8:bytes}"); // right-aligned units stay tidy ``` -------------------------------- ### Parse Double Input with TryReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads a double-precision floating-point number from user input. Useful for measurements or values requiring decimal precision. ```csharp // Parse double if (Console.TryReadLine(out double temperature, "Temperature (°C): ")) { Console.WriteLineInterpolated($"Temperature set to {temperature:F1}°C"); } ``` -------------------------------- ### Access console streams via ConsoleContext Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Provides access to the underlying TextWriter and TextReader instances for direct manipulation or testing. ```csharp TextWriter @out = ConsoleContext.Out; TextWriter @err = ConsoleContext.Error; TextReader @in = ConsoleContext.In; ``` -------------------------------- ### Write styled text with interpolated strings Source: https://github.com/dusrdev/prettyconsole/blob/stable/README.md Use WriteInterpolated for styled output. Colors reset automatically, and the method returns the number of visible characters written. ```csharp Console.WriteInterpolated($"Hello {Green}world{Default}!"); Console.WriteInterpolated(OutputPipe.Error, $"{Yellow}warning{Default}: {message}"); if (!Console.TryReadLine(out int choice, $"Pick option {Cyan}1-5{Default}: ")) { Console.WriteLineInterpolated($"{Red}Not a number.{Default}"); } // Zero-allocation padding directly from the handler Console.WriteInterpolated($"Header{new WhiteSpace(6)}Value"); ``` -------------------------------- ### Read Nullable Type Input with ReadLine Source: https://context7.com/dusrdev/prettyconsole/llms.txt Reads input from the user and attempts to parse it into a nullable type. Returns null if the user provides no input or invalid input for the specified type. ```csharp // Read nullable type int? optionalValue = Console.ReadLine("Optional number: "); if (optionalValue.HasValue) { Console.WriteLineInterpolated($"You entered: {optionalValue.Value}"); } ```