Navigate to Post

Wednesday, March 25, 2020

Asp.net website background jobs and Job dashboard with Hangfire

Introduction

As we all know setting up Asp.net background jobs is tedious job. It requires multiple things like creating separate console application, writing argument based coding and we need to setup batch command on server. Windows task is useful tool to carry out scheduled jobs.

Nowadays we are moving towards rapid development life cycle, we should be able to setup background tasks within short span of time. As well as it should give us some kind of interactive Job dashboard.

Here I will guide you with some important steps to wire up Hangfire with asp.net / MySql database application.

Adding Packages

Considering we have asp.net site with MySql as back-end database.
First of all I have installed below Hangfire supporting nugget packages on website code, below is package.config


<package id="Hangfire" version="1.7.8" targetFramework="net461" />
<package id="Hangfire.Core" version="1.7.8" targetFramework="net461" />
<package id="Hangfire.MySqlStorage" version="2.0.0" targetFramework="net461" />
<package id="Hangfire.SqlServer" version="1.7.8" targetFramework="net461" />

Adding Startup.cs code

Add following code in startup.cs Configure method
below code has some important aspects like

  • Connecting mysql as storage to hangfire scheduler
  • Table prefix for table created by hangfire (here we used Job_***)
  • Adding title to dashboard
  • Adding back button hyperlink 
  • Adding Authorization filter to allow access to selected users
  • Added two recurring job minutely and hourly jobs, here we are calling a static method "SendEmail" and "RunSomeProcess", you are free to add your own logic, these methods will be automatically triggered after a minute and hourly respectively.   



string conStr = ConfigurationManager.ConnectionStrings["DBString"].ConnectionString.ToString();

Hangfire.GlobalConfiguration.Configuration.UseStorage(
new Hangfire.MySql.MySqlStorage(
conStr,
new Hangfire.MySql.MySqlStorageOptions
{
TransactionIsolationLevel = IsolationLevel.ReadCommitted,
QueuePollInterval = TimeSpan.FromSeconds(15),
JobExpirationCheckInterval = TimeSpan.FromHours(1),
CountersAggregateInterval = TimeSpan.FromMinutes(5),
PrepareSchemaIfNecessary = true,
DashboardJobListLimit = 50000,
TransactionTimeout = TimeSpan.FromMinutes(1),
TablesPrefix = "Job_"
}));
DashboardOptions dashboardOptions = new DashboardOptions();
dashboardOptions.AppPath = "/Home.aspx";

dashboardOptions.DashboardTitle = "MySite Jobs";
dashboardOptions.Authorization = new[] { new HangfireAuthorizationFilter() };
app.UseHangfireDashboard("/dashboard", dashboardOptions);
_backgroundJobServer = new BackgroundJobServer();

RecurringJob.AddOrUpdate(() => Jobs.SendEmail(), Cron.Minutely);
RecurringJob.AddOrUpdate(() => Jobs.RunSomeProcess(), Cron.Hourly(15));

Authorization filter

To restrict access of this job dashboard, we are setting up an authorization filter which will allow only specific users  or user role will have access to this dashboard

Below is authorizationFilter class, add your custom logic to validate your logged-in user

public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter 
    {
        public bool Authorize(DashboardContext context)
        {
            bool boolAuthorizeCurrentUserToAccessHangFireDashboard = false;
            if (HttpContext.Current != null && HttpContext.Current.Session != null)
            {                
                    if (Some Condition check)
                    {
                    boolAuthorizeCurrentUserToAccessHangFireDashboard = true;
                    }                
            }
            return boolAuthorizeCurrentUserToAccessHangFireDashboard;
        }
    }

Dashboard is ready to use

Once we run site, add hit url "https://mysite.com/dashboard", we get a beautifully designed job dashboard






Summary

These are simple steps to create .net recurring jobs or methods with interactive dashboard. I hope you enjoyed learning. If you have any questions/feedback/issues, please write them in the comment box.

All time trending post