### Install Coravel using CLI Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Installation/README.md Installs Coravel into an existing project using the Coravel CLI. ```bash coravel install ``` -------------------------------- ### Install Coravel via NuGet Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Installation/README.md Installs the Coravel NuGet package into your .NET project. ```bash dotnet add package coravel ``` -------------------------------- ### Install Coravel CLI and Mailer Feature Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Installs the Coravel CLI globally and then uses it to install the mailer feature, which adds the necessary Nuget package and scaffolding files. ```bash dotnet tool install --global coravel-cli coravel mail install ``` -------------------------------- ### Install Coravel CLI Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Installation/README.md Installs the Coravel CLI as a global .NET tool, enabling scaffolding and easier project integration. ```bash dotnet tool install --global coravel-cli ``` -------------------------------- ### Coravel Queuing Setup Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Demonstrates how to add Coravel's queuing services to a .NET Core application's startup configuration and how to inject the IQueue interface. ```csharp services.AddQueue(); // ... IQueue _queue; public HomeController(IQueue queue) { this._queue = queue; } ``` -------------------------------- ### Coravel CLI Installation Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Cli/README.md Installs the Coravel CLI global tool using the .NET CLI. ```bash dotnet tool install --global coravel-cli ``` -------------------------------- ### Install Coravel into Project Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Cli/README.md Installs the necessary Coravel Nuget package(s) into an existing .NET Core project. ```bash coravel install ``` -------------------------------- ### Razor View Example Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md An example of a Razor view for an email, demonstrating how to use a model, set ViewBag properties for heading and preview, and define sections for content. ```html @model App.Models.UserModel @{ ViewBag.Heading = "Welcome New User: " + Model.Name; ViewBag.Preview = "Preview message in inbox"; }

Hi @Model.Name! @await Component.InvokeAsync("EmailLinkButton", new { text = "click me", url = "www.google.com" })

