### Custom Command Creator Example (StructureMap) Source: https://jasperfx.github.io/oakton/guide/bootstrapping.html An example of a custom `ICommandCreator` using StructureMap. ```csharp public class StructureMapCommandCreator : ICommandCreator { private readonly IContainer _container; public StructureMapCommandCreator(IContainer container) { _container = container; } public IOaktonCommand CreateCommand(Type commandType) { return (IOaktonCommand)_container.GetInstance(commandType); } public object CreateModel(Type modelType) { return _container.GetInstance(modelType); } } ``` -------------------------------- ### Program.cs - IHostBuilder Example Source: https://jasperfx.github.io/oakton/guide/host/ioc.html Example of setting up an IHostBuilder and running Oakton commands. ```csharp public class Program { public static Task Main(string[] args) { return CreateHostBuilder(args) .RunOaktonCommands(args); } public static IHostBuilder CreateHostBuilder(string[] args) => // This is a little old-fashioned, but still valid .NET core code: Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService(); }); } ``` -------------------------------- ### Multiple Commands Example Source: https://jasperfx.github.io/oakton/guide/getting_started.html Defines the CheckoutCommand and CleanCommand classes, demonstrating how to create multiple commands within a single tool. ```csharp [Description("Switch branches or restore working tree files")] public class CheckoutCommand : OaktonAsyncCommand { public override async Task Execute(CheckoutInput input) { await Task.CompletedTask; return true; } } [Description("Remove untracked files from the working tree")] public class CleanCommand : OaktonCommand { public override bool Execute(CleanInput input) { return true; } } ``` -------------------------------- ### Key/Value Flags Command Line Example Source: https://jasperfx.github.io/oakton/guide/parsing.html Example of using key/value flags with a dictionary. ```bash executable command --prop:color Red --prop:direction North ``` -------------------------------- ### Git Checkout Command Line Examples Source: https://jasperfx.github.io/oakton/guide/parsing.html Examples of using the git checkout command with different flag syntaxes for creating branches. ```bash git checkout -b working ``` ```bash git checkout --create-branch working ``` -------------------------------- ### Command Executor Setup Source: https://jasperfx.github.io/oakton/guide/getting_started.html Sets up the CommandExecutor in Program.Main() to discover and register all command classes within the application's assembly. ```csharp static int Main(string[] args) { var executor = CommandExecutor.For(_ => { // Find and apply all command classes discovered // in this assembly _.RegisterCommands(typeof(Program).GetTypeInfo().Assembly); }); return executor.Execute(args); } ``` -------------------------------- ### Use Resource Setup on Startup in Development Source: https://jasperfx.github.io/oakton/guide/host/resources.html This snippet shows how to enable resource setup on startup only when the system is running in development mode. ```csharp using var host = await Host.CreateDefaultBuilder() .ConfigureServices(services => { // More service registrations like this is a real app! }) .UseResourceSetupOnStartupInDevelopment() .StartAsync(); ``` -------------------------------- ### Git Clean Command Line Examples Source: https://jasperfx.github.io/oakton/guide/parsing.html Examples of using the git clean command with various boolean flag combinations. ```bash git clean -x -d --force ``` ```bash git clean -x -d --f ``` ```bash git clean -xfd ``` -------------------------------- ### Use Resource Setup on Startup (Alternative Syntax) Source: https://jasperfx.github.io/oakton/guide/host/resources.html An alternative syntax to achieve the same functionality of setting up resources on startup using UseResourceSetupOnStartup(). ```csharp using var host = await Host.CreateDefaultBuilder() .ConfigureServices(services => { // More service registrations like this is a real app! }) .UseResourceSetupOnStartup() .StartAsync(); ``` -------------------------------- ### Example Extension Command using NetCoreInput Source: https://jasperfx.github.io/oakton/guide/host/extensions.html A simple extension command that uses NetCoreInput to build the application's host as a smoke test. ```csharp [Description("Simply try to build a web host as a smoke test", Name = "smoke")] public class SmokeCommand : OaktonCommand { public override bool Execute(NetCoreInput input) { // This method builds out the IWebHost for your // configured IHostBuilder of the application using (var host = input.BuildHost()) { Console.WriteLine("It's all good"); } return true; } } ``` -------------------------------- ### Enumerable Flags Command Line Example Source: https://jasperfx.github.io/oakton/guide/parsing.html Example of using enumerable flags for files and directories. ```bash executable command --files one.txt two.txt "c:\folder\file.txt" --directories c:\folder1 c:\folder2 ``` -------------------------------- ### DictInput Class Example Source: https://jasperfx.github.io/oakton/guide/parsing.html C# class demonstrating a dictionary for key/value flags. ```csharp public class DictInput { public Dictionary PropFlag = new Dictionary(); } ``` -------------------------------- ### AboutThisAppPart Implementation Source: https://jasperfx.github.io/oakton/guide/host/describe.html An example implementation of the `AboutThisAppPart` class, which is a built-in described system part that provides information about the application's assembly, environment, and configuration. ```csharp public class AboutThisAppPart : IDescribedSystemPart { private readonly IHostEnvironment _host; public AboutThisAppPart(IHostEnvironment host, IConfiguration configuration) { _host = host; Title = "About " + Assembly.GetEntryAssembly()?.GetName().Name ?? "This Application"; } public string Title { get; } public Task Write(TextWriter writer) { var entryAssembly = Assembly.GetEntryAssembly(); writer.WriteLine($" Entry Assembly: {entryAssembly.GetName().Name}"); writer.WriteLine($" Version: {entryAssembly.GetName().Version}"); writer.WriteLine($" Application Name: {_host.ApplicationName}"); writer.WriteLine($" Environment: {_host.EnvironmentName}"); writer.WriteLine($" Content Root Path: {_host.ContentRootPath}"); writer.WriteLine($"AppContext.BaseDirectory: {AppContext.BaseDirectory}"); return Task.CompletedTask; } } ``` -------------------------------- ### Argument Usages Example Source: https://jasperfx.github.io/oakton/guide/commands.html Demonstrates how to specify argument usages and valid flags within a command's constructor. ```csharp public OtherNameCommand() { // You can specify multiple usages Usage("describe what is different about this usage") // Specify which arguments are part of this usage // and in what order they should be expressed // by the user .Arguments(x => x.Name, x => x.Color) // Optionally, you can provide a white list of valid // flags in this usage .ValidFlags(x => x.TitleFlag); } ``` -------------------------------- ### Add Resource Setup on Startup Source: https://jasperfx.github.io/oakton/guide/host/resources.html This code snippet demonstrates how to automatically set up all registered IStatefulResource instances on application startup by adding a custom IHostedService. ```csharp using var host = await Host.CreateDefaultBuilder() .ConfigureServices(services => { // More service registrations like this is a real app! services.AddResourceSetupOnStartup(); }).StartAsync(); ``` -------------------------------- ### CheckoutInput Class Example Source: https://jasperfx.github.io/oakton/guide/parsing.html C# class demonstrating how to define flags for recreating git checkout command line options. ```csharp public class CheckoutInput { [FlagAlias("create-branch",'b')] public string CreateBranchFlag { get; set; } public bool DetachFlag { get; set; } public bool ForceFlag { get; set; } } ``` -------------------------------- ### Getting Help for a Single Command Source: https://jasperfx.github.io/oakton/guide/help.html Commands to get usage help for a single command named 'clean'. ```bash executable help clean ``` ```bash executable ? clean ``` -------------------------------- ### Async Command Example Source: https://jasperfx.github.io/oakton/guide/commands.html An example of a command class inheriting from OaktonAsyncCommand for asynchronous operations, showing async/await usage. ```csharp public class DoNameThingsCommand : OaktonAsyncCommand { public override async Task Execute(NameInput input) { AnsiConsole.MarkupLine($"[{input.Color}]Starting...[/]"); await Task.Delay(TimeSpan.FromSeconds(3)); AnsiConsole.MarkupLine($"[{input.Color}]Done! Hello {input.Name}[/]"); return true; } } ``` -------------------------------- ### Asynchronous Command Example Source: https://jasperfx.github.io/oakton/guide/commands.html Example of an asynchronous command using OaktonAsyncCommand. ```csharp [Description("Say my name", Name = "say-async-name")] public class AsyncSayNameCommand : OaktonAsyncCommand { public AsyncSayNameCommand() { Usage("Capture the users name").Arguments(x => x.FirstName, x => x.LastName); } public override async Task Execute(SayName input) { await Console.Out.WriteLineAsync($"{input.FirstName} {input.LastName}"); return true; } } ``` -------------------------------- ### CleanInput Class Definition Source: https://jasperfx.github.io/oakton/guide/getting_started.html Defines the input class for the 'clean' command, including properties for Force, RemoveUntrackedDirectories, and DoNoUseStandardIgnoreRules flags. ```csharp public class CleanInput { [Description("Do it now!")] public bool ForceFlag { get; set; } [FlagAlias('d')] [Description("Remove untracked directories in addition to untracked files")] public bool RemoveUntrackedDirectoriesFlag { get; set; } [FlagAlias('x')] [Description("Remove only files ignored by Git")] public bool DoNoUseStandardIgnoreRulesFlag { get; set; } } ``` -------------------------------- ### Appsettings.json Configuration Source: https://jasperfx.github.io/oakton/guide/host/environment.html Example of a connection string configuration in appsettings.json. ```json { "connectionString": "some connection string using integrated security" } ``` -------------------------------- ### FileInput Class Example Source: https://jasperfx.github.io/oakton/guide/parsing.html C# class demonstrating the use of string arrays for enumerable flags. ```csharp public class FileInput { public string[] FilesFlag; public string[] DirectoriesFlag; } ``` -------------------------------- ### NameCommand Class with Description and Usage Source: https://jasperfx.github.io/oakton/guide/help.html Example of using the [Description] attribute on a command class and defining multiple usage patterns. ```csharp [Description("Print somebody's name")] public class NameCommand : OaktonCommand { public NameCommand() { // The usage pattern definition here is completely // optional Usage("Default Color").Arguments(x => x.Name); Usage("Print name with specified color").Arguments(x => x.Name, x => x.Color); } public override bool Execute(NameInput input) { var text = input.Name; if (!string.IsNullOrEmpty(input.TitleFlag)) { text = input.TitleFlag + " " + text; } AnsiConsole.MarkupLine($"[{input.Color}]{text}[/]"); // Just telling the OS that the command // finished up okay return true; } } ``` -------------------------------- ### Registering Custom Describers Source: https://jasperfx.github.io/oakton/guide/host/describe.html Example of how to register custom `IDescriptionSystemPart` types in the application's DI container using extension methods on `IServiceCollection`. ```csharp static Task Main(string[] args) { return Host.CreateDefaultBuilder() .ConfigureServices(services => { for (int i = 0; i < 5; i++) { services.AddSingleton(new GoodEnvironmentCheck(i + 1)); services.AddSingleton(new BadEnvironmentCheck(i + 1)); services.AddSingleton(new FakeResource("Database", "Db " + (i + 1))); } services.AddSingleton(new FakeResource("Bad", "Blows Up") { Failure = new DivideByZeroException() }); services.CheckEnvironment("Inline, async check", async (services, token) => { await Task.Delay(1.Milliseconds(), token); throw new Exception("I failed!"); }); // This is an example of adding custom // IDescriptionSystemPart types to your // application that can participate in // the describe output services.AddDescription(); services.AddDescription(); services.AddDescription(); }) .RunOaktonCommands(args); } ``` -------------------------------- ### Overriding Hosting Environment and Configuration Source: https://jasperfx.github.io/oakton/guide/host/environment.html Example of overriding hosting environment and configuration items when running environment checks. ```bash dotnet run -- check-env --environment UAT --config:filepath "some file path" ``` -------------------------------- ### Default describe command output Source: https://jasperfx.github.io/oakton/guide/host/describe.html This is an example of the output from the describe command when run without any arguments, showing information about the application's entry assembly, version, environment, and referenced assemblies. ```text ── About EnvironmentCheckDemonstrator ────────────────────────────────────────── Entry Assembly: EnvironmentCheckDemonstrator Version: 1.0.0.0 Application Name: EnvironmentCheckDemonstrator Environment: Production Content Root Path: /Users/jeremydmiller/code/oakton/src/EnvironmentCheckDemonstrator AppContext.BaseDirectory: /Users/jeremydmiller/code/oakton/src/EnvironmentCheckDemonstrator/bin/Debug/net5.0/ ── Referenced Assemblies ──────────────────────────────────────────────────────── ┌───────────────────────────────────────────────────────┬─────────┐ │ Assembly Name │ Version │ ├───────────────────────────────────────────────────────┼─────────┤ │ System.Runtime │ 5.0.0.0 │ │ Oakton │ 3.0.0.0 │ │ Microsoft.Extensions.DependencyInjection.Abstractions │ 5.0.0.0 │ │ System.ComponentModel │ 5.0.0.0 │ │ System.Console │ 5.0.0.0 │ │ Microsoft.Extensions.Hosting │ 5.0.0.0 │ │ Microsoft.Extensions.Hosting.Abstractions │ 5.0.0.0 │ │ Baseline │ 2.1.1.0 │ └───────────────────────────────────────────────────────┴─────────┘ ``` -------------------------------- ### Extending describe Source: https://jasperfx.github.io/oakton/guide/host/describe.html Example of extending the describe functionality to add referenced assemblies to a table. ```csharp foreach (var assemblyName in referenced) table.AddRow(assemblyName.Name, assemblyName.Version.ToString()); AnsiConsole.Write(table); return Task.CompletedTask; } } ``` -------------------------------- ### Sample Options File Content Source: https://jasperfx.github.io/oakton/guide/opts.html An example of the content for an 'mytool.opts' file, providing default user name and password flags. ```text -u MyUserName -p ~~HeMan2345 ``` -------------------------------- ### Writing describe output to a file Source: https://jasperfx.github.io/oakton/guide/host/describe.html Example of how to use the describe command with the --file flag to write the output to a markdown file named 'myapp.md'. ```bash dotnet run -- describe --file myapp.md ``` -------------------------------- ### Successful Environment Checks Output Source: https://jasperfx.github.io/oakton/guide/host/environment.html Example output when all environment checks pass successfully. ```text Running Environment Checks 1.) Success: good 2.) Success: also good All environment checks are good! ``` -------------------------------- ### Asynchronous Execution from Program.Main Source: https://jasperfx.github.io/oakton/guide/commands.html Example of executing commands asynchronously from Program.Main using CommandExecutor. ```csharp static Task Main(string[] args) { var executor = CommandExecutor.For(_ => { // Find and apply all command classes discovered // in this assembly _.RegisterCommands(typeof(Program).GetTypeInfo().Assembly); }); return executor.ExecuteAsync(args); } ``` -------------------------------- ### MyDbCommand with [InjectService] Source: https://jasperfx.github.io/oakton/guide/host/ioc.html Example of a command class using the [InjectService] attribute to inject a DbContext. ```csharp public class MyDbCommand : OaktonAsyncCommand { [InjectService] public MyDbContext DbContext { get; set; } public override Task Execute(MyInput input) { // do stuff with DbContext from up above return Task.FromResult(true); } } ``` -------------------------------- ### ReferencedAssemblies Implementation with Console Formatting Source: https://jasperfx.github.io/oakton/guide/host/describe.html An example of a described system part that implements both `IDescribedSystemPart` for file output (markdown) and `IWriteToConsole` for enhanced console output using Spectre.Console. ```csharp public class ReferencedAssemblies : IDescribedSystemPart, IWriteToConsole { public string Title { get; } = "Referenced Assemblies"; // If you're writing to a file, this method will be called to // write out markdown formatted text public Task Write(TextWriter writer) { var referenced = Assembly.GetEntryAssembly().GetReferencedAssemblies(); foreach (var assemblyName in referenced) writer.WriteLine("* " + assemblyName); return Task.CompletedTask; } // If you're only writing to the console, you can implement the // IWriteToConsole method and optionally use Spectre.Console for // enhanced displays public Task WriteToConsole() { var table = new Table(); table.AddColumn("Assembly Name"); table.AddColumn("Version"); var referenced = Assembly.GetEntryAssembly().GetReferencedAssemblies(); ``` -------------------------------- ### NameInput Class with Description Attributes Source: https://jasperfx.github.io/oakton/guide/help.html Example of using the [Description] attribute on fields and properties of an input class to provide help information. ```csharp public class NameInput { [Description("The name to be printed to the console output")] public string Name { get; set; } [Description("The color of the text. Default is black")] public ConsoleColor Color { get; set; } = ConsoleColor.Black; [Description("Optional title preceeding the name")] public string TitleFlag { get; set; } } ``` -------------------------------- ### Environment Check Failure Output Source: https://jasperfx.github.io/oakton/guide/host/environment.html Example output when an environment check fails due to missing database configuration. ```text Running Environment Checks 1.) Failed: Can connect to the application database System.InvalidOperationException: The ConnectionString property has not been initialized. at System.Data.SqlClient.SqlConnection.PermissionDemand() at System.Data.SqlClient.SqlConnectionFactory.Permissi onDemand(DbConnection outerConnection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.Open() at MvcApp.Startup.<>c.b_ _4_0(IConfiguration config) in /Users/jeremydmiller/code/oakton/src/MvcApp/Startup.cs:line 41 at Oakton.AspNetCore.Environment.EnvironmentCheckExtensions.<>c__DisplayClass2_0`1.b__0(IServ iceProvider s, CancellationToken c) in /Users/jeremydmiller/code/oakton/src/Oakton.AspNetCore/Environment/EnvironmentCheckExtensions.cs:line 53 at Oakton.AspNetCore.Environment.LambdaCheck.Assert(IServiceP ``` -------------------------------- ### Run environment checks Source: https://jasperfx.github.io/oakton/guide/host/run.html This command runs configured environment checks before starting the application. If any checks fail, the application startup will fail. ```bash dotnet run -- --environment ``` -------------------------------- ### Aliased Command Example Source: https://jasperfx.github.io/oakton/guide/commands.html Shows how to override the default command name using the 'Alias' property in the [Description] attribute. ```csharp [Description("Say my name differently", Name = "different-name")] public class AliasedCommand : OaktonCommand ``` -------------------------------- ### Resource Management for Testing Source: https://jasperfx.github.io/oakton/guide/host/resources.html Extension methods available on IHost for managing resources during testing or development, including setup, reset, and teardown. ```csharp public static async Task usages_for_testing(IHost host) { // Programmatically call Setup() on all resources await host.SetupResources(); // Maybe between integration tests, clear any // persisted state. For example, I've used this to // purge Rabbit MQ queues between tests await host.ResetResourceState(); // Tear it all down! await host.TeardownResources(); } ``` -------------------------------- ### IStatefulResource Interface Source: https://jasperfx.github.io/oakton/guide/host/resources.html The IStatefulResource interface defines the contract for stateful resources, allowing Oakton to manage their setup, teardown, clearing of state, and status checks. ```csharp /// /// Adapter interface used by Oakton enabled applications to allow /// Oakton to setup/teardown/clear the state/check on stateful external /// resources of the system like databases or messaging queues /// public interface IStatefulResource { /// /// Categorical type name of this resource for filtering /// string Type { get; } /// /// Identifier for this resource /// string Name { get; } /// /// Check whether the configuration for this resource is valid. An exception /// should be thrown if the check is invalid /// /// /// Task Check(CancellationToken token); /// /// Clear any persisted state within this resource /// /// /// Task ClearState(CancellationToken token); /// /// Tear down the stateful resource represented by this implementation /// /// /// Task Teardown(CancellationToken token); /// /// Make any necessary configuration to this stateful resource /// to make the system function correctly /// /// /// Task Setup(CancellationToken token); /// /// Optionally return a report of the current state of this resource /// /// /// Task DetermineStatus(CancellationToken token); } ``` -------------------------------- ### Set Up All Resources Source: https://jasperfx.github.io/oakton/guide/host/resources.html Command to set up all registered resources. ```bash dotnet run -- resources setup ``` -------------------------------- ### "Old School Program.Main()" (.NET 5 and before) Source: https://jasperfx.github.io/oakton/guide/host/integration_with_i_host.html Oakton usage for "old school" < .Net 6 applications. ```csharp public class Program { public static Task Main(string[] args) { return CreateHostBuilder(args) // This extension method replaces the calls to // IWebHost.Build() and Start() .RunOaktonCommands(args); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(x => x.UseStartup()); } ``` -------------------------------- ### Single Command Bootstrapping Source: https://jasperfx.github.io/oakton/guide/bootstrapping.html If all you have is a single command in your project, the bootstrapping can be as simple as this. ```csharp class Program { static int Main(string[] args) { // As long as this doesn't blow up, we're good to go return CommandExecutor.ExecuteCommand(args); } } ``` -------------------------------- ### Multiple Commands Bootstrapping Source: https://jasperfx.github.io/oakton/guide/bootstrapping.html For more complex applications with multiple commands, you need to interact a little more with the `CommandFactory` configuration. ```csharp public static int Main(string[] args) { var executor = CommandExecutor.For(_ => { // Automatically discover and register // all OaktonCommand's in this assembly _.RegisterCommands(typeof(Program).GetTypeInfo().Assembly); // You can also add commands explicitly from // any assembly _.RegisterCommand(); // In the absence of a recognized command name, // this is the default command to try to // fit to the arguments provided _.DefaultCommand = typeof(ColorCommand); _.ConfigureRun = run => { // you can use this to alter the values // of the inputs or actual command objects // just before the command is executed }; // This is strictly for the as yet undocumented // feature in stdocs to generate and embed usage information // about console tools built with Oakton into // stdocs generated documentation websites _.SetAppName("MyApp"); }); // See the page on Opts files executor.OptionsFile = "myapp.opts"; return executor.Execute(args); } ``` -------------------------------- ### Using a Custom Command Creator Source: https://jasperfx.github.io/oakton/guide/bootstrapping.html How to tell `CommandExecutor` about a custom command creator. ```csharp public static void Bootstrapping(IContainer container) { var executor = CommandExecutor.For(_ => { // do the other configuration of the CommandFactory }, new StructureMapCommandCreator(container)); } ``` -------------------------------- ### Sample Input Class for Arguments Source: https://jasperfx.github.io/oakton/guide/parsing.html Demonstrates how to define arguments as public fields or settable properties, and how to ignore certain members. ```csharp public class NameInput { // Arguments can be settable properties public string First { get; set; } // Arguments can be public fields public string Last; // Read only properties are ignored public string Fullname => $"{First} {Last}"; // You can explicitly ignore public fields or // properties that should not be captured at // the command line [IgnoreOnCommandLine] public string Nickname; // This would be considered to be a flag, // not an argument public bool VerboseFlag { get; set; } } ``` -------------------------------- ### Sample output of available commands Source: https://jasperfx.github.io/oakton/guide/host/run.html Output on a sample MVC application with commands from an extension library. ```text Searching 'AspNetCoreExtensionCommands, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' for commands ----------------------------------------------------------------------- Available commands: ----------------------------------------------------------------------- check-env -> Execute all environment checks against the application run -> Runs the configured AspNetCore application smoke -> Simply try to build a web host as a smoke test ------------------------------------------------------------------------ ``` -------------------------------- ### Listing available commands Source: https://jasperfx.github.io/oakton/guide/host/run.html At any time to see the list of available commands in your system, use either the command `dotnet run -- ?` or `dotnet run -- help`. ```bash dotnet run -- ? ``` -------------------------------- ### IDescribedSystemPart Interface Source: https://jasperfx.github.io/oakton/guide/host/describe.html The `IDescribedSystemPart` interface defines the contract for custom system parts that can be described by the `describe` command. Implementations should provide a title and a method to write markdown-formatted text. ```csharp /// /// Base class for a "described" part of your application. /// Implementations of this type should be registered in your /// system's DI container to be exposed through the "describe" /// command /// public interface IDescribedSystemPart { /// /// A descriptive title to be shown in the rendered output /// string Title { get; } /// /// Write markdown formatted text to describe this system part /// /// /// Task Write(TextWriter writer); } ``` -------------------------------- ### Combining with IWebHostBuilder Source: https://jasperfx.github.io/oakton/guide/host/integration_with_i_host.html Oakton usage with IWebHostBuilder for older .NET versions. ```csharp public class Program { public static Task Main(string[] args) { return CreateWebHostBuilder(args) // This extension method replaces the calls to // IWebHost.Build() and Start() .RunOaktonCommands(args); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup(); } ``` -------------------------------- ### Displaying All Commands Source: https://jasperfx.github.io/oakton/guide/help.html Commands to display a list of all available commands. ```bash executable help ``` ```bash executable ? ``` -------------------------------- ### Programmatic equivalent of overriding hosting environment Source: https://jasperfx.github.io/oakton/guide/host/run.html This code shows the programmatic equivalent of running your application with the `--environment Testing` flag, noting the usage of `UseEnvironment("Testing")`. ```csharp public class Program { public static Task Main(string[] args) { return CreateWebHostBuilder(args) .RunOaktonCommands(args); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup() // This is what the --environment flag does .UseEnvironment("Testing"); } ``` -------------------------------- ### IDescribedSystemPartFactory Interface Source: https://jasperfx.github.io/oakton/guide/host/describe.html The `IDescribedSystemPartFactory` interface allows for the discovery of related groups of system parts. Implementations of this service can help the `describe` command discover additional system parts. ```csharp /// /// Register implementations of this service to help /// the describe command discover additional system parts /// public interface IDescribedSystemPartFactory { IDescribedSystemPart[] Parts(); } ``` -------------------------------- ### Startup.ConfigureServices Method Source: https://jasperfx.github.io/oakton/guide/host/environment.html Adding an environment check for database connectivity in the Startup.ConfigureServices method using Oakton.AspNetCore. ```csharp // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Other registrations we don't care about... // This extension method is in Oakton.AspNetCore services.CheckEnvironment("Can connect to the application database", config => { var connectionString = config["connectionString"]; using (var conn = new SqlConnection(connectionString)) { // Just attempt to open the connection. If there's anything // wrong here, it's going to throw an exception conn.Open(); } }); // Ignore this please;) services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); } ``` -------------------------------- ### Help text for the 'run' command Source: https://jasperfx.github.io/oakton/guide/host/run.html Looking farther into what the 'run' command provides with `dotnet run -- ? run`. ```text Usages for 'run' (Runs the configured AspNetCore application) run [-c, --check] [-e, --environment ] [-v, --verbose] [-l, --log-level ] [----config: ] --------------------------------------------------------------------------------------------------------------------------------------- Flags --------------------------------------------------------------------------------------------------------------------------------------- [-c, --check] -> Run the environment checks before starting the host [-e, --environment ] -> Use to override the ASP.Net Environment name [-v, --verbose] -> Write out much more information at startup and enables console logging [-l, --log-level ] -> Override the log level [----config: ] -> Overwrite individual configuration items --------------------------------------------------------------------------------------------------------------------------------------- ``` -------------------------------- ### Input Class with Enumerable Arguments Source: https://jasperfx.github.io/oakton/guide/parsing.html Shows how to use array or enumerable arguments in an input class. ```csharp public class EnumerableArgumentInput { public IEnumerable Names { get; set; } public IEnumerable OptionalFlag { get; set; } public IEnumerable Enums { get; set; } [Description("ages of target")] public IEnumerable Ages { get; set; } } ``` -------------------------------- ### dotnet run with project specification Source: https://jasperfx.github.io/oakton/guide/host/run.html If your command prompt is at the solution directory, you can use all the available dotnet run options, and in this case tell the dotnet CLI to run a project in another directory. ```bash dotnet run --project src/MvcApp/MvcApp.csproj ``` -------------------------------- ### Overriding the hosting environment Source: https://jasperfx.github.io/oakton/guide/host/run.html To override the hosting environment that your ASP.Net Core application runs under, use the _environment_ flag. ```bash dotnet run -- --environment Testing ``` -------------------------------- ### Command Line Help for check-env Source: https://jasperfx.github.io/oakton/guide/host/environment.html Command to display help information for the 'check-env' command. ```bash dotnet run -- ? check-env ``` -------------------------------- ### resources Command Help Output Source: https://jasperfx.github.io/oakton/guide/host/resources.html The help output for the 'resources' command, showing its structure and available options. ```bash resources - Check, setup, or teardown stateful resources of this system ├── Ensure all stateful resources are set up │ └── dotnet run -- resources │ ├── [-t, --timeout ] │ ├── [-t, --type ] │ ├── [-n, --name ] │ ├── [-e, --environment ] │ ├── [-v, --verbose] │ ├── [-l, --log-level ] │ └── [----config: ] └── Execute an action against all resources └── dotnet run -- resources clear|teardown|setup|statistics|check|list ├── [-t, --timeout ] ├── [-t, --type ] ├── [-n, --name ] ├── [-e, --environment ] ├── [-v, --verbose] ├── [-l, --log-level ] └── [----config: ] Usage Description ────────────────────────────────────────────────────────────────────────────────────────────────────────────── action Resource action, default is setup [-t, --timeout ] Timeout in seconds, default is 60 [-t, --type ] Optionally filter by resource type [-n, --name ] Optionally filter by resource name [-e, --environment ] Use to override the ASP.Net Environment name [-v, --verbose] Write out much more information at startup and enables console logging [-l, --log-level ] Override the log level [----config: ] Overwrite individual configuration items ``` -------------------------------- ### Describe command line flags Source: https://jasperfx.github.io/oakton/guide/host/describe.html This shows the available command-line flags for the describe command, including options for output file, silent mode, title filtering, listing parts, interactive mode, environment override, verbosity, log level, and configuration overrides. ```text [-f, --file ] -> Optionally write the description to the given file location [-s, --silent] -> Do not write any output to the console [-t, --title ] -> Filter the output to only a single described part [-l, --list] -> If set, the command only lists the known part titles [-i, --interactive] -> If set, interactively select which part(s) to preview [-e, --environment <environment>] -> Use to override the ASP.Net Environment name [-v, --verbose] -> Write out much more information at startup and enables console logging [-l, --log-level <loglevel>] -> Override the log level [----config:<prop> <value>] -> Overwrite individual configuration items ``` -------------------------------- ### Registering Commands from Extension Assemblies Source: https://jasperfx.github.io/oakton/guide/discovery.html This C# code demonstrates how to opt into the auto-discovery of commands by using the RegisterCommandsFromExtensionAssemblies() option when building a CommandFactory in Oakton.AspNetCore. ```csharp return CommandExecutor.For(factory => { factory.ApplyFactoryDefaults(applicationAssembly); factory.ConfigureRun = commandRun => { if (commandRun.Input is IHostBuilderInput i) { factory.ApplyExtensions(source); i.HostBuilder = source; } else { var props = commandRun.Command.GetType().GetProperties().Where(x => x.HasAttribute<InjectServiceAttribute>()) .ToArray(); if (props.Any()) { commandRun.Command = new HostWrapperCommand(commandRun.Command, source.Build, props); } } }; }); ``` -------------------------------- ### .NET 6 Console Integration Source: https://jasperfx.github.io/oakton/guide/host/integration_with_i_host.html Oakton integration with IHost for .NET 6 console applications. ```csharp using Oakton; var builder = WebApplication.CreateBuilder(args); // This isn't required, but it "helps" Oakton to enable // some additional diagnostics for the stateful resource // model builder.Host.ApplyOaktonExtensions(); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); // Note the usage of await to force the implied // Program.Main() method to be asynchronous return await app.RunOaktonCommands(args); ``` -------------------------------- ### Default dotnet run command Source: https://jasperfx.github.io/oakton/guide/host/run.html To run your application normally from a command prompt with all the default configuration from the project root directory. ```bash dotnet run ``` -------------------------------- ### Overriding configuration items Source: https://jasperfx.github.io/oakton/guide/host/run.html Individual values in your system's IConfiguration can be overridden at the command line using the _--config_ flag. ```bash dotnet run -- --config:key1 value1 --config:key2 value2 ``` -------------------------------- ### Configuring Options File Source: https://jasperfx.github.io/oakton/guide/opts.html Configures the command executor to look for an options file named 'mytool.opts'. ```csharp var executor = CommandExecutor.For(_ => { // configure the command discovery }); executor.OptionsFile = "mytool.opts"; ``` -------------------------------- ### check-env Command Line Help Output Source: https://jasperfx.github.io/oakton/guide/host/environment.html Output detailing the available flags and options for the 'check-env' command. ```text Usages for 'check-env' (Execute all environment checks against the application) check-env [-f, --file <file>] [-e, --environment <environment>] [-v, --verbose] [-l, --log-level <logleve>] [----config:<prop> <value>] ------------------------------------------------------------------------------------------------------------------ Flags ------------------------------------------------------------------------------------------------------------------ [-f, --file <file>] -> Use to optionally write the results of the environment checks to a file [-e, --environment <environment>] -> Use to override the ASP.Net Environment name [-v, --verbose] -> Write out much more information at startup and enables console logging [-l, --log-level <logleve>] -> Override the log level [----config:<prop> <value>] -> Overwrite individual configuration items ------------------------------------------------------------------------------------------------------------------ ``` -------------------------------- ### List Registered Resources Source: https://jasperfx.github.io/oakton/guide/host/resources.html Command to list all registered resources in the system. ```bash dotnet run -- resources list ``` -------------------------------- ### Defining Dependencies Between Resources Source: https://jasperfx.github.io/oakton/guide/host/resources.html An interface for stateful resources that allows defining dependencies on other resources, ensuring they are set up in the correct order. ```csharp /// <summary> /// Use to create dependencies between /// </summary> public interface IStatefulResourceWithDependencies : IStatefulResource { // Given all the known stateful resources in your system -- including the current resource! // tell Oakton which resources are dependencies of this resource that should be setup first IEnumerable<IStatefulResource> FindDependencies(IReadOnlyList<IStatefulResource> others); } ``` -------------------------------- ### Base Class for Command Inputs Source: https://jasperfx.github.io/oakton/guide/opts.html A base class for command inputs that includes optional user name and password properties. ```csharp public class SecuredInput { public string UserName { get; set; } public string Password { get; set; } } ``` -------------------------------- ### View Resource Statistics Source: https://jasperfx.github.io/oakton/guide/host/resources.html Command to view statistics for all registered resources. ```bash dotnet run -- resources statistics ``` -------------------------------- ### Running Environment Checks Source: https://jasperfx.github.io/oakton/guide/host/environment.html Command to run environment checks on the application. ```bash dotnet run -- check-env ``` -------------------------------- ### Teardown All Resources Source: https://jasperfx.github.io/oakton/guide/host/resources.html Command to teardown all registered resources. ```bash dotnet run -- resources teardown ``` -------------------------------- ### Marking an Assembly for Oakton Command Discovery Source: https://jasperfx.github.io/oakton/guide/discovery.html This C# attribute is used to mark assemblies that contain Oakton commands to be discovered and loaded automatically. ```csharp [assembly:Oakton.OaktonCommandAssembly] ``` -------------------------------- ### Required Files Check Source: https://jasperfx.github.io/oakton/guide/host/environment.html Extension method for checking the existence of a required file. ```csharp /// <summary> /// Issue an environment check for the existence of a named file /// </summary> /// <param name="services"></param> /// <param name="path"></param> public static void CheckThatFileExists(this IServiceCollection services, string path) { var check = new FileExistsCheck(path); services.AddSingleton<IEnvironmentCheck>(check); } ``` -------------------------------- ### Check Resource State Source: https://jasperfx.github.io/oakton/guide/host/resources.html Command to check the state of each registered resource. ```bash dotnet run -- resources check ``` -------------------------------- ### Required Service Registration Check Source: https://jasperfx.github.io/oakton/guide/host/environment.html Extension methods for checking if a required IoC service registration exists. ```csharp /// <summary> /// Issue an environment check for the registration of a service in the underlying IoC /// container /// </summary> /// <param name="services"></param> /// <typeparam name="T"></typeparam> public static void CheckServiceIsRegistered<T>(this IServiceCollection services) { services.CheckEnvironment("Service {typeof(T).FullName} should be registered", s => s.GetRequiredService<T>()); } /// <summary> /// Issue an environment check for the registration of a service in the underlying IoC /// container /// </summary> /// <param name="services"></param> /// <param name="serviceType"></param> public static void CheckServiceIsRegistered(this IServiceCollection services, Type serviceType) { services.CheckEnvironment($"Service {serviceType.FullName} should be registered", s => s.GetRequiredService(serviceType)); } ``` -------------------------------- ### IStatefulResourceSource Interface Source: https://jasperfx.github.io/oakton/guide/host/resources.html The IStatefulResourceSource interface is a helper to find other stateful resources, allowing for the discovery and management of multiple resources. ```csharp /// <summary> /// Expose multiple stateful resources /// </summary> public interface IStatefulResourceSource { IReadOnlyList<IStatefulResource> FindResources(); } ``` -------------------------------- ### IEnvironmentCheck Interface Source: https://jasperfx.github.io/oakton/guide/host/environment.html The IEnvironmentCheck interface defines the contract for environment checks in Oakton.AspNetCore. ```csharp /// <summary> /// Executed during bootstrapping time to carry out environment tests /// against the application /// </summary> public interface IEnvironmentCheck { /// <summary> /// A textual description for command line output that describes /// what is being checked /// </summary> string Description { get; } /// <summary> /// Asserts that the current check is valid. Throw an exception /// to denote a failure /// </summary> Task Assert(IServiceProvider services, CancellationToken cancellation); } ``` -------------------------------- ### Clear Existing State Source: https://jasperfx.github.io/oakton/guide/host/resources.html Command to clear any existing state for resources. ```bash dotnet run -- resources clear ``` -------------------------------- ### Overriding the minimum log level Source: https://jasperfx.github.io/oakton/guide/host/run.html You can override the minimum log level in the running application using any valid value of the LogLevel enumeration and the _--log-level_ flag. ```bash dotnet run -- --log-level Information ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.