Hangfire.io – Installation & Hello World Application

Background

One of the applications that we are hosting relies on Hangfire to perform some background processing.

It is time to get smart quick!

What Are we going To Do

We will take the minimalist approach.

Checklist

  1. No Visual Studio IDE.
  2. Just an editor, notepad++
  3. Nuget, Packet Manager
  4. Hangfire packages
  5. Validate that MSBuild is installed
    • If not download and install it
  6. Create Source Files
    • Simple File
    • Build File
  7. Invoke Build
  8. Trial Runs

Installation

Hangfire is based on Microsoft .Net and we can install it by laying down Nuget and Hangfire specific packages.

Nuget

Outline

  1. Download nuget

 

Download nuget

Download nuget.exe from here.

The current version is 3.5.

And, we reached for the file under the “Windows x86 CommandLine” section.

 

Hangfire

Outline

  1. Download Hangfire packages
    • Install Hangfire.core
    • Install Hangfire.sqlserver

hangfire.core

Code


rem installHangFireCore

set _folderNuget=N:\downloads\nuget\v3.5\
set _logger=N:\downloads\wtee\wtee.exe

if not exist log mkdir log

%_folderNuget%\nuget.exe install Hangfire.Core | %_logger% log\Hangfire.core.log

Output

hangfire.SqlServer

Code


rem installHangFire.SqlServer

set _folderNuget=N:\downloads\nuget\v3.5\
set _logger=N:\downloads\wtee\wtee.exe

if not exist log mkdir log

%_folderNuget%\nuget.exe install Hangfire.SqlServer | %_logger% log\Hangfire.sqlserver.log

Output

 

Files

 

Package Description Links  Files
 Hangfire.core Core components for Hangfire (background job system for ASP.NET applications). Link (Nuget Gallery )  a) Hangfire.Core
b) Owin
c) Newtonsoft.Json
 Hangfire.sqlServer  SQL Server 2008+ (including Express), SQL Server LocalDB and SQL Azure storage support for Hangfire (background job system for ASP.NET applications).  Link ( Nuget Gallery )  a) Hangfire.Core
b) Hangfire.SqlServer
c) Owin
d) Microsoft.Owin
e) Microsoft.Owin.Host.SystemWeb
f) Newtonsoft.Json

 

 

 

MS Build

Download Build

Microsoft Build Tools 2015

Download Site

Download MSBuild from here.

Install
Welcome

Installing

Setup Completed

 

Source Code

Source File

Source File

hfSimple.cs

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Hangfire;
using Hangfire.SqlServer;


namespace consoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            useHangFire();
        }


        static void useHangFire()
        {


            GlobalConfiguration.Configuration.UseSqlServerStorage("connectionString");
			
			
            using (var server = new BackgroundJobServer())
            {

		
				BackgroundJob.Schedule(() => backgroundTask.sayHello(), TimeSpan.FromSeconds(2));
				
				RecurringJob.AddOrUpdate("IDStopClock", () => backgroundTask.sayTime(), Cron.Minutely);
				
				Console.WriteLine("Hangfire Server started. Press any key to exit...");			
				
                Console.ReadKey();
            }
			

	 }
	 
	 


    } // class program
	
	
	class backgroundTask
	{
		
		static String FORMAT_DATETIME = "{0:ddd, MMM d, yyyy  hh:mm tt}";
		
		
		static long lIteration = 0;
		

		static public void sayHello()
		{
			
			String strTimeStamp;
			String strLog;
			
			strTimeStamp = String.Format(FORMAT_DATETIME, DateTime.Now);
			
			strLog = "At " + strTimeStamp + " ... Saying Hello";

			//Say Time
			Console.WriteLine(strLog);
		
			
		} //sayHello
		
		[AutomaticRetry(Attempts = 5)]
		[DisableConcurrentExecution(timeoutInSeconds: 10 * 60)]
		static public void sayTime()
		{
			
			String strTimeStamp;
			String strLog;
			
			strTimeStamp = String.Format(FORMAT_DATETIME, DateTime.Now);
			
			strLog = lIteration + ")" + strTimeStamp;

			//Say Time
			Console.WriteLine(strLog);
		
			lIteration = lIteration + 1;
			
		} //sayTime
		
		
	}
	
}


 

Configuration

App.config

Code


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

  <connectionStrings>
    <add name="connectionString" connectionString="Trusted_Connection=Yes;Server=.;Application Name=hangfire;database=labHangFire;" />

  </connectionStrings>
</configuration>
Explanation
  1. ConnectionStrings
    • Trusted_Connection=Yes
      • Integrated Security; as opposed to SQL Server username/password combination
    • Application Name
      • Given name for the Application
    • database
      • Name of the database on the specified SQL Instance

 

Build Files

Build Configuration File

hfsimple.csproj

Code

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{2957BCCD-03ED-4FF3-868D-8A07226516D7}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>hfsimple</RootNamespace>
    <AssemblyName>hfsimple</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
  
    <Reference Include="Hangfire.Core">
      <HintPath>package\Hangfire.Core.1.6.12\lib\net45\Hangfire.Core.dll</HintPath>
      <Private>True</Private>
    </Reference>
	
	<Reference Include="Hangfire.SqlServer">
	  <HintPath>package\Hangfire.SqlServer.1.6.12\lib\net45\Hangfire.SqlServer.dll</HintPath>
	  <Private>True</Private>
	</Reference>
	<Reference Include="Newtonsoft.Json">
      <HintPath>package\Newtonsoft.Json.5.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
      <Private>True</Private>
    </Reference>
    
	<Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  
  </ItemGroup>
  
  <ItemGroup>
    <Compile Include="hfSimple.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  
  <ItemGroup>
    <None Include="App.config" />
    <None Include="packages.config" />
  </ItemGroup>
  
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- 
  
	  To modify your build process, add your task inside one of the targets below and uncomment it. 
      Other similar extension points exist, see Microsoft.Common.targets.
	
	  <Target Name="BeforeBuild">
	  </Target>
	  <Target Name="AfterBuild">
	  </Target>
	  
  -->
</Project>

Build Script

buildhf.cmd

Code

set "_appFolder=C:\Program Files (x86)\MSBuild\14.0\Bin\"

"%_appFolder%\msbuild" hfSimple.csproj /t:Rebuild 

 

Usage

Sample Run

Explanation

  1. Each minute, we display the current time on the console

 

Review

SQL Server

Upon initial run, Hangfire creates its tables.

Object Explorer

Image

Explanation

  1. Objects / Tables created

 

Errors

Error Signature Error Sample Resolution
Unhandled Exception: System.Data.SqlClient.SqlException: Cannot open database Unhandled Exception: System.Data.SqlClient.SqlException: Cannot open database “labHangFire” requested by the login. The login failed.
Login failed for user ‘dadeniji’.
Create database referenced for hangfire

 

 

Source Code Version Control

GitHub

DanielAdeniji/hangfireConsoleSimple
Link

Summary

What we have is a simple, console application.

In later posts, we will dig more into profiling.

2 thoughts on “Hangfire.io – Installation & Hello World Application

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s