### Basic Console Logging in Hangfire Job Source: https://github.com/pieceofsummer/hangfire.console/blob/master/README.md Demonstrates how to write a simple "Hello, world!" message to the Hangfire console log from within a job method. It requires the PerformContext object to be passed as a job argument. ```csharp public void TaskMethod(PerformContext context) { context.WriteLine("Hello, world!"); } ``` -------------------------------- ### Create Progress Bar with Fractional Values Source: https://context7.com/pieceofsummer/hangfire.console/llms.txt Shows how to create a progress bar that accepts and displays fractional (double) values for more precise progress tracking. The display precision is controlled by the ProgressBarDecimalDigits setting. ```csharp public void JobWithFractionalProgress(PerformContext context) { // Named progress bar with fractional (double) values var progress = context.WriteProgressBar("Precision", 0.0, ConsoleTextColor.Yellow); for (double i = 0; i <= 100; i += 0.5) { Thread.Sleep(50); progress.SetValue(i); // Displays based on ProgressBarDecimalDigits setting } } ``` -------------------------------- ### Configure Hangfire.Console in .NET Core Source: https://github.com/pieceofsummer/hangfire.console/blob/master/README.md Sets up Hangfire with SQL Server storage and enables the console logging feature within the .NET Core application's services configuration. This is typically done in the Startup.cs file. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddHangfire(config => { config.UseSqlServerStorage("connectionSting"); config.UseConsole(); }); } ``` -------------------------------- ### Access Hangfire Job Console Output with C# Source: https://context7.com/pieceofsummer/hangfire.console/llms.txt Demonstrates how to use the GetConsoleApi() extension method to retrieve text lines and progress bar data for Hangfire jobs. It covers fetching all lines, filtering for text-only, and filtering for progress bars. Requires Hangfire.Core and a JobStorage implementation. ```csharp public class ConsoleMonitoringExample { private readonly JobStorage _storage; public ConsoleMonitoringExample(JobStorage storage) { _storage = storage; } public void ReadJobConsoleOutput(string jobId) { // Get monitoring API for the job storage using (var monitoringApi = _storage.GetMonitoringApi()) using (var consoleApi = _storage.GetConsoleApi()) { // Get job details to find processing start time var jobDetails = monitoringApi.JobDetails(jobId); var processingState = jobDetails?.History .FirstOrDefault(s => s.StateName == "Processing"); if (processingState == null) { Console.WriteLine("Job has not started processing yet"); return; } // Get all console lines var lines = consoleApi.GetLines(jobId, processingState.CreatedAt, LineType.Any); foreach (var line in lines) { if (line is TextLineDto textLine) { Console.WriteLine("[{0:HH:mm:ss}] {1}", textLine.Timestamp, textLine.Text); } else if (line is ProgressBarDto progressBar) { Console.WriteLine("[{0:HH:mm:ss}] Progress '{1}': {2:F1}%", progressBar.Timestamp, progressBar.Name ?? progressBar.Id.ToString(), progressBar.Progress); } } } } public void GetOnlyTextLines(string jobId, DateTime processingStartTime) { using (var consoleApi = _storage.GetConsoleApi()) { // Filter to get only text lines (no progress bars) var textLines = consoleApi.GetLines(jobId, processingStartTime, LineType.Text); foreach (var line in textLines.Cast()) { Console.WriteLine("{0}: {1}", line.Timestamp, line.Text); } } } public void GetOnlyProgressBars(string jobId, DateTime processingStartTime) { using (var consoleApi = _storage.GetConsoleApi()) { // Filter to get only progress bar states var progressBars = consoleApi.GetLines(jobId, processingStartTime, LineType.ProgressBar); foreach (var bar in progressBars.Cast()) { Console.WriteLine("Progress bar {0} ({1}): {2:F2}%", bar.Id, bar.Name ?? "unnamed", bar.Progress); } } } } // Example usage var storage = JobStorage.Current; var monitor = new ConsoleMonitoringExample(storage); monitor.ReadJobConsoleOutput("job-id-123"); ``` -------------------------------- ### Configure Hangfire Console Feature with C# Source: https://context7.com/pieceofsummer/hangfire.console/llms.txt Shows how to configure Hangfire's console feature using the ConsoleOptions class. This includes settings for data retention (ExpireIn), live update polling (PollInterval), and visual customization (colors, progress bar decimals). Requires Hangfire.Core and a storage provider. ```csharp // Full configuration example with all available options var options = new ConsoleOptions { // Data retention settings ExpireIn = TimeSpan.FromHours(48), // Keep console data for 48 hours FollowJobRetentionPolicy = false, // Use ExpireIn instead of job retention // Live update settings PollInterval = 2000, // Poll every 2 seconds (default: 1000ms) // Visual customization BackgroundColor = "#282c34", // Dark background (default: #0d3163) TextColor = "#abb2bf", // Light gray text (default: #ffffff) TimestampColor = "#98c379", // Green timestamps (default: #00aad7) // Progress bar display ProgressBarDecimalDigits = 2 // Show 2 decimal places (default: 1) }; // Apply configuration GlobalConfiguration.Configuration .UseStorage(new SqlServerStorage("connectionString")) .UseConsole(options); // Validation rules enforced: // - ExpireIn must be >= 1 minute // - PollInterval must be >= 100ms // - ProgressBarDecimalDigits must be 0-3 ``` -------------------------------- ### Configure Hangfire.Console in non-.NET Core Source: https://github.com/pieceofsummer/hangfire.console/blob/master/README.md Configures Hangfire with SQL Server storage and the console logging feature for applications not using .NET Core's Startup.cs. This approach uses the GlobalConfiguration class. ```csharp GlobalConfiguration.Configuration .UseSqlServerStorage("connectionSting") .UseConsole(); ``` -------------------------------- ### Create Multiple Named Progress Bars with Colors Source: https://context7.com/pieceofsummer/hangfire.console/llms.txt Illustrates creating multiple, distinct progress bars, each with a custom name and color, to track different stages of a job concurrently. This provides a clearer visual representation of complex job progress. ```csharp public void JobWithMultipleProgressBars(PerformContext context) { // Create named progress bars with different colors var downloadProgress = context.WriteProgressBar("Download", 0, ConsoleTextColor.Blue); var processProgress = context.WriteProgressBar("Process", 0, ConsoleTextColor.Green); var uploadProgress = context.WriteProgressBar("Upload", 0, ConsoleTextColor.Cyan); // Simulate download phase for (int i = 0; i <= 100; i += 20) { Thread.Sleep(200); downloadProgress.SetValue(i); } context.WriteLine(ConsoleTextColor.Blue, "Download complete!"); // Simulate processing phase for (int i = 0; i <= 100; i += 10) { Thread.Sleep(100); processProgress.SetValue(i); } context.WriteLine(ConsoleTextColor.Green, "Processing complete!"); // Simulate upload phase for (int i = 0; i <= 100; i += 25) { Thread.Sleep(300); uploadProgress.SetValue(i); } context.WriteLine(ConsoleTextColor.Cyan, "Upload complete!"); } ``` -------------------------------- ### Demonstrate Console Colors with ConsoleTextColor Source: https://context7.com/pieceofsummer/hangfire.console/llms.txt Shows how to use predefined color constants from the ConsoleTextColor class to style text output in the console. These colors can be applied using WriteLine() or SetTextColor() methods. ```csharp public void DemonstrateColors(PerformContext context) { // All available predefined colors context.WriteLine(ConsoleTextColor.Black, "Black text"); context.WriteLine(ConsoleTextColor.DarkBlue, "Dark blue text"); context.WriteLine(ConsoleTextColor.DarkGreen, "Dark green text"); context.WriteLine(ConsoleTextColor.DarkCyan, "Dark cyan text"); context.WriteLine(ConsoleTextColor.DarkRed, "Dark red text"); context.WriteLine(ConsoleTextColor.DarkMagenta, "Dark magenta text"); context.WriteLine(ConsoleTextColor.DarkYellow, "Dark yellow text"); context.WriteLine(ConsoleTextColor.Gray, "Gray text"); context.WriteLine(ConsoleTextColor.DarkGray, "Dark gray text"); context.WriteLine(ConsoleTextColor.Blue, "Blue text"); context.WriteLine(ConsoleTextColor.Green, "Green text"); context.WriteLine(ConsoleTextColor.Cyan, "Cyan text"); context.WriteLine(ConsoleTextColor.Red, "Red text"); context.WriteLine(ConsoleTextColor.Magenta, "Magenta text"); context.WriteLine(ConsoleTextColor.Yellow, "Yellow text"); context.WriteLine(ConsoleTextColor.White, "White text"); // Color values (hex): // Black=#000000, DarkBlue=#000080, DarkGreen=#008000, DarkCyan=#008080 // DarkRed=#800000, DarkMagenta=#800080, DarkYellow=#808000, Gray=#c0c0c0 // DarkGray=#808080, Blue=#0000ff, Green=#00ff00, Cyan=#00ffff // Red=#ff0000, Magenta=#ff00ff, Yellow=#ffff00, White=#ffffff } ``` -------------------------------- ### Create and Update a Simple Progress Bar Source: https://context7.com/pieceofsummer/hangfire.console/llms.txt Demonstrates how to create a basic inline progress bar using the WriteProgressBar() extension method and update its value during job execution. This progress bar is visible in the Hangfire Dashboard. ```csharp public void JobWithProgressBar(PerformContext context) { // Create a simple progress bar (starts at 0%) var progress = context.WriteProgressBar(); for (int i = 0; i <= 100; i += 10) { // Simulate work Thread.Sleep(500); // Update progress bar value progress.SetValue(i); context.WriteLine("Completed {0}%", i); } } ``` -------------------------------- ### Configure Hangfire Console Logging with UseConsole() Source: https://context7.com/pieceofsummer/hangfire.console/llms.txt Configures Hangfire to enable console logging using the `UseConsole()` extension method. This method registers necessary filters, dashboard routes, and renderers. It can be called globally or within .NET Core's `AddHangfire` configuration, and supports custom options for retention, polling, and colors. ```csharp // .NET Core Startup.cs configuration public void ConfigureServices(IServiceCollection services) { services.AddHangfire(config => { config.UseSqlServerStorage("Server=localhost;Database=Hangfire;Trusted_Connection=True;"); config.UseConsole(); }); } // Alternative: Global configuration GlobalConfiguration.Configuration .UseSqlServerStorage("Server=localhost;Database=Hangfire;Trusted_Connection=True;") .UseConsole(); // With custom options GlobalConfiguration.Configuration .UseSqlServerStorage("Server=localhost;Database=Hangfire;Trusted_Connection=True;") .UseConsole(new ConsoleOptions { ExpireIn = TimeSpan.FromHours(12), // Keep console sessions for 12 hours FollowJobRetentionPolicy = true, // Expire with parent job (default) PollInterval = 500, // Poll every 500ms for live updates BackgroundColor = "#1e1e1e", // Dark background TextColor = "#d4d4d4", // Light gray text TimestampColor = "#569cd6", // Blue timestamps ProgressBarDecimalDigits = 2 // Show 2 decimal places on progress }); ``` -------------------------------- ### Progress Bar with Enumeration in Hangfire Job Source: https://github.com/pieceofsummer/hangfire.console/blob/master/README.md Demonstrates using the `WithProgress` extension method to automatically update a progress bar while iterating over a collection in a Hangfire job. It simplifies progress tracking for loops. ```csharp public void TaskMethod(PerformContext context) { var bar = context.WriteProgressBar(); foreach (var item in collection.WithProgress(bar)) { // do work } } ``` -------------------------------- ### Basic Progress Bar in Hangfire Job Source: https://github.com/pieceofsummer/hangfire.console/blob/master/README.md Illustrates how to create and update a basic inline progress bar within a Hangfire job. The progress bar is initialized and then its value is set to 100. ```csharp public void TaskMethod(PerformContext context) { // create progress bar var progress = context.WriteProgressBar(); // update value for previously created progress bar progress.SetValue(100); } ``` -------------------------------- ### Write Console Output with WriteLine() Source: https://context7.com/pieceofsummer/hangfire.console/llms.txt Writes text messages to the Hangfire job console using the `WriteLine()` extension method. It supports plain strings, formatted strings with arguments, and colored output via `ConsoleTextColor`. The `PerformContext` is automatically injected by Hangfire. ```csharp public class MyBackgroundJobs { // Basic console output public void SimpleJob(PerformContext context) { context.WriteLine("Starting job execution..."); context.WriteLine("Processing item: {0}", 42); context.WriteLine("User: {0}, Action: {1}", "admin", "login"); context.WriteLine(); // Empty line context.WriteLine("Job completed successfully!"); } // Colored console output public void JobWithColors(PerformContext context) { context.WriteLine(ConsoleTextColor.Green, "SUCCESS: Operation completed"); context.WriteLine(ConsoleTextColor.Yellow, "WARNING: {0} items skipped", 5); context.WriteLine(ConsoleTextColor.Red, "ERROR: Failed to process item {0}", "ABC123"); context.WriteLine(ConsoleTextColor.Cyan, "INFO: Processing took {0}ms", 1500); // Using SetTextColor for multiple lines context.SetTextColor(ConsoleTextColor.DarkGray); context.WriteLine("Debug: Variable x = 10"); context.WriteLine("Debug: Variable y = 20"); context.ResetTextColor(); context.WriteLine("Back to default color"); } } // Enqueue the job (pass null for PerformContext - Hangfire injects it automatically) BackgroundJob.Enqueue(x => x.SimpleJob(null)); BackgroundJob.Enqueue(x => x.JobWithColors(null)); ``` -------------------------------- ### Colored Console Logging in Hangfire Job Source: https://github.com/pieceofsummer/hangfire.console/blob/master/README.md Shows how to write messages to the Hangfire console with specific text colors, such as highlighting errors in red. It uses `SetTextColor` and `ResetTextColor` methods on the PerformContext. ```csharp public void TaskMethod(PerformContext context) { context.SetTextColor(ConsoleTextColor.Red); context.WriteLine("Error!"); context.ResetTextColor(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.