Skip to content

Console Commands ​

Complete Example: A Validating Command ​

Add this file to a Blog application:

csharp
// app/Commands/GreetDemo.cs
using DotBlaze;

namespace Blog.Commands;

public class GreetDemo : Command
{
    public override string Signature => "demo:greet {name} {--times=1}";
    public override string Description => "Print a greeting one to five times.";
    public override Task<int> Handle()
    {
        if (!int.TryParse(Option("times"), out var count) || count is < 1 or > 5)
        {
            Error("--times must be between 1 and 5.");
            return Task.FromResult(1);
        }
        for (var index = 0; index < count; index++)
            Line($"Hello, {Argument("name")}.");
        return Task.FromResult(0);
    }
}

Run dotblaze demo:greet Ada --times=2: two Hello, Ada. lines and exit code 0. --times=abc returns 1 with the validation message. dotblaze demo:greet --help shows usage. Runtime fallback: dotnet run -- demo:greet Ada; make:* generators themselves belong to the CLI rather than the application's runtime command registry.

Introduction ​

Laravel ships with Artisan, a command line interface that runs inside your application. DotBlaze takes the same approach: the commands are built into the application, and you run them by passing the command name to your app, either directly or through the dotblaze tool.

The dotblaze Tool ​

dotblaze is a dotnet tool (see Installation for how to install it). Run it anywhere inside your application folder; it finds the nearest .csproj that references DotBlaze by searching upward from the current directory.

CommandWhat it does
dotblaze new BlogCreates a new application (runs dotnet new dotblaze-app -n Blog -o Blog).
dotblaze serveRuns the web server (dotnet run). Extra arguments go to dotnet run.
dotblaze serve --watchWatches files and rebuilds/restarts (dotnet watch --no-hot-reload --project <app.csproj> run), including Blade changes. Remaining arguments are forwarded after run; arguments after -- belong to the app. See Hot Reload.
dotblaze make:...Generates code, see Generating Code. These run in the tool itself and do not build your app.
dotblaze <command>Anything else runs in your application: dotblaze migrate is dotnet run -- migrate.

Running Commands ​

With the tool:

shell
dotblaze list
dotblaze migrate

Without it, put the command after --, so dotnet run passes it to your application:

shell
dotnet run -- list
dotnet run -- migrate

A published application takes the command as its first argument:

shell
dotnet Blog.dll migrate

list shows every command: the built-in ones, your own, and (through the tool) the generators. --help after a command name shows its arguments and options:

shell
dotblaze queue:work --help

Passing Options ​

Options use the --name=value or --name value form; an option without a value is a flag. Other arguments are positional:

shell
dotblaze queue:work --queue=emails,default --sleep=5
dotblaze migrate:fresh --seed
dotblaze queue:retry 12

Unknown options, missing arguments, and extra arguments print the usage and exit with 1.

Tinker (REPL) ​

Tinker is an interactive C# console with your application loaded, like php artisan tinker. You can use your models, facades, and services in it. It ships as a separate package, because it brings the C# compiler (Roslyn) with it:

bash
dotnet add package DotBlaze.Tinker
bash
dotblaze tinker
text
> await Post.Query().Count()
= 18
> var user = await User.Find(1);
> user.Email
= "ada@example.com"
> if (user is not null) {
*   Console.WriteLine(user.Name);
* }
Ada
> exit

