### Install Windows Service using InstallUtil Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/processing-jobs-in-windows-service.md Use the InstallUtil tool to install the Windows Service after building the project. ```powershell installutil .exe ``` -------------------------------- ### Install Microsoft.Net.Http Package Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md Install the Microsoft.Net.Http package to enable asynchronous HTTP request capabilities. ```powershell Install-Package Microsoft.Net.Http ``` -------------------------------- ### Install MiniProfiler Package Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md Use this command to install the MiniProfiler NuGet package. ```powershell Install-Package MiniProfiler ``` -------------------------------- ### Install Performance Counters Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/performance-counters.md Run this command on every machine to install or update the performance counters. ```powershell hangfire-perf ipc ``` -------------------------------- ### Install Entity Framework Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md Command to install the Entity Framework NuGet package via the Package Manager Console. ```powershell Install-Package EntityFramework ``` -------------------------------- ### Install Hangfire.Throttling via Package Manager Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/throttling.md Use the Package Manager Console to install the library. ```powershell Install-Package Hangfire.Throttling ``` -------------------------------- ### Install Hangfire.Throttling via .csproj Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/throttling.md Add the package reference to your project file. ```xml ``` -------------------------------- ### Installing Hangfire.Pro Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-batches.md Install the required package via NuGet Package Manager Console. ```powershell PM> Install-Package Hangfire.Pro ``` -------------------------------- ### Install Postal NuGet Package Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/send-email.md Use this command to install the Postal library for ASP.NET MVC 5. ```powershell Install-Package Postal.Mvc5 ``` -------------------------------- ### Initialize and Start Hangfire Server Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/processing-background-jobs.md Create an instance of the Hangfire Server and start processing jobs. Advanced options, such as providing an explicit job storage instance, can be configured via the constructor. ```csharp var server = new BackgroundJobServer(); ``` -------------------------------- ### Initialize BackgroundJobServer in Global.asax Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/processing-jobs-in-web-app.md Manually manage the lifecycle of the BackgroundJobServer by starting it in Application_Start and disposing of it in Application_End. ```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(); } } } ``` -------------------------------- ### Run ASP.NET Core Application Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/aspnet-core-applications.md Command to start the ASP.NET Core application. This command initiates the application and any background processing services. ```bash dotnet run ``` -------------------------------- ### Define HomeController Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md The initial controller setup for the MVC application. ```c# public class HomeController : Controller { public ActionResult Index() { return View(); } } ``` -------------------------------- ### Install Hangfire.Pro.Redis via Package Manager Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-redis.md Install the Hangfire.Pro.Redis package using the Package Manager Console. ```powershell PM> Install-Package Hangfire.Pro.Redis ``` -------------------------------- ### Install Hangfire via NuGet Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/send-email.md Use the Package Manager Console to install the Hangfire package. ```powershell Install-Package Hangfire ``` -------------------------------- ### Initialize BackgroundJobServer Source: https://github.com/hangfireio/hangfire.documentation/blob/main/index.md Starts the background processing server within a using block to manage its lifecycle. ```csharp using (new BackgroundJobServer()) { Console.WriteLine("Hangfire Server started. Press ENTER to exit..."); Console.ReadLine(); } ``` -------------------------------- ### Start a Batch with Multiple Nested Batches Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-batches.md Creates a parent batch that immediately starts two child batches. This is useful for organizing related tasks 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 Hangfire.SqlServer.Msmq via NuGet Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-sql-server-with-msmq.md Use the NuGet Package Manager Console to install the MSMQ extension for Hangfire SQL Server storage. ```powershell PM> Install-Package Hangfire.SqlServer.Msmq ``` -------------------------------- ### Install Hangfire SQL Server Storage Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/processing-jobs-in-console-app.md Install the SQL Server storage provider to enable persistent job storage. ```powershell PM> Install-Package Hangfire.SqlServer ``` -------------------------------- ### Add Microsoft.Data.SqlClient Package Reference Source: https://github.com/hangfireio/hangfire.documentation/blob/main/upgrade-guides/upgrading-to-hangfire-1.8.md Explicitly install the Microsoft.Data.SqlClient package if no other package references it. Note potential breaking changes in version 4.0.0 regarding encryption. ```xml ``` -------------------------------- ### Install Hangfire Packages Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/aspnet-applications.md Install the core Hangfire package, SQL Server storage, ASP.NET integration, and SQL client library 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 via Package Manager Console Source: https://github.com/hangfireio/hangfire.documentation/blob/main/installation.md Use this command in the Package Manager Console to install the main Hangfire bootstrapper package. ```csharp PM> Install-Package Hangfire ``` -------------------------------- ### Enable MiniProfiler in Global.asax.cs Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md Integrate MiniProfiler start and stop calls within 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(); } } ``` -------------------------------- ### Start a New Nested Batch Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-batches.md Initiates a new batch that can contain other batches or background jobs. This is the fundamental way to start a nested batch structure. ```csharp BatchJob.StartNew(parent => { parent.Enqueue(() => Console.WriteLine("First")); parent.StartNew(child => child.Enqueue(() => Console.WriteLine("Second"))); }); ``` -------------------------------- ### Install NLog Package using Package Manager Console Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/send-email.md Install the NLog logging framework using the NuGet Package Manager Console. This is a prerequisite for using NLog with Hangfire. ```powershell Install-Package NLog ``` -------------------------------- ### Configuring batches Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-batches.md Enable batch functionality globally. The second example demonstrates setting a custom expiration time. ```csharp GlobalConfiguration.Configuration.UseBatches(); ``` ```csharp GlobalConfiguration.Configuration.UseBatches(TimeSpan.FromDays(2)); ``` -------------------------------- ### Install Hangfire.SqlServer NuGet Package Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-sql-server.md 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 ``` -------------------------------- ### Create HangFire User and Schema Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-sql-server.md Example SQL script to create a dedicated user and schema for Hangfire, granting necessary permissions for schema management. ```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 SQL Server Storage with Explicit SqlClientFactory Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-sql-server.md Manually specify which SQL client factory to use when both Microsoft.Data.SqlClient and System.Data.SqlClient are installed. Microsoft.Data.SqlClient is preferred by default. ```csharp GlobalConfiguration.Configuration .UseSqlServerStorage("connection_string", new SqlServerStorageOptions { SqlClientFactory = System.Data.SqlClient.SqlClientFactory // or SqlClientFactory = Microsoft.Data.SqlClient.SqlClientFactory }); ``` -------------------------------- ### Install Hangfire Core Package Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/processing-jobs-in-console-app.md Use the Package Manager Console to add the core Hangfire library to your project. ```powershell PM> Install-Package Hangfire.Core ``` -------------------------------- ### HomeController with IBackgroundJobClient Dependency Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/writing-unit-tests.md Inject IBackgroundJobClient into your controller for easier unit testing. This example shows dependency injection for both ASP.NET MVC and unit test scenarios. ```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)); ... } } ``` -------------------------------- ### Add Hangfire NuGet Packages Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/index.md Install the core Hangfire package along with the SQL Server implementation and the Microsoft DataSqlClient package using the .NET CLI. ```bash dotnet add package Hangfire.Core dotnet add package Hangfire.SqlServer dotnet add package Microsoft.Data.SqlClient ``` -------------------------------- ### Recommended SQL Server Storage Options (Hangfire 1.7) Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-sql-server.md Configure Hangfire 1.7 with recommended options for new installations to ensure optimal performance and compatibility. These settings will be default in Hangfire 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 }); ``` -------------------------------- ### Build Documentation with Make Source: https://github.com/hangfireio/hangfire.documentation/blob/main/README.md Use this command to build the HTML documentation after cloning the repository. Generated files will be in the \'_build\' directory. ```bash make html ``` -------------------------------- ### Configure a Dynamic Fixed Window Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/throttling.md Sets up a dynamic window with a single bucket, effectively creating a fixed window per tenant. ```c# IThrottlingManager manager = new ThrottlingManager(); manager.AddOrUpdateDynamicWindow("newsletter", new DynamicWindowOptions( limit: 4, interval: TimeSpan.FromHours(1), buckets: 1)); ``` -------------------------------- ### Configure Hangfire with Startup Class Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/aspnet-applications.md Configure Hangfire, including data compatibility, serializers, and SQL Server storage, then use `UseHangfireAspNet` and `UseHangfireDashboard`. A sample background job is enqueued. ```csharp // Startup.cs using Hangfire; using Hangfire.SqlServer; public class Startup { private IEnumerable GetHangfireServers() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Server=.\SQLEXPRESS; Database=HangfireTest; Integrated Security=True;"); yield return new BackgroundJobServer(); } public void Configuration(IAppBuilder app) { app.UseHangfireAspNet(GetHangfireServers); app.UseHangfireDashboard(); // Let's also create a sample background job BackgroundJob.Enqueue(() => Debug.WriteLine("Hello world from Hangfire!")); // ...other configuration logic } } ``` -------------------------------- ### Implement IProcessHostPreloadClient for IIS Auto-Start Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/making-aspnet-app-always-running.md Create a class that implements IProcessHostPreloadClient to trigger Hangfire startup during the Windows Process Activation service initialization. ```c# public class ApplicationPreload : System.Web.Hosting.IProcessHostPreloadClient { public void Preload(string[] parameters) { HangfireBootstrapper.Instance.Start(); } } ``` -------------------------------- ### Transition to MSMQ Queues Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-sql-server-with-msmq.md Deploy multiple server instances to process both legacy SQL Server queues and new MSMQ queues during migration. ```c# /* 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(); ``` ```c# /* This server will process only SQL Server table queues, i.e. old jobs */ var oldStorage = new SqlServerStorage(""); var oldOptions = new BackgroundJobServerOptions { Queues = new [] { "critical", "default" }, // Include this line only if you have multiple queues }; 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}", "critical", "default"); app.UseHangfireServer(); ``` -------------------------------- ### Initialize Hangfire Console Application Source: https://context7.com/hangfireio/hangfire.documentation/llms.txt Set up a basic console application with SQL Server storage and a background server instance. ```csharp using System; using Hangfire; using Hangfire.SqlServer; class Program { static void Main() { // Configure Hangfire GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseColouredConsoleLogProvider() .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Server=.\\sqlexpress;Database=HangfireTest;Integrated Security=True;"); // Create different job types BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!")); BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"), TimeSpan.FromMinutes(1)); RecurringJob.AddOrUpdate("minutely", () => Console.WriteLine("Recurring!"), Cron.Minutely); // Start server and wait using (var server = new BackgroundJobServer()) { Console.WriteLine("Hangfire Server started. Press ENTER to exit..."); Console.ReadLine(); } } } ``` -------------------------------- ### Configure Hangfire Startup Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/send-email.md Initialize Hangfire storage and server components within the Startup class. ```c# public class Startup { public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration .UseSqlServerStorage( "MailerDb", new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) }); app.UseHangfireDashboard(); app.UseHangfireServer(); } } ``` -------------------------------- ### Configure Hangfire in OWIN Startup Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md Add these lines to your OWIN Startup class to initialize SQL Server storage, the dashboard, and the background server. ```csharp public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration.UseSqlServerStorage("HighlighterDb"); app.UseHangfireDashboard(); app.UseHangfireServer(); } ``` -------------------------------- ### Configure SQL Server Storage Source: https://context7.com/hangfireio/hangfire.documentation/llms.txt Set up SQL Server storage with connection strings, compatibility levels, and custom options. ```csharp using Hangfire; using Hangfire.SqlServer; // Basic configuration with connection string GlobalConfiguration.Configuration .UseSqlServerStorage(@"Server=.\sqlexpress; Database=Hangfire; Integrated Security=True;"); // Hangfire 1.8 recommended settings GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Database=Hangfire.Sample; Integrated Security=True;"); // Hangfire 1.7 recommended settings GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("connection_string", new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, DisableGlobalLocks = true }); // Disable automatic schema installation var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = false }; GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string", options); // Specify SQL client explicitly GlobalConfiguration.Configuration .UseSqlServerStorage("connection_string", new SqlServerStorageOptions { SqlClientFactory = Microsoft.Data.SqlClient.SqlClientFactory.Instance // or: SqlClientFactory = System.Data.SqlClient.SqlClientFactory.Instance }); ``` -------------------------------- ### Configure a Dynamic Sliding Window Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/throttling.md Sets up a dynamic window with multiple buckets to enable sliding window behavior. ```c# manager.AddOrUpdateDynamicWindow("newsletter", new DynamicWindowOptions( limit: 4, interval: TimeSpan.FromHours(1), buckets: 60)); ``` -------------------------------- ### Configure and Run Hangfire Server in Windows Service Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/processing-jobs-in-windows-service.md Implement Hangfire Server within a Windows Service. Ensure Hangfire is configured with SQL Server storage and the server is started on service start and disposed on service stop. ```csharp using System.ServiceProcess; using Hangfire; using Hangfire.SqlServer; namespace WindowsService1 { public partial class Service1 : ServiceBase { private BackgroundJobServer _server; public Service1() { InitializeComponent(); GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string"); } protected override void OnStart(string[] args) { _server = new BackgroundJobServer(); } protected override void OnStop() { _server.Dispose(); } } } ``` -------------------------------- ### IIS Application Pool Advanced Settings for Auto-start Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/making-aspnet-app-always-running.md Configure advanced settings for an IIS application pool to ensure it starts automatically and remains active. This involves setting the start mode to 'Always Running' and the idle time-out to 0. ```xml 1. Set start mode to "Always Running". : 1. 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. 2. Set Idle Time-Out (minutes) to 0. ``` -------------------------------- ### Configure Performance Counters in OWIN Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/performance-counters.md Use the OWIN middleware extension method to enable performance counters within the Startup class. ```csharp using Hangfire.PerformanceCounters; public void Configure(IAppBuilder app) { app.UseHangfirePerformanceCounters(); } ``` -------------------------------- ### Configure and Run Hangfire Background Job Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/index.md Initializes Hangfire with SQL Server storage and enqueues a 'Hello, world!' job. Requires the Hangfire and Hangfire.SqlServer NuGet packages. ```c# 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 IIS Application Pool and Site for Auto-start Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/making-aspnet-app-always-running.md Modify the applicationHost.config file to set the application pool to 'AlwaysRunning' and enable Service AutoStart Providers for your site. Ensure the 'type' attribute in 'serviceAutoStartProviders' correctly points to your application's preload class. ```xml ``` -------------------------------- ### Register the Custom JobActivator Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-ioc-containers.md Configure the custom activator in your application bootstrap logic before starting the Hangfire server. ```c# // Somewhere in bootstrap logic, for example in the Global.asax.cs file var container = new Container(); GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(container)); ... app.UseHangfireServer(); ``` -------------------------------- ### Enable Migrations Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md Command to enable Entity Framework Code First Migrations. ```powershell Enable-Migrations ``` -------------------------------- ### Disable Automatic Schema Preparation Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-sql-server.md Pass SqlServerStorageOptions with PrepareSchemaIfNecessary set to false to manually manage schema installation. ```csharp var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = false }; GlobalConfiguration.Configuration.UseSqlServerStorage("", options); ``` -------------------------------- ### Reference System.Data.SqlClient Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-sql-server.md For compatibility reasons, you can explicitly reference the older System.Data.SqlClient package. Ensure SqlClientFactory points to it if both are present. ```xml ``` -------------------------------- ### Configure Connection String Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md Adding the database connection string to the web.config file. ```xml ``` -------------------------------- ### Manage Hangfire Lifecycle in Global.asax Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/making-aspnet-app-always-running.md Ensure Hangfire starts and stops correctly by hooking into the Application_Start and Application_End events. ```c# 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(); } } ``` -------------------------------- ### Implement HomeController Actions in C# Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md This C# code defines actions for the HomeController, including listing snippets, displaying 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); } } } ``` -------------------------------- ### Modify an Existing Batch by Attaching a Job Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-batches.md Attaches a new background job to an already existing batch. If the batch was finished, it will be reset to the 'started' state. ```csharp var batchId = BatchJob.StartNew(batch => batch.Enqueue(() => Console.WriteLine("First"))); BatchJob.Attach(batchId, batch => batch.Enqueue(() => Console.WriteLine("Second"))); ``` -------------------------------- ### Initialize Hangfire Server in Console Application Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/processing-jobs-in-console-app.md Configure the storage provider and instantiate the BackgroundJobServer to begin processing. Ensure the application remains running using a blocking call like Console.ReadKey. ```c# 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(); } } } } ``` -------------------------------- ### Add or Update Recurring Job with RecurringJobManager Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/performing-recurrent-tasks.md Utilize `RecurringJobManager` for advanced control over recurring jobs. This example schedules a yearly job using `Job.FromExpression`. ```csharp var manager = new RecurringJobManager(); manager.AddOrUpdate("some-id", Job.FromExpression(() => Method()), Cron.Yearly()); ``` -------------------------------- ### Configure Dynamic Window Options Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/throttling.md Defines capacity and sub-window limits for a specific resource using DynamicWindowOptions. ```c# manager.AddOrUpdateDynamicWindow("newsletter", new DynamicWindowOptions( capacity: 20, minLimit: 2, maxLimit: 20, interval: TimeSpan.FromHours(1), buckets: 60)); ``` -------------------------------- ### Implement Custom Logger Interfaces Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/configuring-logging.md Create a custom logging adapter by implementing ILog for message handling and ILogProvider for logger instantiation. ```csharp using Hangfire.Logging; public class CustomLogger : ILog { public string Name { get; set; } public bool Log(LogLevel logLevel, Func messageFunc, Exception exception = null) { if (messageFunc == null) { // Before calling a method with an actual message, LogLib first probes // whether the corresponding log level is enabled by passing a `null` // messageFunc instance. return logLevel > LogLevel.Info; } // Writing a message somewhere, make sure you also include the exception parameter, // because it usually contain valuable information, but it can be `null` for regular // messages. Console.WriteLine(String.Format("{0}: {1} {2} {3}", logLevel, Name, messageFunc(), exception)); // Telling LibLog the message was successfully logged. return true; } } public class CustomLogProvider : ILogProvider { public ILog GetLogger(string name) { // Logger name usually contains the full name of a type that uses it, // e.g. "Hangfire.Server.RecurringJobScheduler". It's used to know the // context of this or that message and for filtering purposes. return new CustomLogger { Name = name }; } } ``` -------------------------------- ### Define a class with dependencies Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/passing-dependencies.md A sample class that manually instantiates dependencies within its method. ```c# public class EmailSender { public void Send(int userId, string message) { var dbContext = new DbContext(); var emailService = new EmailService(); // Some processing logic } } ``` -------------------------------- ### Add System.Data.SqlClient Package Reference Source: https://github.com/hangfireio/hangfire.documentation/blob/main/upgrade-guides/upgrading-to-hangfire-1.8.md Explicitly reference System.Data.SqlClient if you prefer to keep the previous package for compatibility reasons. This ensures SqlClientFactory points to it. ```xml ``` -------------------------------- ### Use Pre-built IoC Activator Extensions Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-ioc-containers.md Utilize existing NuGet integration packages that provide extension methods for configuring specific IoC containers. ```c# GlobalConfiguration.Configuration.UseNinjectActivator(kernel); ``` -------------------------------- ### Continue a Batch with Nested Batches Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-batches.md Defines a continuation for a previously started batch, which itself includes nested batches. This allows for sequential execution of complex job flows. ```csharp BatchJob.ContinueBatchWith(antecedentId, continuation => { continuation.StartNew(inner => inner.Enqueue(() => Console.WriteLine("First"))); continuation.StartNew(inner => inner.Enqueue(() => Console.WriteLine("Second"))); }); ``` -------------------------------- ### Configure OWIN Startup for Hangfire Dashboard Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/making-aspnet-app-always-running.md Optionally map the Hangfire Dashboard UI using an OWIN startup class with authorization filters. ```c# public class Startup { public void Configuration(IAppBuilder app) { var options = new DashboardOptions { AuthorizationFilters = new[] { new LocalRequestsOnlyAuthorizationFilter() } }; app.UseHangfireDashboard("/hangfire", options); } } ``` -------------------------------- ### Creating an atomic batch Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/using-batches.md Use BatchJob.StartNew to ensure all background jobs are created atomically. ```csharp BatchJob.StartNew(x => { for (var i = 0; i < 1000; i++) { x.Enqueue(() => SendEmail(i)); } }); ``` -------------------------------- ### Register a Recurring Job with CRON Expression Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/performing-recurrent-tasks.md Schedule a job using a custom CRON expression for more complex scheduling needs. This example runs a job every two months at noon. ```csharp RecurringJob.AddOrUpdate("powerfuljob", () => Console.Write("Powerful!"), "0 12 * */2"); ``` -------------------------------- ### Configuring Queues in ASP.NET Core Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/configuring-queues.md Define the queues array within the AddHangfireServer configuration in the Startup.cs file. ```c# public void ConfigureServices(IServiceCollection services) { // Add the processing server as IHostedService services.AddHangfireServer(options => { options.Queues = new[] { "alpha", "beta", "default" }; }); } ``` -------------------------------- ### Initialize Performance Counters Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/performance-counters.md Initialize the performance counters by providing a unique application identifier. ```csharp using Hangfire.PerformanceCounters; PerformanceCounters.Initialize("unique-app-id"); ``` -------------------------------- ### Hangfire SQL Server Job Storage Initialization Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/aspnet-core-applications.md Console output indicating the successful installation of Hangfire SQL objects and configuration details for the SQL Server job storage, including queue poll interval. ```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. ``` -------------------------------- ### Configure Hangfire in Global.asax.cs Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/aspnet-applications.md Use this C# code to configure Hangfire's storage and initialize a background job server within the Application_Start method of your Global.asax.cs file. This approach is suitable when a Startup class is not feasible. ```csharp // Global.asax.cs using Hangfire; using Hangfire.SqlServer; public class MvcApplication : System.Web.HttpApplication { private IEnumerable GetHangfireServers() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_180) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Server=.\SQLEXPRESS; Database=HangfireTest; Integrated Security=True;"); yield return new BackgroundJobServer(); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); HangfireAspNet.Use(GetHangfireServers); // Let's also create a sample background job BackgroundJob.Enqueue(() => Debug.WriteLine("Hello world from Hangfire!")); } } ``` -------------------------------- ### Create Database Migration for CodeSnippet Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md Execute these Package Manager Console commands to add a new migration for the CodeSnippet entity and update the database schema. ```powershell Add-Migration AddCodeSnippet Update-Database ``` -------------------------------- ### Manual Schema Migration Script Source: https://github.com/hangfireio/hangfire.documentation/blob/main/upgrade-guides/upgrading-to-hangfire-1.8.md Wrap the DefaultInstall.sql script with ALTER DATABASE commands for manual schema migration. This method aborts current transactions and prevents new ones. ```sql ALTER DATABASE [HangfireDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; -- DefaultInstall.sql / Install.sql contents ALTER DATABASE [HangfireDB] SET MULTI_USER; ``` -------------------------------- ### Configure Fixed Window Rate Limiter Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/throttling.md Initialize a ThrottlingManager and define a fixed window with a specific resource identifier and time interval. ```csharp IThrottlingManager manager = new ThrottlingManager(); manager.AddOrUpdateFixedWindow("github", new FixedWindowOptions(5000, TimeSpan.FromHours(1))); ``` -------------------------------- ### Configure SQL Server Storage Source: https://github.com/hangfireio/hangfire.documentation/blob/main/index.md Sets the persistent storage backend to SQL Server using a connection string. ```csharp GlobalConfiguration.Configuration.UseSqlServerStorage("db_connection"); ``` -------------------------------- ### Configure Redis Storage with Key Prefix Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-redis.md Use RedisStorageOptions to define a unique prefix for shared Redis servers. This ensures environment isolation. ```csharp var options = new RedisStorageOptions { Prefix = "hangfire:"; // default value }; GlobalConfiguration.Configuration.UseRedisStorage("localhost", 0, options); ``` -------------------------------- ### Configure a Sliding Window Counter Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-processing/throttling.md Initializes a sliding window counter with a specific interval, bucket count, and execution limit. ```csharp manager.AddOrUpdateSlidingWindow("dropbox", new SlidingWindowOptions( limit: 4, interval: TimeSpan.FromHours(1), buckets: 3)); ``` -------------------------------- ### Configure Hangfire in OWIN Startup Class Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/index.md For OWIN-based applications, place these configuration lines in your OWIN Startup class. This method is suitable for ASP.NET MVC, Nancy, ServiceStack, and FubuMVC applications. ```csharp using Hangfire; [assembly: OwinStartup(typeof(Startup))] public class Startup { public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration.UseSqlServerStorage(""); } } ``` -------------------------------- ### Import Hangfire Namespaces Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/aspnet-core-applications.md Import the necessary Hangfire namespaces in your Startup.cs file to use Hangfire services and configurations. ```csharp // ... using Microsoft.Extensions.DependencyInjection; using Hangfire; using Hangfire.SqlServer; ``` -------------------------------- ### Configure OWIN Startup for Hangfire Dashboard Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-dashboard.md Registers the Hangfire Dashboard middleware within an OWIN Startup class. ```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(); } } } ``` -------------------------------- ### Create a Thread-Safe HangfireBootstrapper Source: https://github.com/hangfireio/hangfire.documentation/blob/main/deployment-to-production/making-aspnet-app-always-running.md Implement a singleton bootstrapper that registers with the HostingEnvironment to ensure Hangfire initializes exactly once. ```c# public class HangfireBootstrapper : IRegisteredObject { public static readonly HangfireBootstrapper Instance = new HangfireBootstrapper(); private readonly object _lockObject = new object(); private bool _started; private BackgroundJobServer _backgroundJobServer; private HangfireBootstrapper() { } public void Start() { lock (_lockObject) { if (_started) return; _started = true; HostingEnvironment.RegisterObject(this); GlobalConfiguration.Configuration .UseSqlServerStorage("connection string"); // Specify other options here _backgroundJobServer = new BackgroundJobServer(); } } public void Stop() { lock (_lockObject) { if (_backgroundJobServer != null) { _backgroundJobServer.Dispose(); } HostingEnvironment.UnregisterObject(this); } } void IRegisteredObject.Stop(bool immediate) { Stop(); } } ``` -------------------------------- ### Map Multiple Dashboards Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/using-dashboard.md Configure multiple dashboard instances by mapping them to different URL paths and storage providers. ```c# var storage1 = new SqlServerStorage("Connection1"); var storage2 = new SqlServerStorage("Connection2"); app.UseHangfireDashboard("/hangfire1", new DashboardOptions(), storage1); app.UseHangfireDashboard("/hangfire2", new DashboardOptions(), storage2); ``` -------------------------------- ### Register Custom Log Provider Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/configuring-logging.md Register the custom log provider instance globally during application startup. ```csharp GlobalConfiguration.Configuration.UseLogProvider(new CustomLogProvider()); ``` -------------------------------- ### Hangfire Background Server Startup Source: https://github.com/hangfireio/hangfire.documentation/blob/main/getting-started/aspnet-core-applications.md Console output confirming the startup of the Hangfire Server, including worker count, listening queues, shutdown timeout, and schedule polling interval. ```bash 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 ``` -------------------------------- ### Use Recommended Serializer Settings Source: https://github.com/hangfireio/hangfire.documentation/blob/main/upgrade-guides/upgrading-to-hangfire-1.7.md Apply recommended JSON serializer settings for more compact payloads. Be aware of potential breaking changes if custom JSON settings are already in use. ```csharp GlobalConfiguration.Configuration // ... .UseRecommendedSerializerSettings(); ``` -------------------------------- ### Unit Test for Background Job Enqueueing with Moq Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/writing-unit-tests.md Use a mocking framework like Moq to verify that the Create method of IBackgroundJobClient is called with the expected parameters when a background job is enqueued. ```csharp [TestMethod] public void CheckForSpamJob_ShouldBeEnqueued() { // Arrange var client = new Mock(); var controller = new HomeController(client.Object); var comment = CreateComment(); // Act controller.Create(comment); // Assert client.Verify(x => x.Create( It.Is(job => job.Method.Name == "CheckForSpam" && job.Args[0] == comment.Id), It.IsAny())); } ``` -------------------------------- ### Enqueue Instance and Static Methods Source: https://github.com/hangfireio/hangfire.documentation/blob/main/background-methods/index.md Use `BackgroundJob.Enqueue` to schedule instance or static method calls as background jobs. These methods are defined using expression trees. ```csharp BackgroundJob.Enqueue(x => x.Send("hangfire@example.com")); ``` ```csharp BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!")); ``` -------------------------------- ### Initialize search form behavior Source: https://github.com/hangfireio/hangfire.documentation/blob/main/index.md Synchronizes the jumbotron search form action with the sidebar search configuration. ```javascript $(function () { $('#jumbotron-search').attr('action', $('#sidebar-search').attr('action')); }); ``` -------------------------------- ### Configure NLog for Hangfire Logging Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/send-email.md Set up NLog by creating an NLog.config file in the project root. This configuration defines file and event log targets and logging rules for Hangfire. ```xml ``` -------------------------------- ### Configure Hangfire in ASP.NET Application Source: https://github.com/hangfireio/hangfire.documentation/blob/main/configuration/index.md Place this initialization logic in the `Application_Start` method of your `Global.asax.cs` file for ASP.NET applications. Ensure the `Hangfire` namespace is included. ```csharp using Hangfire; public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { // Storage is the only thing required for basic configuration. // Just discover what configuration options do you have. GlobalConfiguration.Configuration .UseSqlServerStorage(""); //.UseActivator(...) //.UseLogProvider(...) } } ``` -------------------------------- ### Create background jobs using BackgroundJob static class Source: https://github.com/hangfireio/hangfire.documentation/blob/main/index.md Use the static BackgroundJob class for a simplified syntax to enqueue background tasks. ```c# BackgroundJob.Enqueue(() => Console.WriteLine("Hello!")); ``` -------------------------------- ### Highlight Source Code using hilite.me API Source: https://github.com/hangfireio/hangfire.documentation/blob/main/tutorials/highlight.md This C# code snippet demonstrates how to asynchronously call the hilite.me API to highlight source code. It includes helper methods for synchronous execution. ```csharp // ~/Controllers/HomeController.cs /* ... */ public class HomeController { /* ... */ private static async Task HighlightSourceAsync(string source) { using (var client = new HttpClient()) { var response = await client.PostAsync( @"http://hilite.me/api", new FormUrlEncodedContent(new Dictionary { { "lexer", "c#" }, { "style", "vs" }, { "code", source } })); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } private static string HighlightSource(string source) { // Microsoft.Net.Http does not provide synchronous API, // so we are using wrapper to perform a sync call. return RunSync(() => HighlightSourceAsync(source)); } private static TResult RunSync(Func> func) { return Task.Run>(func).Unwrap().GetAwaiter().GetResult(); } } ```