Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Design & Architecture » .Net Batch Job Template

.Net Batch Job Template

This article shows how to create a reusable batch job template.

Page Views : 6767
Downloads : 89
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ConsoleTemplate.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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);
            }

            LogWriter = File.CreateText(filePath + ".txt");
            WriteToLog(
"Begin processing:  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));
            WriteToLog(
"-----------------------------------------------------------");
            WriteToLog(
"");
        }

       
static private void CloseLog()
        {
            WriteToLog(
"");
            WriteToLog(
"------------------------------------------------------------");
            WriteToLog(
"Finish processing:  " + DateTime.Now.ToString("yyyy-MM-dd-hh:mm:ss"));

            LogWriter.Close();
        }

       
static private void WriteToLog(string logEntry)
        {
            LogWriter.WriteLine(logEntry);
        }
    }
}

The App.Config file:

<?xml version="1.0" encoding="utf-8" ?>
<
configuration>
  <
configSections>
    <
section name="dataConfiguration"     
            
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
           Microsoft.Practices.EnterpriseLibrary.Data,
                   Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </
configSections
  <
connectionStrings>
    <
add name="MyDatabase"
        
connectionString="Data Source=MYDATABASE;Initial Catalog=DEV;User ID=XYZ;Password=12345"
        
providerName="System.Data.SqlClient" />
  </
connectionStrings>
  <
appSettings>
    <
add key="DaysToStoreLogFiles" value="60"/>
  </
appSettings
</
configuration
>

Notes:

Every time the batch job runs, the first thing it does is call OpenLog( ).  This method performs a number of tasks.  The first thing it does is look for a folder called Log Files.  This folder should be in the same place as the batch job executable.  If it isn't there, it gets created.  All the batch job log files will be stored here.

The next task OpenLog( ) performs is to clear out old log files.  In the app.config file there is a setting which says log files should be stored for sixty days. Log files older than sixty days are deleted.   

Now OpenLog( ) creates a new log file named [year-month-day-hour-minute-second].txt.  If there is already a file with this name (because the batch job was launched twice in the same second), the second file will have a "(2)" added to the end of the file name.  

Now that we have a folder to hold log files and we've created a new log file for this run, OpenLog( ) records the time when processing began.

CloseLog( ) records the time when processing is complete and then closes the log file.

WriteToLog( ) writes a string into the log file.  Each string thus written goes on its own line in the log.  

The .config file also contains the entries for the Microsoft Enterprise Library data access block and a connection string.  With these in place, the batch job is ready to connect to a database, as shown in the Main( ) function.

After a successful run, the batch job exits with a return code of 0.  If it fails while creating the log, it exits with a return code of 1.

The batch job shown above creates a log file name 2009-11-28-110817.txt that looks like this:

Begin processing:  2009-11-28-09:08:17
-----------------------------------------------------------

Hello world!

------------------------------------------------------------
Finish processing: 2009-11-28-09:08:18 
 

When you make your own batch job, the first thing you do is call OpenLog().  The last thing you do when you're done is call CloseLog().  In between, you can write to the log using the WriteToLog(string) method.  All that's left for you to do is add your own code.

Enjoy.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Andrew Fenster
Andrew Fenster is an IT consultant in Cleveland, Ohio.  He has worked as a developer, technical lead or architect on many projects, large and small.  He has consulted for Progressive Insurance, Charles Schwab, OE Connection and National City Bank, among others. 
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Important and useful topic and code. by Raj On December 14, 2009
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.
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.