### Hangfire SQL Server Storage and Server Startup Logs Source: https://docs.hangfire.io/en/latest/_sources/getting-started/aspnet-core-applications.rst.txt Example log output indicating the successful installation of Hangfire SQL objects, configuration of SQL Server job storage, and the startup of the Hangfire Server with specified worker count and listening queues. ```bash info: Hangfire.SqlServer.SqlServerStorage[0] Start installing Hangfire SQL objects... Hangfire SQL objects installed. Using job storage: 'SQL Server: .\@AspNetCoreTest' Using the following options for SQL Server job storage: Queue poll interval: 00:00:15. info: Hangfire.BackgroundJobServer[0] Starting Hangfire Server... Using the following options for Hangfire Server: Worker count: 20 Listening queues: 'default' Shutdown timeout: 00:00:15 Schedule polling interval: 00:00:15 ``` -------------------------------- ### Transition: Separate Servers for Old and New Jobs (Default Queue) Source: https://docs.hangfire.io/en/latest/configuration/using-sql-server-with-msmq.html Run two Hangfire Server instances during transition: one for old SQL Server queues and another for new MSMQ queues. This example configures the server for old jobs first, then sets up the global configuration for MSMQ queues and starts the server for new jobs. ```csharp /* This server will process only SQL Server table queues, i.e. old jobs */ var oldStorage = new SqlServerStorage(""); var oldOptions = new BackgroundJobServerOptions(); app.UseHangfireServer(oldOptions, oldStorage); /* This server will process only MSMQ queues, i.e. new jobs */ GlobalConfiguration.Configuration .UseSqlServerStorage("") .UseMsmqQueues(@"FormatName:Direct=OS:localhost\hangfire-{0}"); app.UseHangfireServer(); ``` -------------------------------- ### Install Microsoft.Data.SqlClient Package Source: https://docs.hangfire.io/en/latest/_sources/upgrade-guides/upgrading-to-hangfire-1.8.rst.txt Explicitly install the Microsoft.Data.SqlClient package if it's not referenced by other parts of your application. ```xml ``` -------------------------------- ### Basic Hangfire Console Application Setup Source: https://docs.hangfire.io/en/latest/_sources/getting-started/index.rst.txt This snippet shows a complete Hangfire setup for a console application. It configures SQL Server storage, sets data compatibility, and enqueues a simple console output job. The background job server is started and kept alive until the console input is received. ```csharp using System; using Hangfire; using Hangfire.SqlServer; namespace ConsoleApplication2 { class Program { static void Main() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseColouredConsoleLogProvider() .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Database=Hangfire.Sample; Integrated Security=True;"); BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!")); using (var server = new BackgroundJobServer()) { Console.ReadLine(); } } } } ``` -------------------------------- ### Install Windows Service Source: https://docs.hangfire.io/en/latest/background-processing/processing-jobs-in-windows-service.html Install the Windows Service using the installutil command-line tool. Replace .exe with your actual project executable name. ```bash installutil .exe ``` -------------------------------- ### Install Microsoft.Net.Http Package Source: https://docs.hangfire.io/en/latest/_sources/tutorials/highlight.rst.txt Install the Microsoft.Net.Http NuGet package to enable making HTTP requests for code highlighting. ```powershell Install-Package Microsoft.Net.Http ``` -------------------------------- ### Install Windows Service Source: https://docs.hangfire.io/en/latest/_sources/background-processing/processing-jobs-in-windows-service.rst.txt Use the installutil utility to install your Windows Service project. Replace .exe with the actual name of your executable. ```powershell installutil .exe ``` -------------------------------- ### Install Entity Framework Package Source: https://docs.hangfire.io/en/latest/_sources/tutorials/highlight.rst.txt Use this PowerShell command in the Package Manager Console to install the Entity Framework NuGet package. ```powershell Install-Package EntityFramework ``` -------------------------------- ### Install MiniProfiler Package Source: https://docs.hangfire.io/en/latest/_sources/tutorials/highlight.rst.txt Command to install the MiniProfiler NuGet package for application profiling. ```csharp Install-Package MiniProfiler ``` -------------------------------- ### Instantiate and Start Hangfire Server Source: https://docs.hangfire.io/en/latest/_sources/background-processing/processing-background-jobs.rst.txt Create an instance of Hangfire Server and start it. Advanced options like explicit job storage can be configured via constructor overrides. ```csharp var server = new BackgroundJobServer(); ``` -------------------------------- ### Install Performance Counters Source: https://docs.hangfire.io/en/latest/deployment-to-production/performance-counters.html Run this command on every machine to install the Hangfire performance counters. Use 'upc' to uninstall. ```bash hangfire-perf ipc ``` ```bash hangfire-perf upc ``` -------------------------------- ### Initial HomeController Setup Source: https://docs.hangfire.io/en/latest/_sources/tutorials/highlight.rst.txt This is the basic structure of the HomeController after scaffolding an empty MVC 5 controller. It includes a single Index action returning a view. ```csharp public class HomeController : Controller { public ActionResult Index() { return View(); } } ``` -------------------------------- ### Run ASP.NET Core Application Source: https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html Execute this command in your project directory to start the application. Visual Studio users can also use the F5 key. ```bash dotnet run ``` -------------------------------- ### Install Hangfire.Core Package Source: https://docs.hangfire.io/en/latest/_sources/background-processing/processing-jobs-in-console-app.rst.txt Install the core Hangfire package using the Package Manager Console. ```powershell PM> Install-Package Hangfire.Core ``` -------------------------------- ### Set Application Pool Start Mode to Always Running Source: https://docs.hangfire.io/en/latest/_sources/deployment-to-production/making-aspnet-app-always-running.rst.txt Configure the application pool's start mode to 'Always Running' in Advanced Settings to ensure it starts without waiting for the first request. ```text Set start mode to “Always Running†. ``` -------------------------------- ### Run ASP.NET Core Application Source: https://docs.hangfire.io/en/latest/_sources/getting-started/aspnet-core-applications.rst.txt Command to start an ASP.NET Core application from the command line. This is typically used for development and testing. ```bash dotnet run ``` -------------------------------- ### Install Performance Counters Source: https://docs.hangfire.io/en/latest/_sources/deployment-to-production/performance-counters.rst.txt Run this command to install Hangfire performance counters on a machine. This needs to be done on every machine where Hangfire is deployed. ```powershell hangfire-perf ipc ``` -------------------------------- ### Install Hangfire.Throttling via Package Manager Console Source: https://docs.hangfire.io/en/latest/_sources/background-processing/throttling.rst.txt Install the Hangfire.Throttling package using the Install-Package command in the Package Manager Console. This is an alternative installation method. ```powershell Install-Package Hangfire.Throttling ``` -------------------------------- ### Install Hangfire.Pro Package Source: https://docs.hangfire.io/en/latest/_sources/background-methods/using-batches.rst.txt Installs the Hangfire.Pro package using the NuGet Package Manager Console. ```powershell PM> Install-Package Hangfire.Pro ``` -------------------------------- ### Configure Application Initialization for ASP.NET Core Source: https://docs.hangfire.io/en/latest/_sources/deployment-to-production/making-aspnet-app-always-running.rst.txt Configure application initialization settings in IIS to ensure the application starts and initializes correctly after a restart. Specify the host name and initialization page. ```text doAppInitAfterRestart: **True** Open up the *Collection...* ellipsis. On the next window, click *Add* and enter the following: hostName: **{URL host for your Hangfire application}** initializationPage: **{path for your Hangfire dashboard, like /hangfire}** ``` -------------------------------- ### Start a Batch with Multiple Child Batches Source: https://docs.hangfire.io/en/latest/background-methods/using-batches.html Shows how to initiate a parent batch that spawns two distinct child batches. This allows for parallel execution of different sets of jobs within a single atomic transaction. ```csharp var antecedentId = BatchJob.StartNew(batch => { batch.StartNew(inner => inner.Enqueue(() => Console.WriteLine("First"))); batch.StartNew(inner => inner.Enqueue(() => Console.WriteLine("Second"))); }); ``` -------------------------------- ### Install NLog Package Source: https://docs.hangfire.io/en/latest/_sources/tutorials/send-email.rst.txt Install the NLog logging framework using the NuGet package manager. This is a prerequisite for using NLog with Hangfire. ```powershell Install-Package NLog ``` -------------------------------- ### Start Hangfire Server Source: https://docs.hangfire.io/en/latest/index.html Instantiate and start the BackgroundJobServer to begin processing background jobs. The server runs in dedicated background threads and manages job fetching and storage cleanup. Use a 'using' statement to ensure proper disposal. ```csharp using (new BackgroundJobServer()) { Console.WriteLine("Hangfire Server started. Press ENTER to exit..."); Console.ReadLine(); } ``` -------------------------------- ### Configure MiniProfiler in Global.asax.cs Source: https://docs.hangfire.io/en/latest/_sources/tutorials/highlight.rst.txt Add MiniProfiler start and stop calls to the Application_BeginRequest and Application_EndRequest methods in Global.asax.cs. ```csharp // ~/Global.asax.cs public class MvcApplication : HttpApplication { /* ... */ protected void Application_BeginRequest() { StackExchange.Profiling.MiniProfiler.Start(); } protected void Application_EndRequest() { StackExchange.Profiling.MiniProfiler.Stop(); } } ``` -------------------------------- ### Install Hangfire Packages Source: https://docs.hangfire.io/en/latest/getting-started/aspnet-applications.html Install the necessary Hangfire core, SQL Server, ASP.NET integration, and SQL client packages using the Package Manager Console. ```powershell PM> Install-Package Hangfire.Core PM> Install-Package Hangfire.SqlServer PM> Install-Package Hangfire.AspNet PM> Install-Package Microsoft.Data.SqlClient ``` -------------------------------- ### Install Hangfire NuGet Packages Source: https://docs.hangfire.io/en/latest/_sources/getting-started/aspnet-applications.rst.txt Install the core Hangfire packages and the SQL Server integration package using the Package Manager Console. ```powershell PM> Install-Package Hangfire.Core PM> Install-Package Hangfire.SqlServer PM> Install-Package Hangfire.AspNet PM> Install-Package Microsoft.Data.SqlClient ``` -------------------------------- ### Install Hangfire.Pro.Redis via Package Manager Console Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-redis.rst.txt Install the Hangfire.Pro.Redis package using the Package Manager Console in Visual Studio. ```powershell PM> Install-Package Hangfire.Pro.Redis ``` -------------------------------- ### Install Hangfire.Throttling via .csproj Source: https://docs.hangfire.io/en/latest/_sources/background-processing/throttling.rst.txt Add the Hangfire.Throttling package to your project by including it in your .csproj file. This is the recommended method for new project types. ```xml ``` -------------------------------- ### Create Batch with Continuation for Processing Large Lists Source: https://docs.hangfire.io/en/latest/_sources/background-methods/using-batches.rst.txt Example of creating a batch to process a large list and then continuing with a notification batch. ```csharp var batchId = BatchJob.StartNew(batch => batch.Enqueue(() => ProcessHugeList(batch.Id, ListId))); BatchJob.ContinueBatchWith(batchId, batch => batch.Enqueue(() => SendNotification(ListId))); ``` -------------------------------- ### Install Postal NuGet Package Source: https://docs.hangfire.io/en/latest/_sources/tutorials/send-email.rst.txt Installs the Postal.Mvc5 NuGet package, which is required for using the Postal library in an ASP.NET MVC 5 project. ```powershell Install-Package Postal.Mvc5 ``` -------------------------------- ### Install Hangfire Core and SQL Server Packages Source: https://docs.hangfire.io/en/latest/_sources/getting-started/index.rst.txt Use the dotnet CLI to add the necessary Hangfire packages to your project. This includes the core package and the SQL Server implementation. ```bash dotnet add package Hangfire.Core dotnet add package Hangfire.SqlServer dotnet add package Microsoft.Data.SqlClient ``` -------------------------------- ### Install Hangfire.SqlServer.MSMQ Package Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-sql-server-with-msmq.rst.txt Install the MSMQ support package for Hangfire SQL Server using the NuGet Package Manager Console. ```powershell PM> Install-Package Hangfire.SqlServer.Msmq ``` -------------------------------- ### EmailSender Class with Direct Dependency Instantiation Source: https://docs.hangfire.io/en/latest/_sources/background-methods/passing-dependencies.rst.txt An example of an EmailSender class that directly instantiates its dependencies within the method. This approach is less testable. ```csharp public class EmailSender { public void Send(int userId, string message) { var dbContext = new DbContext(); var emailService = new EmailService(); // Some processing logic } } ``` -------------------------------- ### Configure Global.asax.cs for Hangfire Source: https://docs.hangfire.io/en/latest/_sources/deployment-to-production/making-aspnet-app-always-running.rst.txt Ensures Hangfire server starts on application start and stops on application end. This is crucial for environments without auto-start. ```csharp public class Global : HttpApplication { protected void Application_Start(object sender, EventArgs e) { HangfireBootstrapper.Instance.Start(); } protected void Application_End(object sender, EventArgs e) { HangfireBootstrapper.Instance.Stop(); } } ``` -------------------------------- ### Basic Hangfire Console Application Setup Source: https://docs.hangfire.io/en/latest/getting-started/index.html This snippet shows how to configure Hangfire with SQL Server storage and enqueue a simple background job. It includes the necessary using statements and the main program logic. ```csharp using System; using Hangfire; using Hangfire.SqlServer; namespace ConsoleApplication2 { class Program { static void Main() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseColouredConsoleLogProvider() .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Database=Hangfire.Sample; Integrated Security=True;"); BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!")); using (var server = new BackgroundJobServer()) { Console.ReadLine(); } } } } ``` -------------------------------- ### Configure Application Pool and Service AutoStart Source: https://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html Modify the applicationHost.config file to set the application pool to 'AlwaysRunning' and enable Service AutoStart Providers. This ensures your application starts automatically with IIS. ```xml ``` -------------------------------- ### Implement IProcessHostPreloadClient for Hangfire Source: https://docs.hangfire.io/en/latest/_sources/deployment-to-production/making-aspnet-app-always-running.rst.txt This class is called by the Windows Process Activation service during startup and after Application pool recycles to start the Hangfire server. ```csharp public class ApplicationPreload : System.Web.Hosting.IProcessHostPreloadClient { public void Preload(string[] parameters) { HangfireBootstrapper.Instance.Start(); } } ``` -------------------------------- ### Install Hangfire.SqlServer NuGet Package Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-sql-server.rst.txt Add the Hangfire.SqlServer NuGet package to your project to enable SQL Server storage. This is often a dependency of the main Hangfire package. ```xml ``` -------------------------------- ### NLog Configuration File Source: https://docs.hangfire.io/en/latest/_sources/tutorials/send-email.rst.txt Configure NLog by creating an NLog.config file in the project root. This setup defines targets for file and event log logging, including layout and archiving rules. ```xml ``` -------------------------------- ### Install Hangfire NuGet Packages Source: https://docs.hangfire.io/en/latest/getting-started/index.html Add the necessary Hangfire NuGet packages to your project using the .NET CLI. This includes Hangfire.Core, Hangfire.SqlServer, and a SQL client package. ```bash dotnet add package Hangfire.Core dotnet add package Hangfire.SqlServer dotnet add package Microsoft.Data.SqlClient ``` -------------------------------- ### Create HangFire User and Schema Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-sql-server.rst.txt Example SQL script to create a dedicated user and schema for Hangfire, granting minimal necessary privileges. ```sql CREATE USER [HangFire] WITH PASSWORD = 'strong_password_for_hangfire' GO IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE [name] = 'HangFire') EXEC ('CREATE SCHEMA [HangFire]') GO ALTER AUTHORIZATION ON SCHEMA::[HangFire] TO [HangFire] GO GRANT CREATE TABLE TO [HangFire] GO ``` -------------------------------- ### Configure Hangfire Server with OWIN Extension Source: https://docs.hangfire.io/en/latest/_sources/background-processing/processing-jobs-in-web-app.rst.txt This snippet demonstrates how to use Hangfire's OWIN extension method to automatically configure and start the background job server. This is a simpler approach for OWIN-based applications. ```csharp public class Startup { public void Configuration(IAppBuilder app) { app.UseHangfireServer(); } } ``` -------------------------------- ### Initialize Hangfire Server in Console App Source: https://docs.hangfire.io/en/latest/_sources/background-processing/processing-jobs-in-console-app.rst.txt Configure Hangfire to use SQL Server storage and start the background job server. The application will keep running until a key is pressed. ```csharp using System; using Hangfire; using Hangfire.SqlServer; namespace ConsoleApplication2 { class Program { static void Main() { GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string"); using (var server = new BackgroundJobServer()) { Console.WriteLine("Hangfire Server started. Press any key to exit..."); Console.ReadKey(); } } } } ``` -------------------------------- ### Install Hangfire NuGet Packages Source: https://docs.hangfire.io/en/latest/_sources/getting-started/aspnet-core-applications.rst.txt Add the necessary Hangfire NuGet packages to your project's .csproj file. Ensure you are using compatible versions. ```xml ``` -------------------------------- ### Initialize Hangfire Server in global.asax.cs Source: https://docs.hangfire.io/en/latest/_sources/background-processing/processing-jobs-in-web-app.rst.txt Use this snippet to initialize Hangfire's SQL Server storage and start the BackgroundJobServer in an ASP.NET application's global.asax.cs file. Ensure the server instance is disposed on application end for graceful shutdown. ```csharp using System; using System.Web; using Hangfire; namespace WebApplication1 { public class Global : HttpApplication { private BackgroundJobServer _backgroundJobServer; protected void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configuration .UseSqlServerStorage("DbConnection"); _backgroundJobServer = new BackgroundJobServer(); } protected void Application_End(object sender, EventArgs e) { _backgroundJobServer.Dispose(); } } } ``` -------------------------------- ### Continue a Batch with Multiple Nested Batches Source: https://docs.hangfire.io/en/latest/background-methods/using-batches.html Demonstrates creating continuation batches for a previously started batch. This allows for sequential execution of tasks after the antecedent batch completes. ```csharp BatchJob.ContinueBatchWith(antecedentId, continuation => { continuation.StartNew(inner => inner.Enqueue(() => Console.WriteLine("First"))); continuation.StartNew(inner => inner.Enqueue(() => Console.WriteLine("Second"))); }); ``` -------------------------------- ### Create a Batch Job with Throttling Source: https://docs.hangfire.io/en/latest/_sources/background-processing/throttling.rst.txt Construct a batch job where the start and end methods use Mutex or Semaphore attributes to throttle the entire batch. Use BatchContinuationOptions.OnAnyFinishedState to ensure the throttler is released even if jobs fail. ```csharp BatchJob.StartNew(batch => { var startId = batch.Enqueue(() => StartBatch()); var bodyId = batch.ContinueJobWith(startId, nestedBatch => { for (var i = 0; i < 5; i++) nestedBatch.Enqueue(() => Thread.Sleep(5000)); }); batch.ContinueBatchWith( bodyId, () => CompleteBatch(), options: BatchContinuationOptions.OnAnyFinishedState); }); ``` -------------------------------- ### Configure Application Initialization in IIS Source: https://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html Configure the `applicationInitialization` settings in IIS to ensure the application initializes after a restart. This involves setting `doAppInitAfterRestart` and adding initialization details. ```text doAppInitAfterRestart: **True** Open up the _Collection…_ ellipsis. On the next window, click _Add_ and enter the following: hostName: **{URL host for your Hangfire application}** initializationPage: **{path for your Hangfire dashboard, like /hangfire}** ``` -------------------------------- ### IIS Application Pool Start Mode and Idle Time-Out Source: https://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html Set the application pool's start mode to 'Always Running' and Idle Time-Out to 0 minutes. This ensures the worker process starts immediately and remains active. ```text Set start mode to “Always Running”. Setting the start mode to “Always Running” tells IIS to start a worker process for your application right away, without waiting for the initial request. Set Idle Time-Out (minutes) to 0. ``` -------------------------------- ### Creating a Batch of Jobs Atomically Source: https://docs.hangfire.io/en/latest/_sources/background-methods/using-batches.rst.txt Shows how to use BatchJob.StartNew to create a batch of background jobs atomically, ensuring all or none are created successfully. ```csharp BatchJob.StartNew(x => { for (var i = 0; i < 1000; i++) { x.Enqueue(() => SendEmail(i)); } }); ``` -------------------------------- ### Reference System.Data.SqlClient Package Source: https://docs.hangfire.io/en/latest/_sources/upgrade-guides/upgrading-to-hangfire-1.8.rst.txt If you prefer to keep using System.Data.SqlClient for compatibility, reference it explicitly. ```xml ``` -------------------------------- ### Enqueueing Multiple Jobs Without Batches (Old Way) Source: https://docs.hangfire.io/en/latest/_sources/background-methods/using-batches.rst.txt Demonstrates the traditional approach to enqueuing multiple jobs, highlighting the challenges in handling exceptions and preventing duplicates. ```csharp for (var i = 0; i < 1000; i++) { BackgroundJob.Enqueue(() => SendEmail(i)); // What to do on exception? } ``` -------------------------------- ### Install MiniProfiler NuGet Package Source: https://docs.hangfire.io/en/latest/tutorials/highlight.html Installs the MiniProfiler package via the NuGet Package Manager Console. This package is used for application profiling. ```powershell Install-Package MiniProfiler ``` -------------------------------- ### Create and Attach Job to an Empty Batch Source: https://docs.hangfire.io/en/latest/_sources/background-methods/using-batches.rst.txt Demonstrates creating an empty batch and then attaching a background job to it. Initially empty batches are considered completed. ```csharp var batchId = BatchJob.StartNew(batch => {}); BatchJob.Attach(batchId, batch => batch.Enqueue(() => Console.WriteLine("Hello, world!"))); ``` -------------------------------- ### Enable Service AutoStart Provider Source: https://docs.hangfire.io/en/latest/_sources/deployment-to-production/making-aspnet-app-always-running.rst.txt Enable the Service AutoStart Provider for a specific site to allow custom preloading logic. ```xml ``` -------------------------------- ### Nested Batch Creation and Continuation Source: https://docs.hangfire.io/en/latest/_sources/background-methods/using-batches.rst.txt Demonstrates creating nested batches and continuations, including continuing a batch with a job and continuing a job with a batch. ```csharp BatchJob.StartNew(parent => { var nested1 = parent.StartNew(nested => { nested.Enqueue(() => Console.WriteLine("Nested 1")); }); var nested2 = parent.ContinueBatchWith(nested1, () => Console.WriteLine("Nested 2")); var nested3 = parent.ContinueJobWith(nested2, nested => { nested.Enqueue(() => Console.WriteLine("Nested 3")); }); string nested5 = null; var nested4 = parent.ContinueBatchWith(nested3, nested => { nested5 = nested.Enqueue(() => Console.WriteLine("Nested 4")); }); parent.ContinueJobWith(nested5, () => Console.WriteLine("Nested 5")); }); ``` -------------------------------- ### Install Hangfire SQL Server Storage Package Source: https://docs.hangfire.io/en/latest/_sources/background-processing/processing-jobs-in-console-app.rst.txt Install the Hangfire SQL Server storage package using the Package Manager Console. ```powershell PM> Install-Package Hangfire.SqlServer ``` -------------------------------- ### Multiple Levels of Nested Batches Source: https://docs.hangfire.io/en/latest/_sources/background-methods/using-batches.rst.txt Demonstrates creating multiple levels of nested batches, illustrating the flexibility in structuring complex batch hierarchies. ```csharp BatchJob.StartNew(batch1 => { batch1.StartNew(batch2 => { batch2.StartNew(batch3 => batch3.Enqueue(() => Console.WriteLine("Nested"))); }); }); ``` -------------------------------- ### Install Hangfire NuGet Package Source: https://docs.hangfire.io/en/latest/_sources/tutorials/send-email.rst.txt Installs the Hangfire NuGet package, which provides a framework for running background jobs reliably within an ASP.NET application. ```powershell Install-Package Hangfire ``` -------------------------------- ### Configure Application Pool for Always Running Source: https://docs.hangfire.io/en/latest/_sources/deployment-to-production/making-aspnet-app-always-running.rst.txt Modify the application pool's start mode to 'AlwaysRunning' to ensure it starts immediately and stays active. ```xml ``` -------------------------------- ### Configure 'Back to site' Link for Subfolder Applications Source: https://docs.hangfire.io/en/latest/configuration/using-dashboard.html For applications in subfolders, use `VirtualPathUtility.ToAbsolute("~")` to correctly set the 'Back to site' link's `AppPath`. ```csharp var options = new DashboardOptions { AppPath = VirtualPathUtility.ToAbsolute("~") }; app.UseHangfireDashboard("/hangfire", options); ``` -------------------------------- ### Enqueue a Background Job with Arguments Source: https://docs.hangfire.io/en/latest/_sources/background-methods/passing-arguments.rst.txt Demonstrates how to enqueue a background job with a simple string argument. Arguments are serialized to JSON. ```csharp BackgroundJob.Enqueue(() => Console.WriteLine("Hello, {0}!", "world")); ``` -------------------------------- ### Add System.Data.SqlClient Package Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-sql-server.rst.txt Include the System.Data.SqlClient package if you need to maintain compatibility with older versions or specific project requirements. ```xml ``` -------------------------------- ### HomeController Implementation Source: https://docs.hangfire.io/en/latest/_sources/tutorials/highlight.rst.txt Controller for handling actions related to code snippets, including listing, viewing details, and creating new snippets. It interacts with the HighlighterDbContext. ```csharp // ~/Controllers/HomeController.cs using System; using System.Linq; using System.Web.Mvc; using Hangfire.Highlighter.Models; namespace Hangfire.Highlighter.Controllers { public class HomeController : Controller { private readonly HighlighterDbContext _db = new HighlighterDbContext(); public ActionResult Index() { return View(_db.CodeSnippets.ToList()); } public ActionResult Details(int id) { var snippet = _db.CodeSnippets.Find(id); return View(snippet); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create([Bind(Include="SourceCode")] CodeSnippet snippet) { if (ModelState.IsValid) { snippet.CreatedAt = DateTime.UtcNow; // We'll add the highlighting a bit later. _db.CodeSnippets.Add(snippet); _db.SaveChanges(); return RedirectToAction("Details", new { id = snippet.Id }); } return View(snippet); } protected override void Dispose(bool disposing) { if (disposing) { _db.Dispose(); } base.Dispose(disposing); } } } ``` -------------------------------- ### Install Hangfire NuGet Package Source: https://docs.hangfire.io/en/latest/tutorials/highlight.html Use this command in the Package Manager Console to add Hangfire to your project. ```powershell Install-Package Hangfire ``` -------------------------------- ### Enabling Batches in Global Configuration Source: https://docs.hangfire.io/en/latest/background-methods/using-batches.html Demonstrates how to enable the Batches feature by calling the UseBatches method on the GlobalConfiguration. ```csharp GlobalConfiguration.Configuration.UseBatches(); ``` -------------------------------- ### Disable Automatic Schema Preparation Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-sql-server.rst.txt Set `PrepareSchemaIfNecessary` to `false` in `SqlServerStorageOptions` to manually manage schema installation. ```csharp var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = false }; GlobalConfiguration.Configuration.UseSqlServerStorage("", options); ``` -------------------------------- ### Uninstall Performance Counters Source: https://docs.hangfire.io/en/latest/_sources/deployment-to-production/performance-counters.rst.txt Run this command to uninstall Hangfire performance counters from a machine. This is the counterpart to the installation command. ```powershell hangfire-perf upc ``` -------------------------------- ### Access Hangfire Dashboard URL Source: https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html Open this URL in your browser to access the Hangfire Dashboard interface after your application has started. ```text http://localhost:5000/hangfire ``` -------------------------------- ### Manage Recurring Jobs with RecurringJobManager Source: https://docs.hangfire.io/en/latest/_sources/background-methods/performing-recurrent-tasks.rst.txt Use RecurringJobManager for more advanced control over recurring jobs. This example adds a yearly job. ```csharp var manager = new RecurringJobManager(); manager.AddOrUpdate("some-id", Job.FromExpression(() => Method()), Cron.Yearly()); ``` -------------------------------- ### Import Hangfire Namespaces in Startup.cs Source: https://docs.hangfire.io/en/latest/_sources/getting-started/aspnet-core-applications.rst.txt Include the necessary Hangfire namespaces in your Startup.cs file to use its services and extensions. ```csharp // ... using Microsoft.Extensions.DependencyInjection; using Hangfire; using Hangfire.SqlServer; ``` -------------------------------- ### MiniProfiler Integration in Global.asax.cs Source: https://docs.hangfire.io/en/latest/tutorials/highlight.html Integrates MiniProfiler into the application lifecycle by starting and stopping the profiler on each request. This requires modifications to the Global.asax.cs file. ```csharp // ~/Global.asax.cs public class MvcApplication : HttpApplication { /* ... */ protected void Application_BeginRequest() { StackExchange.Profiling.MiniProfiler.Start(); } protected void Application_EndRequest() { StackExchange.Profiling.MiniProfiler.Stop(); } } ``` -------------------------------- ### Explicitly Configure SqlClientFactory Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-sql-server.rst.txt Manually specify which SQL Client factory to use (Microsoft.Data.SqlClient or System.Data.SqlClient) within SqlServerStorageOptions if both are installed or for explicit control. ```csharp GlobalConfiguration.Configuration .UseSqlServerStorage("connection_string", new SqlServerStorageOptions { SqlClientFactory = System.Data.SqlClient.SqlClientFactory // or SqlClientFactory = Microsoft.Data.SqlClient.SqlClientFactory }); ``` -------------------------------- ### Configure Hangfire in OWIN Startup Class Source: https://docs.hangfire.io/en/latest/_sources/configuration/index.rst.txt Place this code in your OWIN Startup class for OWIN-based applications (ASP.NET MVC, Nancy, etc.) to configure Hangfire with SQL Server storage. This snippet requires the OwinStartup attribute. ```csharp using Hangfire; [assembly: OwinStartup(typeof(Startup))] public class Startup { public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration.UseSqlServerStorage(""); } } ``` -------------------------------- ### Create Multiple Batches Atomically Source: https://docs.hangfire.io/en/latest/_sources/background-methods/using-batches.rst.txt Use BatchJob.StartNew to create a parent batch that atomically creates child batches and enqueues background jobs. ```csharp var antecedentId = BatchJob.StartNew(batch => { batch.StartNew(inner => inner.Enqueue(() => Console.WriteLine("First"))); batch.StartNew(inner => inner.Enqueue(() => Console.WriteLine("Second"))) }); ``` -------------------------------- ### Hangfire SQL Server Job Storage Initialization Source: https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html These log messages indicate that Hangfire is initializing its SQL Server objects and starting the job storage. ```log info: Hangfire.SqlServer.SqlServerStorage[0] Start installing Hangfire SQL objects... Hangfire SQL objects installed. Using job storage: 'SQL Server: .\@AspNetCoreTest' Using the following options for SQL Server job storage: Queue poll interval: 00:00:15. ``` -------------------------------- ### Configure Recommended Options for Hangfire 1.7+ Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-sql-server.rst.txt Apply recommended settings for Hangfire.SqlServer version 1.7.0 and later to ensure optimal performance and compatibility. These settings will be default in version 2.0. ```csharp GlobalConfiguration.Configuration .UseSqlServerStorage("db_connection", new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, DisableGlobalLocks = true // Migration to Schema 7 is required }); ``` -------------------------------- ### Configure Hangfire in OWIN Startup Source: https://docs.hangfire.io/en/latest/_sources/tutorials/highlight.rst.txt Add these lines to your OWIN Startup class to configure Hangfire with SQL Server storage, the dashboard, and the server. ```csharp public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration.UseSqlServerStorage("HighlighterDb"); app.UseHangfireDashboard(); app.UseHangfireServer(); } ``` -------------------------------- ### Implement Custom OWIN Authorization Filter Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-dashboard.rst.txt Example of a custom authorization filter for the Hangfire Dashboard in an OWIN environment. This filter checks if the user is authenticated. ```csharp public class MyAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize(DashboardContext context) { // In case you need an OWIN context, use the next line, `OwinContext` class // is the part of the `Microsoft.Owin` package. var owinContext = new OwinContext(context.GetOwinEnvironment()); // Allow all authenticated users to see the Dashboard (potentially dangerous). return owinContext.Authentication.User.Identity.IsAuthenticated; } } ``` -------------------------------- ### Register Hangfire Services in ASP.NET Core Source: https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html Register Hangfire services, including the SQL Server storage and the Hangfire server itself as an IHostedService. This configuration is for new installations. ```csharp public void ConfigureServices(IServiceCollection services) { // Add Hangfire services. services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"))); // Add the processing server as IHostedService services.AddHangfireServer(); // Add framework services. services.AddMvc(); } ``` -------------------------------- ### Initialize Performance Counters in OWIN Startup Source: https://docs.hangfire.io/en/latest/deployment-to-production/performance-counters.html Easily integrate Hangfire performance counters into your OWIN application by calling this extension method within your Startup class's Configure method. ```csharp using Hangfire.PerformanceCounters; public void Configure(IAppBuilder app) { app.UseHangfirePerformanceCounters(); } ``` -------------------------------- ### Add Hangfire Dashboard to OWIN Application Source: https://docs.hangfire.io/en/latest/_sources/configuration/using-dashboard.rst.txt This snippet shows how to register the Hangfire Dashboard middleware in an OWIN startup class. Ensure the Hangfire.Owin package is installed. ```csharp using Hangfire; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(MyWebApplication.Startup))] namespace MyWebApplication { public class Startup { public void Configuration(IAppBuilder app) { // Map Dashboard to the `http:///hangfire` URL. app.UseHangfireDashboard(); } } } ``` -------------------------------- ### Controller for Enqueuing Background Jobs Source: https://docs.hangfire.io/en/latest/_sources/background-methods/writing-unit-tests.rst.txt This controller demonstrates how to inject IBackgroundJobClient for dependency injection, making it testable. The constructor allows for providing a mock client during unit tests. ```csharp public class HomeController : Controller { private readonly IBackgroundJobClient _jobClient; // For ASP.NET MVC public HomeController() : this(new BackgroundJobClient()) { } // For unit tests public HomeController(IBackgroundJobClient jobClient) { _jobClient = jobClient; } public ActionResult Create(Comment comment) { ... _jobClient.Enqueue(() => CheckForSpam(comment.Id)); ... } } ``` -------------------------------- ### Complex Batch Nesting with Continuations and Jobs Source: https://docs.hangfire.io/en/latest/background-methods/using-batches.html Illustrates advanced batch creation using nested continuations for both batches and individual jobs. This enables intricate workflow definitions. ```csharp BatchJob.StartNew(parent => { var nested1 = parent.StartNew(nested => { nested.Enqueue(() => Console.WriteLine("Nested 1")); }); var nested2 = parent.ContinueBatchWith(nested1, () => Console.WriteLine("Nested 2")); var nested3 = parent.ContinueJobWith(nested2, nested => { nested.Enqueue(() => Console.WriteLine("Nested 3")); }); string nested5 = null; var nested4 = parent.ContinueBatchWith(nested3, nested => { nested5 = nested.Enqueue(() => Console.WriteLine("Nested 4")); }); parent.ContinueJobWith(nested5, () => Console.WriteLine("Nested 5")); }); ``` -------------------------------- ### Hangfire Background Job Server Startup Source: https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html Log messages showing the Hangfire Server starting up, including worker count, listening queues, and shutdown timeout. ```log info: Hangfire.BackgroundJobServer[0] Starting Hangfire Server... Using the following options for Hangfire Server: Worker count: 20 Listening queues: 'default' Shutdown timeout: 00:00:15 Schedule polling interval: 00:00:15 ```