How Tinker works:

  • An expression without a semicolon prints its value. Strings are shown quoted, and models and collections as JSON, with hidden attributes left out.
  • A statement or declaration ending in ; prints nothing. Its variables, methods, classes, and using directives stay available for the rest of the session.
  • await works at the top level.
  • Code that is not finished yet, such as an open {, continues on the next line, shown as *.
  • An error prints the compiler message or the exception, and the session keeps its state.

The namespaces System, System.Linq, System.Collections.Generic, System.Threading.Tasks, System.Text, and DotBlaze are imported, plus every namespace of your application and its packages. A type such as Post therefore needs no using.

The code runs in one service scope for the whole session, like a command does. Saving models, sending mail, and dispatching jobs all happen for real, in the database the configuration points at.

To run code without the prompt, pass it with --execute, or pipe it in. The exit code is 1 if the code failed:

bash
dotblaze tinker --execute="await User.Query().Count()"
bash
echo 'await Cache.Forget("post-stats")' | dotblaze tinker

Available Commands ​

Database Commands ​

CommandDescription
migrateRun pending migrations. --seed runs DatabaseSeeder afterwards; --seeder=Name picks another seeder.
migrate:rollbackRoll back the last batch of migrations.
migrate:resetRoll back all migrations.
migrate:freshDrop all tables on the default connection and run all migrations again. Accepts --seed and --seeder=Name.
migrate:statusShow which migrations have run, and in which batch.
db:seedRun DatabaseSeeder, or another seeder with --class=Name.
db:checkCompare your models with the database schema and list the differences.

NOTE

To choose a seeder, db:seed uses --class=Name, while migrate --seed and migrate:fresh --seed use --seeder=Name. This is intentional and the same as in Laravel.

See Migrations and Seeding.

Queue Commands ​

CommandDescription
queue:workProcess jobs until stopped. Options: --queue=a,b (queues in priority order, default default), --connection=name, --sleep=3 (seconds to wait when the queues are empty), --stop-when-empty, --memory=MB, --max-jobs=N, --max-time=seconds (exit after a limit; memory exits with 12), and --tries, --backoff, --timeout (defaults for jobs that set none).
queue:managerRun and balance many queue:work processes from queue.manager in config/Queue.cs, like Horizon. See The Queue Manager.
queue:manager:statusShow the running queue managers, their workers, and waiting jobs.
queue:manager:terminateStop the queue managers after their workers finish the current job (run after a deploy).
queue:failedList failed jobs.
queue:retry <id|all>Push one failed job, or all of them, back onto the connection each failed on. A missing or invalid id prints the usage and exits with 1.
queue:flushDelete all failed jobs.
queue:prune-batchesDelete finished batches older than --hours=24; --unfinished=72 also deletes unfinished ones older than that.

The dashboard packages add their own commands:

CommandDescription
horizon:clearDelete the jobs recorded by Horizon.
telescope:pruneDelete Telescope entries older than --hours=24.
telescope:clearDelete every Telescope entry.
pulse:checkRecord this server's CPU, memory, and disk usage for Pulse until stopped (--once for one reading).
pulse:clearDelete everything Pulse recorded.

queue:work checks the queues in the order given and always drains the first one before moving to the next. Pressing Ctrl+C (SIGINT) or sending SIGTERM lets the current job finish before the worker stops. In production, run workers under a process supervisor; see Deployment and Queues.

Schedule Commands ​

CommandDescription
schedule:runRun the scheduled tasks that are due. Call it every minute from cron.
schedule:workRun the scheduler every minute until stopped (instead of a cron entry).
schedule:listList the scheduled tasks, their cron expressions, and when each runs next.
schedule:test <task>Run one task now, by its number in schedule:list or its name.

Auth Commands ​

CommandDescription
tokens:prune-expiredDelete API tokens that expired more than --hours=24 ago.

Maintenance Commands ​

CommandDescription
downPut the application into maintenance mode. Options: --secret=, --with-secret, --retry=, --refresh=, --redirect=, --render=, --status=503.
upBring it back up.

Route Commands ​

CommandDescription
key:generateWrite a new APP_KEY to .env (from .env.example if there is no .env yet). Refuses to replace a key without --force; --show only prints a key. See Encryption.
route:listList all registered routes with their HTTP methods, URI, name, controller action, and middleware.

Cache Commands ​

CommandDescription
cache:clear [store]Flush a cache store (default: cache.default).

Generating Code ​

The make:* generators write a new file into the conventional folder, with the namespace taken from your project (its <RootNamespace>, or the .csproj file name). A name with slashes creates subfolders and namespaces: dotblaze make:controller Admin/DashboardController writes app/Http/Controllers/Admin/DashboardController.cs in namespace Blog.Controllers.Admin.

Generators never overwrite an existing file unless you pass --force (-f).

Core generators run in the CLI. Package-specific generators are discovered from installed packages and forwarded to the application, so they require a buildable app. make:agent, make:agent-middleware, and make:tool only appear and work after installing DotBlaze.AI. The same rule applies to third-party generators; package authors use GeneratorCommand, not a hard-coded CLI entry.

CommandCreatesOptions
make:controller Nameapp/Http/Controllers--resource (-r): the seven resource actions; --model=Post: actions take a Post (inferred from PostController when app/Models/Post.cs exists).
make:factory Namedatabase/factories--model=Post (inferred from the name otherwise).
make:model Nameapp/Models--factory: also a factory. --migration (-m): also a create_<table>_table migration.
make:migration namedatabase/migrations--create=table, --table=table. See Migrations.
make:seeder Namedatabase/seeders
make:request Nameapp/Http/Requests
make:middleware Nameapp/Http/Middleware--parameters: implements IParameterizedRouteMiddleware (role:admin,editor).
make:provider Nameapp/Providers
make:agent Name [--structured]app/Ai/AgentsNamed agent; requires the optional AI SDK package. --structured adds a result record and a typed Ask method.
make:agent-middleware Nameapp/Ai/MiddlewareA DelegatingChatClient to return from an agent's Middleware().
make:tool Nameapp/Ai/ToolsDescribed function handler for registration with AIFunctionFactory.Create.
make:job Nameapp/Jobs--sync: not queued (no IShouldQueue).
make:event Nameapp/Events
make:listener Nameapp/Listeners--event=Name (required), --queued.
make:live Nameapp/Live + resources/views/liveThe class and its view; adds @using <App>.LiveComponents to _ViewImports.cshtml. See Live Components.
make:mail Nameapp/Mail--queued: implements IShouldQueue. See Mail.
make:notification Nameapp/Notifications--sync: not queued. See Notifications.
make:policy Nameapp/Policies--model=Post: the model (inferred from PostPolicy). See Authorization.
make:command Nameapp/Commands--command=app:name: the command name; by default SendEmailsCommand becomes app:send-emails.
make:authLogin, registration, password reset, email verificationSee below.

Requests are put in the Blog.Requests namespace and controllers in Blog.Controllers (not Blog.Http.*), so that a namespace named Http does not hide the Http facade.

Authentication Scaffolding ​

dotblaze make:auth adds the authentication code from the sample blog, which is covered by its tests: login (with "remember me" and login throttling), registration, logout, password reset, and email verification:

  • app/Http/Controllers/AuthController.cs, PasswordResetController.cs, and EmailVerificationController.cs
  • app/Http/Requests/LoginRequest.cs, RegisterRequest.cs, ForgotPasswordRequest.cs, and ResetPasswordRequest.cs
  • resources/views/auth/Login.blade.html, Register.blade.html, ForgotPassword.blade.html, ResetPassword.blade.html, VerifyEmail.blade.html, ConfirmPassword.blade.html, TwoFactorChallenge.blade.html, and the _Field.blade.html partial (Blade views)
  • routes/auth.cs, whose AuthRoutes.Map() is added after Web.Map() in RouteServiceProvider

The template's User model and migrations already have what these need (RememberToken, EmailVerifiedAt, the password_reset_tokens table). Reset and verification links are emailed, so configure mail and APP_URL.

If any of these files already exists, nothing is written unless you pass --force. Your layout is not changed; the command prints the snippet for the login, register, and logout links. After logging in, users go to / (the Home constant in AuthController). See Authentication.

Writing Commands ​

Generate a command with dotblaze make:command SendEmailsCommand. Any non-abstract class in your application that extends DotBlaze.Command is discovered automatically:

csharp
namespace Blog.Commands;

public class SendEmailsCommand(IQueue queue) : Command
{
    public override string Signature => "mail:send {user : The user id} {--queue=default}";
    public override string Description => "Send the welcome email to a user";

    public override async Task<int> Handle()
    {
        var user = await User.Find(long.Parse(Argument("user")!));
        if (user is null)
        {
            Error("User not found.");
            return 1;
        }

        await queue.Push(new SendWelcomeEmail { User = user }, Option("queue"));
        Info($"Queued the email for {user.Email}.");
        return 0;
    }
}

The constructor may take services from dependency injection. Facades and models work inside Handle, as in a controller. Handle returns the exit code: 0 for success. Two commands with the same name stop the application at startup with an error naming both classes.

Closure Commands ​

A small command does not need a class. Define it with a closure in routes/console.cs, like Laravel's Artisan::command(). The application template includes this one, so dotblaze inspire works in a new app:

csharp
public static class ConsoleRoutes
{
    public static void Map()
    {
        Artisan.Command("inspire", (ClosureCommand command) =>
        {
            command.Comment(Inspiring.Quote());
        }).Purpose("Display an inspiring quote");
    }
}

The signature has the same syntax as a class command's, and .Purpose(...) is the description dotblaze list and --help show. The closure's parameters are filled by type and name:

ParameterValue
ClosureCommandThe running command, Laravel's $this: Argument, Option, Flag, Line, Info, Comment, Error, Call, Out, Stopping.
Named like an argument or optionIts value, converted to the parameter's type (string, numbers, bool, enums, and their nullable forms). --dry-run fills dryRun; a flag fills a bool.
CancellationTokenCancelled on Ctrl+C or SIGTERM, like Stopping.
Any other typeA service from dependency injection.
csharp
Artisan.Command("posts:count {--user= : Only this user's posts}", async (ClosureCommand command, long? user) =>
{
    var query = Post.Query();
    if (user is { } id) query = query.Where(p => p.UserId == id);
    command.Info($"{await query.Count()} posts");
}).Purpose("Count the posts");

Artisan.Command("mail:send {user} {--queue=default}", async (ClosureCommand command, long user, string queue, IQueue jobs) =>
{
    await jobs.Push(new SendWelcomeEmail { User = await User.FindOrFail(user) }, queue);
    return 0;
});

The closure may return nothing (exit code 0), an int exit code, a Task, or a Task<int>. A value that cannot be converted, such as --user=abc for a long?, prints the error and the usage and exits with 1. A closure command with the same name as a class command, or as another closure command, stops the command with an error naming both.

routes/console.cs runs in RouteServiceProvider.Boot, so closure commands are registered before any command runs, and the scheduler can run them with Schedule.Command("inspire").

Defining Input ​

The signature uses Laravel's syntax: the command name, then each argument and option in braces.

SyntaxMeaning
{user}Required argument.
{user?}Optional argument.
{user=1}Optional argument with a default.
{--force}Boolean option (flag).
{--queue=}Option that takes a value.
{--queue=default}Option with a default value.
{--F|force}Adds the shortcut -F.
{user : The user id}A description, shown by --help.

Arrays ({user*}) are not supported.

Reading Input ​

Argument("user") and Option("queue") return the value as a string, the default when it was not passed, or null. Flag("force") returns whether a boolean option was passed.

Writing Output ​

Line(text) and Info(text) write to standard output, Error(text) to standard error. There are no colors, tables, or prompts yet.

Long-Running Commands ​

The Stopping token is cancelled on Ctrl+C or SIGTERM. Pass it to async calls, or check it in a loop, so the command can stop cleanly:

csharp
foreach (var user in await User.All())
{
    if (Stopping.IsCancellationRequested) return 1;
    await SendReport(user);
}

Calling Other Commands ​

Call(commandLine) runs another command in-process, like Laravel's $this->call(), and returns its exit code; its output goes to this command's output:

csharp
await Call("cache:clear redis");
await Call("migrate");

The scheduler runs Schedule.Command(...) tasks the same way.

From controllers or services, use the Artisan facade:

csharp
using var output = new StringWriter();
var exitCode = await Artisan.Call("route:list", output);
var text = output.ToString();

Artisan.Call also accepts a string array of command arguments, a separate error writer, and a cancellation token. It returns the command's exit code, preserves command validation and exception behavior, and uses a fresh service scope with a copy of the caller's context.

How Commands Run ​

When the first argument is a command name, Application.Create builds the application exactly as it does for the web server: .env and the config/*.cs classes are loaded, and every provider runs Register and Boot. Then, instead of starting the web server, the command runs inside its own service scope, so facades and models work as usual. Command options are not added to the application's configuration.

Because the web host is not started for a command, hosted services do not run. In particular, the in-app queue worker (queue.worker: true) never runs during a command.

The dotblaze tool forwards a command with dotnet run --project <your.csproj> -- <command>, so it builds your application first if needed. Build errors are shown and the command does not run.

NOTE

Any first argument that is not an option (--x or x=y) is treated as a command. An unknown one, such as a misspelled dotblaze migrat, prints Unknown command 'migrat'. and exits with 1 instead of starting the web server.

Exit Codes ​

Commands exit with code 0 on success. Some commands use other codes, which is useful in scripts and CI:

  • db:check exits with 1 when the schema does not match the models.
  • queue:work exits with 1 when a job ignores its timeout, so a process supervisor can start a fresh worker.
  • Bad input (unknown command or option, missing argument) exits with 1.
  • An unhandled exception (for example a failing migration) ends the command with a non-zero code.

The dotblaze tool returns the exit code of the command it forwarded.

Not Yet Available ​

There are no interactive prompts (ask, confirm), tables, or progress bars in commands yet.