Over the years I've had to write enough batch jobs that I've come up with a template. Most batch jobs have a number of common elements. When the job runs, you want it to record in a log the time when it ran, what tasks it performed and the time when it finished. If the batch job runs into problems, you want it to record the problem to the log and then exit with an error code. Most batch jobs also need to connect to a database.
Writing all the code to create a log, get a database connection string and connect to the database is time consuming. It's best to build something reusable. So without further ado, here is the template I use. Comments and explanation are at the end.
using
System;
using
System.Collections.Generic;
using System.Configuration;
using System.IO
using System.Text;
namespace ConsoleTemplate
{
class
BatchTemplate
{
public static
StreamWriter LogWriter =
null;
static int Main(string[]
args)
{
OpenLog();
db =
DatabaseFactory.CreateDatabase("MyDatabase");
DbCommand cmd =
db.GetStoredProcCommand("MyStoredProcedure");
WriteToLog(
"Hello
world!");
CloseLog();
return 0;
}
static private void
OpenLog()
{
// Create log folder if it
doesn't exist
string folderPath =
Path.Combine(Environment.CurrentDirectory,
"Log Files");
DirectoryInfo logFolder =
new
DirectoryInfo(folderPath);
if (!logFolder.Exists)
logFolder.Create();
// Clear out old logs
string appSetting =
ConfigurationManager.AppSettings["DaysToStoreLogFiles"];
int days =
int.Parse(appSetting);
TimeSpan span =
new
TimeSpan(days, 0, 0, 0);
foreach(FileInfo
logFile in
logFolder.GetFiles())
{
if (logFile.CreationTime <
DateTime.Now - span)
logFile.Delete();
}
// Create new log file
string filePath = Path.Combine(folderPath, DateTime.Now.ToString("yyyy-MM-dd-hhmmss"));
if (File.Exists(filePath + ".txt"))
{
bool exitApplication = true;
for (int x = 1; x <= 10; x++)
{
string newPath = filePath + "(" + x.ToString() + ")";
if (!File.Exists(newPath + ".txt"))
{
filePath = newPath;
exitApplication = false;
break;
}
}
// If someone has really launched the batch job more than 10 times in
// a single second, something is wrong.
if (exitApplication)
Environment.Exit(1);
}

Raj VashuPosted Dec 14, 2009, 7:41 PM
This important and useful article. I wish I had found this article a few months ago when I had been writing code for multiple batch jobs. I am looking forward for more articles from you Andy. Best regards, Raj V.