### Spectre.Console Quick Start Example Source: https://spectreconsole.net/console A basic example demonstrating styled text with markup, a simple table, and a status spinner. Ensure you have the necessary using statements for Spectre.Console and System.Threading. ```csharp // Styled text with markup AnsiConsole.MarkupLine("[bold blue]Welcome[/] to [green]Spectre.Console[/]!"); // A simple table var table = new Table() .AddColumn("Feature") .AddColumn("Description") .AddRow("[green]Markup[/]", "Rich text with colors and styles") .AddRow("[blue]Tables[/]", "Structured data display") .AddRow("[yellow]Progress[/]", "Spinners and progress bars"); AnsiConsole.Write(table); // Status spinner for work AnsiConsole.Status() .Start("Processing...", ctx => { Thread.Sleep(2500); }); AnsiConsole.MarkupLine("[green]Done![/]"); ``` -------------------------------- ### TreeGuide.Ascii Example Source: https://spectreconsole.net/console/reference/tree-guide-reference Renders a tree structure using the Ascii tree guide. This guide uses basic ASCII characters. ```text Root |-- Child 1 | |-- Grandchild 1.1 | `-- Grandchild 1.2 `-- Child 2 |-- Grandchild 2.1 `-- Grandchild 2.2 ``` -------------------------------- ### TreeGuide.Line Example Source: https://spectreconsole.net/console/reference/tree-guide-reference Renders a tree structure using the Line tree guide. This guide uses single-line Unicode box-drawing characters. ```text Root ├── Child 1 │ ├── Grandchild 1.1 │ └── Grandchild 1.2 └── Child 2 ├── Grandchild 2.1 └── Grandchild 2.2 ``` -------------------------------- ### Create and Render a Tree with Line Guide Source: https://spectreconsole.net/console/reference/tree-guide-reference Demonstrates how to create a tree structure and render it using the default Line guide. Ensure your terminal supports Unicode for certain tree guides. ```csharp var tree = new Tree("Root"); tree.Guide(TreeGuide.Line); var node1 = tree.AddNode("Child 1"); node1.AddNode("Grandchild 1.1"); node1.AddNode("Grandchild 1.2"); tree.AddNode("Child 2"); AnsiConsole.Write(tree); ``` -------------------------------- ### Explain Command Examples Source: https://spectreconsole.net/cli/reference/built-in-command-behaviors Provides examples of using the explain command with different options to control the output. Use --detailed for parameter information and --hidden to include hidden commands. ```bash myapp cli explain # Show all commands myapp cli explain add # Show specific command myapp cli explain --detailed # Show parameter details myapp cli explain --hidden # Include hidden items ``` -------------------------------- ### TreeGuide.DoubleLine Example Source: https://spectreconsole.net/console/reference/tree-guide-reference Renders a tree structure using the DoubleLine tree guide. This guide uses double-line Unicode box-drawing characters. ```text Root ╠══ Child 1 ║ ╠══ Grandchild 1.1 ║ ╚══ Grandchild 1.2 ╚══ Child 2 ╠══ Grandchild 2.1 ╚══ Grandchild 2.2 ``` -------------------------------- ### Combining Widgets Example Source: https://spectreconsole.net/console/live/live-display Example demonstrating how to combine multiple widgets into layouts for a sophisticated dashboard. ```APIDOC ## Combining Widgets Create sophisticated dashboards by combining multiple widgets in layouts. ```csharp // Create status table var statusTable = new Table() .Border(TableBorder.Rounded) .BorderColor(Color.Cyan) .AddColumn("Service") .AddColumn("Status") .AddColumn("Requests/sec"); // Create metrics table var metricsTable = new Table() .Border(TableBorder.Rounded) .BorderColor(Color.Yellow) .AddColumn("Metric") .AddColumn("Current") .AddColumn("Average"); // Create layout with both tables var layout = new Layout("Root") .SplitRows( new Layout("Header"), new Layout("Body").SplitColumns( new Layout("Status"), new Layout("Metrics") ) ); layout["Header"].Update( new Panel("[bold cyan]Real-Time Dashboard[/]") .BorderColor(Color.Blue) .Padding(1, 0) ); layout["Status"].Update(new Panel(statusTable).Header("Services")); layout["Metrics"].Update(new Panel(metricsTable).Header("System Metrics")); AnsiConsole.Live(layout) .Start(ctx => { for (int i = 0; i < 15; i++) { // Update status table statusTable.Rows.Clear(); statusTable.AddRow("API Gateway", "[green]Healthy[/]", $"{Random.Shared.Next(100, 500)}"); statusTable.AddRow("Auth Service", "[green]Healthy[/]", $"{Random.Shared.Next(50, 200)}"); statusTable.AddRow("Database", i > 10 ? "[yellow]Degraded[/]" : "[green]Healthy[/]", $"{Random.Shared.Next(200, 800)}"); statusTable.AddRow("Cache", "[green]Healthy[/]", $"{Random.Shared.Next(1000, 3000)}"); // Update metrics table metricsTable.Rows.Clear(); metricsTable.AddRow("CPU", $"{Random.Shared.Next(20, 75)}%", "45%"); metricsTable.AddRow("Memory", $"{Random.Shared.Next(4, 12)} GB", "8 GB"); metricsTable.AddRow("Disk I/O", $"{Random.Shared.Next(10, 90)} MB/s", "45 MB/s"); metricsTable.AddRow("Network", $"{Random.Shared.Next(100, 500)} MB/s", "250 MB/s"); ctx.Refresh(); Thread.Sleep(1000); } }); ``` ``` -------------------------------- ### TreeGuide.BoldLine Example Source: https://spectreconsole.net/console/reference/tree-guide-reference Renders a tree structure using the BoldLine tree guide. This guide uses bold Unicode box-drawing characters. ```text Root ┣━━ Child 1 ┃ ┣━━ Grandchild 1.1 ┃ ┗━━ Grandchild 1.2 ┗━━ Child 2 ┣━━ Grandchild 2.1 ┗━━ Grandchild 2.2 ``` -------------------------------- ### Configure CommandApp Entry Point Source: https://spectreconsole.net/cli/tutorials/dependency-injection-in-cli-apps Sets up the main entry point for the CLI application, configuring it to use the `GreetCommand`. This is the minimal setup to run the command. ```csharp using Spectre.Console.Cli; var app = new CommandApp(); return app.Run(args); ``` -------------------------------- ### Start Tasks Programmatically with Spectre.Console Progress Source: https://spectreconsole.net/console/tutorials/progress-bars-tutorial This snippet demonstrates how to start tasks programmatically within a progress bar. It shows how to set custom styles for completed, finished, and remaining portions of the bar, and how to control the start of a task based on the progress of another. Use this when you need to manage task dependencies or delay the start of certain operations. ```csharp AnsiConsole.Progress() .Columns( new SpinnerColumn(), new TaskDescriptionColumn(), new ProgressBarColumn { CompletedStyle = new Style(Color.Green), FinishedStyle = new Style(Color.Lime), RemainingStyle = new Style(Color.Grey) }, new PercentageColumn(), new ElapsedTimeColumn()) .Start(ctx => { var worldMap = ctx.AddTask("Loading World Map", maxValue: 200); var character = ctx.AddTask("Loading Character Data"); var sounds = ctx.AddTask("Loading Sound Effects", maxValue: 50); // Textures won't start until we call StartTask() var textures = ctx.AddTask("Loading Textures", autoStart: false); var random = new Random(42); while (!ctx.IsFinished) { worldMap.Increment(random.NextDouble() * 3); character.Increment(random.NextDouble() * 1.5); sounds.Increment(random.NextDouble() * 1.5); // Start textures once world map reaches 25% if (worldMap.Percentage >= 25 &&! textures.IsStarted) { textures.StartTask(); } if (textures.IsStarted) { textures.Increment(random.NextDouble() * 2); } Thread.Sleep(50); } }); AnsiConsole.MarkupLine("[lime]All assets loaded![/]"); ``` -------------------------------- ### Example Command Line Usage Source: https://spectreconsole.net/cli/how-to/using-custom-type-converters Demonstrates how users can provide complex types like points on the command line using the defined options and custom converters. ```bash myapp --point 10,20 --color red myapp --point 100,200 --offset 5,5 ``` -------------------------------- ### Wire Up CommandApp in Program.cs Source: https://spectreconsole.net/cli Configures and runs a Spectre.Console.Cli command application. This example sets GreetCommand as the root command. ```csharp var app = new CommandApp(); return app.Run(args); ``` -------------------------------- ### Set Application Name and Add Usage Examples Source: https://spectreconsole.net/cli/how-to/customizing-help-text-and-usage Customize the application name and add common invocation patterns to the help text. This overrides the default executable name and provides clear examples for users. ```csharp var app = new CommandApp(); app.Configure(config => { // Set application name (overrides default exe/dll name) config.SetApplicationName("myapp"); // Set version shown in --version output config.SetApplicationVersion("1.2.0"); // Add examples shown in top-level help config.AddExample("production"); config.AddExample("staging", "--force"); config.AddExample("dev", "--dry-run", "--verbose"); }); return await app.RunAsync(args); ``` -------------------------------- ### Basic Grid Usage Source: https://spectreconsole.net/console/widgets/grid Demonstrates the fundamental setup of a Grid by adding columns and then populating rows with content. Ensure each row has the same number of cells as there are columns. ```csharp var grid = new Grid(); // Add columns grid.AddColumn(); grid.AddColumn(); // Add rows grid.AddRow("Name:", "[blue]John Doe[/]"); grid.AddRow("Email:", "[blue]john.doe@example.com[/]"); grid.AddRow("Phone:", "[blue]+1 (555) 123-4567[/]"); AnsiConsole.Write(grid); ``` -------------------------------- ### Register Commands with Metadata Source: https://spectreconsole.net/cli/how-to/configuring-commandapp-and-commands Register commands with descriptions, aliases, and examples using CommandApp.Configure. Includes conditional debug settings for exception propagation and example validation. ```csharp var app = new CommandApp(); app.Configure(config => { // Set application identity for help output config.SetApplicationName("myapp"); config.SetApplicationVersion("1.0.0"); // Add commands with descriptions, aliases, and examples config.AddCommand("add") .WithDescription("Add a new item") .WithAlias("a") .WithExample("add", "todo.txt") .WithExample("add", "notes.md", "--force"); config.AddCommand("remove") .WithDescription("Remove an item") .WithAlias("rm") .WithAlias("delete") .WithExample("remove", "old-file.txt"); config.AddCommand("list") .WithDescription("List all items") .WithAlias("ls"); #if DEBUG // Development-only settings config.PropagateExceptions(); config.ValidateExamples(); #endif }); return await app.RunAsync(args); ``` -------------------------------- ### Three-Column Layout Example Source: https://spectreconsole.net/console/widgets/layout Illustrates creating a standard application layout with navigation, main content, and sidebar regions. ```APIDOC ## Three-Column Layout Create a classic application layout with navigation, main content, and sidebar regions containing different widget types. ### Method ```csharp // Example usage of Layout for a three-column structure var layout = new Layout("Root") .SplitColumns( new Layout("Navigation").Size(18), new Layout("Main"), new Layout("Sidebar").Size(22)); layout["Navigation"].Update( new Panel(new Markup( "[blue]Menu[/]\n" + "├─ Dashboard\n" + "├─ Reports\n" + "└─ Settings")) .BorderColor(Color.Blue)); var table = new Table() .BorderColor(Color.Green) .AddColumn("Item") .AddColumn("Value") .AddRow("Orders", "1,234") .AddRow("Revenue", "$45,678"); layout["Main"].Update( new Panel(table) .Header("Statistics") .BorderColor(Color.Green)); layout["Sidebar"].Update( new Panel("[yellow]Quick Actions[/]\n• New Report\n• Export Data\n• Refresh") .BorderColor(Color.Yellow)); AnsiConsole.Write(layout); ``` ``` -------------------------------- ### Add Logging Packages Source: https://spectreconsole.net/cli/tutorials/logging-in-cli-apps Installs the necessary Microsoft.Extensions.Logging packages for structured logging. ```bash dotnet add package Microsoft.Extensions.Logging dotnet add package Microsoft.Extensions.Logging.Console dotnet add package Microsoft.Extensions.DependencyInjection ``` -------------------------------- ### Using Line Tree Guide (Default) Source: https://spectreconsole.net/console/widgets/tree Sets the tree to use the default Unicode line drawing characters for its guide lines, suitable for most modern terminals. ```csharp var tree = new Tree("Root") .Guide(TreeGuide.Line); var child1 = tree.AddNode("Child 1"); child1.AddNode("Grandchild 1.1"); child1.AddNode("Grandchild 1.2"); var child2 = tree.AddNode("Child 2"); child2.AddNode("Grandchild 2.1"); AnsiConsole.Write(tree); ``` -------------------------------- ### Example Usage: Title Screens Source: https://spectreconsole.net/console/widgets/align Demonstrates how to use the Align class to center application splash screens or welcome messages. ```APIDOC ## Title Screens Example ### Description Use centered alignment for application splash screens or welcome messages. ### Code ```csharp var title = new FigletText("Spectre") .Color(Color.Blue); var subtitle = new Markup("[italic grey]A modern .NET console library[/]"); var titleAligned = Align.Center(title); var subtitleAligned = Align.Center(subtitle); AnsiConsole.Write(titleAligned); AnsiConsole.Write(subtitleAligned); AnsiConsole.WriteLine(); var instructions = new Markup("[dim]Press any key to continue...[/]"); AnsiConsole.Write(Align.Center(instructions)); ``` ``` -------------------------------- ### LiveDisplay Methods Source: https://spectreconsole.net/console/live/live-display Methods for starting and managing the live display. ```APIDOC ### Methods `Start(Action action)` Starts the live display. ### Parameters - **action** (Action) - The action to execute. `T Start(Func func)` ### Parameters - **func** (Func) `Task StartAsync(Func func)` Starts the live display. ### Parameters - **func** (Func) - The action to execute. ### Returns - The result. `Task StartAsync(Func> func)` ### Parameters - **func** (Func>) ``` -------------------------------- ### Dynamic Visibility Example Source: https://spectreconsole.net/console/widgets/layout Shows how to control the visibility of layout sections at runtime. ```APIDOC ## Dynamic Visibility Control section visibility at runtime to show or hide regions based on application state. ### Method ```csharp // Example of controlling layout visibility var layout = new Layout("Root") .SplitColumns( new Layout("Left"), new Layout("Middle"), new Layout("Right")); layout["Left"].Update(new Panel("Always visible").BorderColor(Color.Green)); layout["Middle"].Update(new Panel("Hidden section").BorderColor(Color.Red)); layout["Right"].Update(new Panel("Also visible").BorderColor(Color.Blue)); // Hide the middle section layout["Middle"].IsVisible = false; AnsiConsole.Write(layout); ``` ``` -------------------------------- ### Dashboard Layout Example Source: https://spectreconsole.net/console/widgets/layout Demonstrates how to create a dashboard layout with headers, footers, and split content areas using rows and columns. ```APIDOC ## Dashboard Layout Combine multiple layout techniques to create a complete dashboard with headers, sidebars, content areas, and status bars. ### Method ```csharp // Example usage of Layout for dashboard var layout = new Layout("Root") .SplitRows( new Layout("Header").Size(3), new Layout("Main"), new Layout("Footer").Size(3)); layout["Header"].Update( new Panel("[bold yellow]System Dashboard[/]") .BorderColor(Color.Yellow)); layout["Main"].SplitColumns( new Layout("Left").Ratio(1), new Layout("Right").Ratio(2)); layout["Left"].SplitRows( new Layout("Metrics"), new Layout("Logs")); layout["Metrics"].Update( new Panel("[green]CPU: 45%\nRAM: 62%\nDisk: 78%[/]") .Header("System Metrics") .BorderColor(Color.Green)); layout["Logs"].Update( new Panel("[dim]12:03 Process started\n12:05 Connected\n12:07 Ready[/]") .Header("Recent Logs") .BorderColor(Color.Blue)); layout["Right"].Update( new Panel("[white]Main application content area\nDisplays real-time data and visualizations[/]") .Header("Content") .BorderColor(Color.Cyan1)); layout["Footer"].Update( new Panel("[dim]Connected | Uptime: 2h 34m | Last Update: 12:07:45[/]") .BorderColor(Color.Grey)); AnsiConsole.Write(layout); ``` ``` -------------------------------- ### Development Settings Source: https://spectreconsole.net/cli/how-to/configuring-commandapp-and-commands Enable development-specific settings like propagating exceptions for full stack traces and validating examples at startup. ```csharp #if DEBUG config.PropagateExceptions(); // Get full stack traces config.ValidateExamples(); // Verify all WithExample calls are valid #endif ``` -------------------------------- ### Greet Command Implementation Source: https://spectreconsole.net/cli/tutorials/dependency-injection-in-cli-apps The main command class that uses the IGreetingFactory to get a greeting service and display the greeting. It depends on IGreetingFactory and IAnsiConsole. ```csharp public class GreetCommand : Command { private readonly IGreetingFactory _greetingFactory; private readonly IAnsiConsole _console; public GreetCommand(IGreetingFactory greetingFactory, IAnsiConsole console) { _greetingFactory = greetingFactory; _console = console; } public class Settings : CommandSettings { [CommandArgument(0, "")] [Description("The name to greet")] public string Name { get; init; } = string.Empty; [CommandOption("-s|--style")] [Description("The greeting style to use (Casual, Formal, or Enthusiastic)")] [DefaultValue(GreetingStyle.Casual)] public GreetingStyle Style { get; init; } } protected override int Execute(CommandContext context, Settings settings, CancellationToken cancellation) { var service = _greetingFactory.Create(); var greeting = service.GetGreeting(settings.Name); _console.WriteLine(greeting); return 0; } } ``` -------------------------------- ### Run Add and List Commands Source: https://spectreconsole.net/cli/tutorials/building-a-multi-command-cli-tool Demonstrates how to execute the 'add' and 'list' commands from the .NET CLI. ```bash dotnet run -- add Newtonsoft.Json # Added package Newtonsoft.Json dotnet run -- list # Packages: # (none yet) ``` -------------------------------- ### Runtime Log Level Examples Source: https://spectreconsole.net/cli/tutorials/logging-in-cli-apps Demonstrates how to run the CLI application with different log levels specified via the --logLevel option. Observe the output changes based on the selected verbosity. ```bash dotnet run -- myfile.txt # info: Processing step 1... dotnet run -- myfile.txt --logLevel Debug # dbug: Detailed step 1 information # info: Processing step 1... dotnet run -- myfile.txt --logLevel Warning # warn: This is a warning message ``` -------------------------------- ### Tree Extension Methods Source: https://spectreconsole.net/console/widgets/tree Offers extension methods for Tree widgets, including getting segments, setting guide lines, and applying styles. ```APIDOC ## Tree Extension Methods ### `IEnumerable GetSegments(IAnsiConsole console)` Gets the segments for a renderable using the specified console. **Parameters:** * `console` (IAnsiConsole) - The console. **Returns:** An enumerable containing segments representing the specified . ### `Tree Guide(TreeGuide guide)` Sets the tree guide line appearance. **Parameters:** * `guide` (TreeGuide) - The tree guide lines to use. **Returns:** The same instance so that multiple calls can be chained. ### `Tree Style(Nullable