@section links { Google | Google } ``` -------------------------------- ### Coravel Scheduler Quick-Start Source: https://github.com/jamesmh/coravel/blob/master/README.md This C# code snippet demonstrates how to set up Coravel's task scheduler in a .NET worker service. It schedules a console message to be printed every second. This requires the 'coravel' NuGet package and basic .NET worker service setup. ```csharp using Coravel; Console.OutputEncoding = System.Text.Encoding.UTF8; var builder = Host.CreateApplicationBuilder(args); builder.Services.AddScheduler(); var host = builder.Build(); host.Services.UseScheduler(s => { s.Schedule(() => Console.WriteLine("It's alive! 🧟")).EverySecond(); }); host.Run(); ``` -------------------------------- ### Use Coravel Scheduler in Configure Method Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Configures and starts the Coravel scheduler within the application's request pipeline. ```csharp var provider = app.ApplicationServices; provider.UseScheduler(scheduler => { scheduler.Schedule( () => Console.WriteLine("Every minute during the week.") ) .EveryMinute() .Weekday(); }); ``` -------------------------------- ### Configure PostgreSQL Cache Driver Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Caching/README.md Configures Coravel to use PostgreSQL for caching. This requires installing the `Coravel.Cache.PostgreSQL` NuGet package and registering the PostgreSQL cache provider with the connection string in `Startup.cs`. ```csharp services.AddPostgreSQLCache(connectionString); ``` -------------------------------- ### Configure SQL Server Cache Driver Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Caching/README.md Configures Coravel to use SQL Server for caching. This involves installing the `Coravel.Cache.SQLServer` NuGet package and registering the SQL Server cache provider with the connection string in `Startup.cs`. ```csharp services.AddSQLServerCache(connectionString); ``` -------------------------------- ### Distributed Locking with Coravel and DistributedLock Source: https://github.com/jamesmh/coravel/blob/master/README.md Example of how to implement distributed locking within a Coravel invocable using the DistributedLock library. This ensures that only one instance of the invocable can execute critical sections of code at a time, preventing race conditions when accessing shared resources like a database. ```csharp public class TestInvocable : IInvocable { private ApplicationDbContext _context; private IDistributedLockProvider _distributedlock; public TestInvocable(ApplicationDbContext context, IDistributedLockProvider distributedlock) { this._context = context; this._distributedlock = distributedlock; } public async Task Invoke() { await using (await this._distributedlock.AcquireAsync()) { await this._context.Test.AddAsync(new TestModel() { Name = "test name" }); await this._context.SaveChangesAsync(); } } } ``` -------------------------------- ### Daily Report Email Job Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md An example C# class implementing the IInvocable interface to send daily reports via email. It depends on IMailer and IUserRepository for sending emails and fetching user data, respectively. The Invoke method iterates through users and sends a personalized email to each. ```csharp public class SendDailyReportsEmailJob : IInvocable { private IMailer _mailer; private IUserRepository _repo; // Each param injected from the service container ;) public SendDailyReportsEmailJob(IMailer mailer, IUserRepository repo) { this._mailer = mailer; this._repo = repo; } public async Task Invoke() { var users = await this._repo.GetUsersAsync(); foreach(var user in users) { var mailable = new NightlyReportMailable(user); await this._mailer.SendAsync(mailable); } } } ``` -------------------------------- ### On-the-Fly Mailable Creation and Sending Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Demonstrates dynamically building and configuring a Mailable before sending it via the IMailer. ```csharp var mail = new GenericMailable() .To("to@test.com") .From("from@test.com") .Html("

Hi!

"); await this._mailer.SendAsync(mail); ``` -------------------------------- ### Global Error Handling for Queues Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Shows how to configure global error handling for the Coravel queue within the application's startup process, allowing for centralized error management. ```csharp var provider = app.ApplicationServices; provider .ConfigureQueue() .OnError(e => { //... handle the error }); ``` -------------------------------- ### Sample Invocable Implementation (Daily Report) Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Invocables/README.md Provides a sample C# implementation of an `IInvocable` class that generates a daily report and sends it via email using Coravel's Mailer service. ```csharp public class SendDailyReportsEmailJob : IInvocable { private readonly IMailer _mailer; private readonly IRepository _repository; public SendDailyReportsEmailJob(IMailer mailer, IRepository repository) { _mailer = mailer; _repository = repository; } public async Task Invoke() { var data = _repository.GetData(); var email = new Email("to@example.com", "Daily Report", "Report content..."); await _mailer.SendAsync(email); } } ``` -------------------------------- ### Configure Mailer in Startup.ConfigureServices() (Non-Web) Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Configures the Coravel Mailer service in non-web .NET projects within the ConfigureServices method, requiring an IConfiguration instance. ```csharp services.AddMailer(this.Configuration); // Instance of IConfiguration. ``` -------------------------------- ### Queuing Invocables Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Shows how to queue a standard Invocable class for background execution using Coravel's QueueInvocable method. ```csharp this._queue.QueueInvocable(); ``` -------------------------------- ### Configure Mailer in Program.cs (.NET Minimal) Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Configures the Coravel Mailer service in a .NET minimal application by calling the AddMailer() extension method. ```csharp var builder = WebApplication.CreateBuilder(args); builder.AddMailer(); ``` -------------------------------- ### Using Coravel's Plain Email Template Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Configures the application to use Coravel's plain email template by setting the Layout property in the _ViewStart.cshtml file. ```csharp @{ Layout = "~/Areas/Coravel/Pages/Mail/PlainTemplate.cshtml"; } ``` -------------------------------- ### Coravel Queue Metrics Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Shows how to retrieve metrics about the queue's current state, including the number of waiting and running tasks. ```csharp var metrics = _queue.GetMetrics(); // Available methods: // metrics.WaitingCount() // metrics.RunningCount() ``` -------------------------------- ### Tracking Task Progress with Events Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Demonstrates how to create listeners for queue events like 'QueueTaskStarted', 'QueueTaskCompleted', and 'DequeuedTaskFailed' to monitor task progress and handle failures. ```csharp public class TaskStartedListener : IListener { // Constructor etc. public async Task HandleAsync(QueueTaskStarted broadcasted) { await this._uiNotifications.NotifyTaskStarted(broadcasted.Guid); } } ``` -------------------------------- ### Queuing Async Tasks Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Demonstrates how to queue an asynchronous task directly using the QueueAsyncTask method, allowing for background execution of lambda expressions. ```csharp this._queue.QueueAsyncTask(async() => { await Task.Delay(1000); Console.WriteLine("This was queued!"); }); ``` -------------------------------- ### Queuing Synchronous Tasks Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Shows how to queue a synchronous task for background execution using the QueueTask method. ```csharp public IActionResult QueueTask() { this._queue.QueueTask(() => Console.WriteLine("This was queued!")); return Ok(); } ``` -------------------------------- ### Queueing Event Broadcasts Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Explains how to queue events for background broadcasting using the QueueBroadcast method, preventing long-running event listeners from blocking HTTP requests. ```csharp this._queue.QueueBroadcast(new OrderCreated(orderId)); ``` -------------------------------- ### Queuing Email Sending Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Shows how to queue an asynchronous task to send an email using the IMailer and Coravel's queuing feature. ```csharp this._queue.QueueAsyncTask(async () => await this._mailer.SendAsync(new MyMailable()) ); ``` -------------------------------- ### Configure Coravel Events Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Events/README.md Configures Coravel's event broadcasting services in the application's startup. This involves adding the necessary services and configuring the event registration. ```csharp services.AddEvents(); var provider = app.ApplicationServices; IEventRegistration registration = provider.ConfigureEvents(); ``` -------------------------------- ### Logging Task Progress Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Explains how to integrate Coravel's queue logging with the .NET Core 'ILogger' interface to track task progress. ```csharp var provider = app.ApplicationServices; provider .ConfigureQueue() .LogQueuedTaskProgress(provider.GetService>()); ``` -------------------------------- ### Scaffold Mailer Views Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Cli/README.md Scaffolds the required views for the Coravel Mailer feature. ```bash coravel mail install ``` -------------------------------- ### Defining Generic Mailable Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Illustrates how to define a generic Mailable class that can be extended for on-the-fly configuration. ```csharp public GenericMailable : Mailable { public override void Build() { } } ``` -------------------------------- ### Create New Mailable Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Cli/README.md Generates a new mailable class and its corresponding view for the Coravel Mailer. ```bash coravel mail new [nameOfYourMailable] ``` -------------------------------- ### Basic Email Sending Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Demonstrates how to inject and use the IMailer interface to send emails with a Mailable object. ```csharp private readonly IMailer _mailer; public MyController(IMailer mailer) { this._mailer = mailer; } // Inside a controller action... await this._mailer.SendAsync(new NewUserViewMailable(user)); ``` -------------------------------- ### Visual Testing: Rendering Mailable to HTML Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Explains how to use RenderAsync instead of SendAsync to render a Mailable to HTML for visual testing or browser display. ```csharp // Controller action that returns a Mailable viewable in the browser! public async Task RenderView() { string message = await this._mailer.RenderAsync(new PendingOrderMailable()); return Content(message, "text/html"); } ``` -------------------------------- ### Schedule an Invocable Daily Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Invocables/README.md Demonstrates how to schedule a specific invocable to run daily at a particular hour and on weekdays using Coravel's scheduler. ```csharp scheduler.Schedule() .DailyAtHour(01) .Weekday(); ``` -------------------------------- ### Configure Coravel Scheduler Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Adds the Coravel scheduler service to the .NET Core dependency injection container. ```csharp services.AddScheduler() ``` -------------------------------- ### Force Run Task at App Startup Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Allows a scheduled task to be executed immediately upon application startup, in addition to its regular schedule. This does not override the task's assigned schedule. ```csharp scheduler.Schedule() .Hourly() .Weekday() .RunOnceAtStart(); ``` -------------------------------- ### Coravel Queuing Source: https://github.com/jamesmh/coravel/blob/master/Src/Coravel/readme.md Coravel provides a zero-configuration, in-memory queue to offload long-running tasks from HTTP requests, improving user experience by preventing them from waiting for task completion. ```.NET Core using Coravel.Queuing; public class MyQueueableTask : IQueueable { public Task InvokeAsync(CancellationToken cancellationToken) { Console.WriteLine("Processing background task..."); return Task.CompletedTask; } } // To dispatch a task: var queue = serviceProvider.GetRequiredService(); queue.QueueAsyncTask(); ``` -------------------------------- ### Queuing Cancellable Invocables Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Details how to queue invocables that can be cancelled, either manually or by the system during shutdown, by implementing ICancellableTask. ```csharp var (taskGuid, token) = queue.QueueCancellableInvocable(); // Somewhere else.... token.Cancel(); // In the invocable: public class CancellableInvocable : ICancellableTask { public CancellationToken Token { get; set; } public async Task Invoke() { while(!this.Token.IsCancellationRequested) { await ProcessNextRecord(); } } } ``` -------------------------------- ### Queuing Invocables with Payload Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Illustrates how to queue an Invocable that requires a payload (data) for execution, using the IInvocableWithPayload interface and QueueInvocableWithPayload method. ```csharp public class SendWelcomeUserEmailInvocable : IInvocable, IInvocableWithPayload { public UserModel Payload { get; set; } public async Task Invoke() { // `this.Payload` will be available to use now. } } // ... var userModel = await _userService.Get(userId); queue.QueueInvocableWithPayload(userModel); ``` -------------------------------- ### Register Custom Cache Driver Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Caching/README.md Demonstrates how to register a custom cache driver, such as one for Redis, by implementing the `ICache` interface and passing an instance or a factory function to `AddCache`. ```csharp services.AddCache(new RedisCache()); // Or, if you need the service provider to create your object: services.AddCache(provider => new RedisCache(provider.GetService())); ``` -------------------------------- ### Coravel Mailing Source: https://github.com/jamesmh/coravel/blob/master/Src/Coravel/readme.md Coravel simplifies email sending in .NET Core applications with built-in Razor templates, a flexible API, visual email testing, and support for various drivers including SMTP, log files, and custom mailers. Configuration is managed via `appsettings.json`. ```.NET Core using Coravel.Mail; // Configuration in appsettings.json: // { // "Coravel": { // "Mailing": { // "From": { // "Name": "Your App", // "Address": "noreply@yourdomain.com" // } // } // } // } // Registering the mailing service: services.AddCoravelMailing(); // Sending an email: var mailer = serviceProvider.GetRequiredService(); await mailer .To("recipient@example.com") .Subject("Hello from Coravel!") .View("MyEmailTemplate", new { Name = "World" }) .SendAsync(); ``` -------------------------------- ### Configuring Queue Consummation Delay (appsettings.json) Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Illustrates how to set the delay between queue consumptions using the 'appsettings.json' configuration file. The default is 30 seconds. ```json { "Coravel": { "Queue": { "ConsummationDelay": 1 } } } ``` -------------------------------- ### Inject ICache Service Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Caching/README.md Demonstrates how to inject the `ICache` interface into a class constructor for use within your application. This allows you to interact with the caching system. ```csharp private ICache _cache; public CacheController(ICache cache) { this._cache = cache; } ``` -------------------------------- ### Configure .NET Project for Razor Views Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Configures a .NET project, especially for shared libraries, to compile Razor views at build time. This involves using the .NET Core 3.1+ SDK for Razor and enabling Razor support for MVC. ```xml True ``` -------------------------------- ### Custom Mailer Implementation and Configuration Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Demonstrates how to implement a custom mailer by inheriting from ICanSendMail and configuring it using dependency injection. This allows for custom sending logic, such as using an HTTP API. ```csharp public class MyHttpApiCustomMailer : ICanSendMail { private readonly IHttpClient _httpClient; public MyHttpApiCustomMailer(IHttpClientFactory httpFactory) { this._httpClient = httpFactory.CreateHttpClient("MailApi"); } public async Task SendAsync(MessageBody message, string subject, IEnumerable to, MailRecipient from, MailRecipient replyTo, IEnumerable cc, IEnumerable bcc, IEnumerable attachments = null, MailRecipient sender = null) { // Code that uses the HttpClient to send mail via an HTTP API. } } // In Program.cs: var builder = WebApplication.CreateBuilder(args); builder.Services.AddScoped(); builder.AddCustomMailer(); ``` -------------------------------- ### Configuring Queue Consummation Delay (Programmatically) Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Queuing/README.md Demonstrates how to programmatically adjust the queue's consummation delay using the 'AddQueue' method in the service configuration. This setting takes precedence over the configuration file. ```csharp services.AddQueue(queueOptions => { // Consume queue every 5 seconds. queueOptions.ConsummationDelay = 5; }); ``` -------------------------------- ### Coravel Task Scheduling Source: https://github.com/jamesmh/coravel/blob/master/Src/Coravel/readme.md Coravel allows developers to set up scheduled tasks directly within their .NET Core application code using a fluent syntax, eliminating the need for external cron job or Task Scheduler configurations. ```.NET Core using Coravel.Invocable; using Coravel.Scheduling.Schedule; public class MyTask : IInvocable { public Task InvokeAsync(CancellationToken cancellationToken) { Console.WriteLine("Hello from Coravel!"); return Task.CompletedTask; } } // In your Startup.cs or Program.cs: services.AddCoravel( "DefaultConnection", // Or your connection string $ ``` -------------------------------- ### Email Link Button Component (Basic) Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Shows how to use the EmailLinkButton Razor component to create a clickable button with a specified text and URL. ```html @await Component.InvokeAsync("EmailLinkButton", new { text = "click me", url = "www.google.com" }) ``` -------------------------------- ### Create Coravel Event Listener Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Events/README.md Implements an event listener by inheriting from `IListener`, where `TEvent` is the specific event type to listen for. The `HandleAsync` method contains the logic to be executed when the event is broadcast. ```csharp public class TweetNewPost : IListener { private TweetingService _tweeter; public TweetNewPost(TweetingService tweeter) { this._tweeter = tweeter; } public async Task HandleAsync(BlogPostCreated broadcasted) { var post = broadcasted.Post; await this._tweeter.TweetNewPost(post); } } ``` -------------------------------- ### Global Mailer Configuration Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Configures global settings for Coravel's Mailer, including logo, company address, company name, and primary color for email templates. These settings are applied via the appsettings.json file. ```json { "Coravel": { "Mail": { "LogoSrc": "https://www.google.ca/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png", "CompanyAddress": "1111 My Company's Address", "CompanyName": "My Company's Name", "PrimaryColor": "#539be2" } } } ``` -------------------------------- ### Create Coravel Event Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Events/README.md Defines a custom event by implementing the `IEvent` interface. Events are data objects that carry information about what occurred in the application. ```csharp public class BlogPostCreated : IEvent { public BlogPost Post { get; set; } public BlogPostCreated(BlogPost post) { this.Post = post; } } ``` -------------------------------- ### Creating a Custom Mailable Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Demonstrates how to create a custom Mailable class in C# that inherits from Coravel's Mailable. This class encapsulates the logic for a specific email type, such as a new user sign-up notification, and can be associated with a model. ```csharp using Coravel.Mailer.Mail; using App.Models; namespace App.Mailables { public class NewUserViewMailable : Mailable { private UserModel _user; public NewUserViewMailable(UserModel user) => this._user = user; public override void Build() { this.To(this._user) .From("from@test.com") .View("~/Views/Mail/NewUser.cshtml", this._user); } } } ``` -------------------------------- ### Sending Inline Mailable with View and Model Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Shows how to send an email using an inline Mailable, specifying a view path and passing a view model. This is useful for creating emails on-the-fly without defining a separate Mailable class. ```csharp public async Task SendMyEmail() { UserModel user = new UserModel() { Email = "FromUserModel@test.com", Name = "Coravel Test Person" }; await this._mailer.SendAsync( Mailable.AsInline() .To(user) .From("from@test.com") .View("~/Views/Mail/NewUser.cshtml", user) ); return Ok(); } ``` -------------------------------- ### Create New Event and Listener Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Cli/README.md Generates a new event class and a corresponding listener class. If the event already exists, only the new listener is created. ```bash coravel event new [eventName] [listenerName] ``` ```bash coravel event new UserCreatedEvent SendUserCreatedEmailListener ``` ```bash coravel event new UserCreatedEvent StartBillingUserListener ``` -------------------------------- ### Logging Tick Catch Up Configuration Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Enables Coravel to log when it replays missed timer ticks due to system overload or resource constraints. This is configured in appsettings.json. ```json { "Coravel": { "Schedule": { "LogTickCatchUp": true } } } ``` -------------------------------- ### Create New Invocable Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Cli/README.md Generates a new Invocable class, typically placed in the './Invocables' directory. ```bash coravel invocable new [nameOfYourInvocable] ``` -------------------------------- ### Register Invocables with Dependency Injection Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Invocables/README.md Shows how to register custom invocable classes with the .NET Core dependency injection container, making them available for execution by Coravel. ```csharp services.AddTransient(); services.AddTransient(); ``` -------------------------------- ### Run Task Daily at Specific Hour Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Schedules a task to run once every day at a specified hour and minute. ```csharp scheduler.Schedule( () => Console.WriteLine("Daily at 1 pm.") ) .DailyAtHour(13); // Or .DailyAt(13, 00) ``` -------------------------------- ### Configuring Email Sender Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Details how to specify the sender of an email using the `From()` method. It supports providing just the email address or a `MailRecipient` object which includes both the email address and sender name. Global sender configuration is also supported via `appsettings.json`. ```csharp From("test@test.com") ``` ```csharp From(new MailRecipient(email, name)) ``` ```json { "Coravel": { "Mail": { "From":{ "Address": "global@from.com", "Name": "My Company" } } } } ``` -------------------------------- ### Schedule an Async Task Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Schedules an asynchronous method or Func to run at a specified interval. The provided method must be awaitable. ```csharp scheduler.ScheduleAsync(async () => { await Task.Delay(500); Console.WriteLine("async task"); }) .EveryMinute(); ``` -------------------------------- ### Configure FileLog Mailer Driver Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Configures Coravel to use the FileLog driver for sending emails, which writes emails to a 'mail.log' file. This is useful for development and testing. ```json { "Coravel": { "Mail": { "Driver": "FileLog" } } } ``` -------------------------------- ### Coravel Scheduling Intervals Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Defines various methods for scheduling tasks at different time intervals, such as every second, every minute, hourly, daily, and monthly. It also includes methods for specific times within an hour or day. ```APIDOC Schedule: EverySecond() Runs the task every second. EveryFiveSeconds() Runs the task every five seconds. EveryTenSeconds() Runs the task every ten seconds. EveryFifteenSeconds() Runs the task every fifteen seconds. EveryThirtySeconds() Runs the task every thirty seconds. EverySeconds(int seconds) Runs the task every specified number of seconds. EveryMinute() Runs the task once a minute. EveryFiveMinutes() Runs the task every five minutes. EveryTenMinutes() Runs the task every ten minutes. EveryFifteenMinutes() Runs the task every fifteen minutes. EveryThirtyMinutes() Runs the task every thirty minutes. Hourly() Runs the task every hour. HourlyAt(int minute) Runs the task at a specific minute past every hour. Daily() Runs the task once a day at midnight. DailyAtHour(int hour) Runs the task once a day at a specific hour (UTC). DailyAt(int hour, int minute) Runs the task once a day at a specific hour and minute (UTC). Weekly() Runs the task once a week. Monthly() Runs the task once a month (at midnight on the 1st day of the month). Cron(string cronExpression) Runs the task using a Cron expression. ``` -------------------------------- ### Coravel Event Broadcasting Source: https://github.com/jamesmh/coravel/blob/master/Src/Coravel/readme.md Coravel's event broadcasting facilitates the creation of maintainable applications with loosely coupled components by enabling events to be broadcast and handled by interested listeners. ```.NET Core using Coravel.Events; public class MyEvent {} public class MyEventListener : IEventListener { public Task HandleAsync(MyEvent broadcasted, CancellationToken cancellationToken) { Console.WriteLine("Event received!"); return Task.CompletedTask; } } // Registering the event broadcasting: services.AddCoravelEvents(); services.Register(); // Broadcasting an event: var events = serviceProvider.GetRequiredService(); events.Broadcast(new MyEvent()); ``` -------------------------------- ### Configure Smtp Mailer Driver Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Configures Coravel to use the SMTP driver for sending emails. Requires specifying the SMTP host, port, username, and password. ```json { "Coravel": { "Mail": { "Driver": "SMTP", "Host": "smtp.mailtrap.io", "Port": 2525, "Username": "[insert]", "Password": "[insert]" } } } ``` -------------------------------- ### Enable In-Memory Caching Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Caching/README.md Enables the default in-memory caching functionality in your .NET Core application's services configuration. This is the first step to using Coravel's caching features. ```csharp services.AddCache(); ``` -------------------------------- ### Coravel Day Constraints Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Allows for chaining day constraints to scheduled tasks, specifying which days of the week the task should run. Supports individual days, weekdays, and weekends, and can be combined. ```APIDOC DayConstraints: Monday() Restricts the schedule to run only on Mondays. Tuesday() Restricts the schedule to run only on Tuesdays. Wednesday() Restricts the schedule to run only on Wednesdays. Thursday() Restricts the schedule to run only on Thursdays. Friday() Restricts the schedule to run only on Fridays. Saturday() Restricts the schedule to run only on Saturdays. Sunday() Restricts the schedule to run only on Sundays. Weekday() Restricts the schedule to run only on weekdays (Monday to Friday). Weekend() Restricts the schedule to run only on weekends (Saturday and Sunday). Chaining Example: Monday().Wednesday() Runs the task on Mondays and Wednesdays. ``` -------------------------------- ### Coravel Caching Source: https://github.com/jamesmh/coravel/blob/master/Src/Coravel/readme.md Coravel offers an easy-to-use API for caching in .NET Core applications. It defaults to an in-memory cache but supports database drivers for more robust caching strategies. ```.NET Core using Coravel.Caching; // Registering the cache service (example with in-memory): services.AddCoravelCaching(); // Using the cache: var cache = serviceProvider.GetRequiredService(); // Set a value await cache.SetAsync("myKey", "myValue", TimeSpan.FromMinutes(5)); // Get a value var value = await cache.GetAsync("myKey"); ``` -------------------------------- ### Schedule Daily Job Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Schedules the previously defined `SendDailyReportsEmailJob` to run on a daily basis using Coravel's scheduler. ```csharp scheduler .Schedule() .Daily(); ``` -------------------------------- ### Schedule a Synchronous Task Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Schedules a synchronous method or Func to run at a specified interval. Use this for non-async operations. ```csharp scheduler.Schedule( () => Console.WriteLine("Scheduled task.") ) .EveryMinute(); ``` -------------------------------- ### Email Link Button Component (Custom Colors) Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Demonstrates customizing the EmailLinkButton component with background and text colors using hex values. ```html @await Component.InvokeAsync("EmailLinkButton", new { text = "click me", url = "www.google.com", backgroundColor = "#333" }) ``` -------------------------------- ### Schedule an Invocable Task Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Schedules a registered Invocable class to run at a specified interval. ```csharp scheduler .Schedule() .EveryTenMinutes(); ``` -------------------------------- ### Sending Inline Mailable with HTML and Text Content Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Demonstrates sending an email with inline HTML and plain text content. This method is suitable when a specific view or model is not required, allowing direct specification of the email body. ```csharp public async Task SendMyEmail() { UserModel user = new UserModel() { Email = "FromUserModel@test.com", Name = "Coravel Test Person" }; await this._mailer.SendAsync( Mailable.AsInline() .To(user) .From("from@test.com") .Html($"

Welcome {user.Name}

") .Text($"Welcome {user.Name}") ); return Ok(); } ``` -------------------------------- ### Run Task on First Day of Month Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Schedules a task to run at midnight on the first day of each month using a cron expression. ```csharp scheduler.Schedule( () => Console.WriteLine("First day of the month.") ) .Cron("0 0 1 * *"); // At midnight on the 1st day of each month. ``` -------------------------------- ### Configuring Email Recipients Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Explains how to specify email recipients using the `To()` method. It supports various overloads, including single email addresses, collections of email addresses, `MailRecipient` objects, and collections of `MailRecipient` objects. ```csharp To("test@test.com") ``` ```csharp To(IEnumerable) ``` ```csharp To(MailRecipient) ``` ```csharp To(IEnumerable) ``` -------------------------------- ### Coravel Zoned Schedules Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Enables scheduling tasks to run according to a specific time zone by using the `Zoned` method with a `TimeZoneInfo` object. Note that `TimeZoneInfo` creation varies by OS and daylight saving time can cause unexpected behavior. ```csharp scheduler .Schedule() .DailyAt(13, 30) .Zoned(TimeZoneInfo.Local); ``` -------------------------------- ### Run Job Once Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Schedules a job to run only the first time it becomes due. After the initial execution, the job is automatically unscheduled. ```csharp scheduler .Schedule() .Hourly() .Once(); ``` -------------------------------- ### Adding HTML Content to Mailable Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Illustrates how to add raw HTML content to an email using the `Html(string html)` method within a Mailable's `Build()` method. This method is typically used when the Mailable is typed with `string`. ```csharp public override void Build() { this.To(this._user) .From("from@test.com") .Html(someHtml); } ``` -------------------------------- ### Schedule an Invocable with Parameters Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Scheduler/README.md Schedules an Invocable class with specific parameters. These invocables should not be registered with the DI container. ```csharp private class BackupDatabaseTableInvocable : IInvocable { private DbContext _dbContext; private string _tableName; public BackupDatabaseTableInvocable(DbContext dbContext, string tableName) { this._dbContext = dbContext; // Injected via DI. this._tableName = tableName; // injected via schedule configuration (see next code block). } public Task Invoke() { // Do the logic. } } // Configuration example: scheduler .ScheduleWithParams("[dbo].[Users]") .Daily(); scheduler .ScheduleWithParams("[dbo].[Products]") .EveryHour(); ``` -------------------------------- ### Adding Plain Text Content to Mailable Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Mailing/README.md Demonstrates how to add a plain text version of an email using the `Text(string plainText)` method. This complements the HTML content, providing a fallback for email clients that do not support HTML. ```csharp public override void Build() { this.To(this._user) .From("from@test.com") .Html(someHtml) .Text(plainText); } ``` -------------------------------- ### Trigger Long Running Calculation via Queue Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Invocables/README.md Illustrates how to trigger a potentially long-running calculation, implemented as an invocable, to be processed in the background using Coravel's queuing mechanism. ```csharp await _queue.QueueAsyncTask(); ``` -------------------------------- ### Cache Item with Remember Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Caching/README.md Caches an item for a specified duration using a key. The `Remember` method takes a cache key, a function to retrieve the data, and a TimeSpan for the cache duration. Subsequent calls with the same key will return the cached item. ```csharp string BigDataLocalFunction() { return "Some Big Data"; }; this._cache.Remember("BigDataCacheKey", BigDataLocalFunction, TimeSpan.FromMinutes(10)); ``` -------------------------------- ### Broadcast Event Source: https://github.com/jamesmh/coravel/blob/master/DocsV2/docs/Events/README.md Broadcasts an event using the `IDispatcher` service. This triggers all registered listeners for the specified event type. ```csharp public class BlogController : Controller { private IDispatcher _dispatcher; public BlogController(IDispatcher dispatcher) { this._dispatcher = dispatcher; } public async Task NewPost(BlogPost newPost) { var postCreated = new BlogPostCreated(newPost); await _dispatcher.Broadcast(postCreated); // All listeners will fire. } } ```