Sitecore Job template
I'm always finding myself writing little throwaway utility pages. A good example of this was recently when we needed to take 250 thousand items out of workflow.
I usually like to kick off a Sitecore Job via the JobManager for these types of problems.
Below is my template aspx page I always start with when I want to write these one off utilities. Just reload the page to see the status of the Job.
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="Sitecore.Data.Items" %>
<%@ Import Namespace="Sitecore.Data.Fields" %>
<%@ Import Namespace="Sitecore.Data" %>
<%@ Import Namespace="Sitecore.Jobs" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
private const string LOGFILE = @"C:\log\mylog.txt";
private string JOBNAME = "MyJob";
public Sitecore.Jobs.Job CurrentJob
{
get { return Sitecore.Jobs.JobManager.GetJob(JOBNAME); }
}
private void Log(string message)
{
using (StreamWriter writer = new StreamWriter(LOGFILE, true))
{
writer.WriteLine(String.Format("{0} : {1}", DateTime.Now.ToString(), message));
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (CurrentJob != null && CurrentJob.Status.State == JobState.Finished)
{
Response.Write("Job Finished!");
}
else
{
if (CurrentJob != null && CurrentJob.Status.State != JobState.Finished)
{
Response.Write(String.Format("Job Running! Processed {0} items", CurrentJob.Status.Processed));
}
else
{
Response.Write("Job Starting!");
StartJob();
}
}
}
public string StartJob()
{
Sitecore.Jobs.JobOptions options = new Sitecore.Jobs.JobOptions(JOBNAME,
"MyJobCategory",
Sitecore.Context.Site.Name,
this,
"DoWork",
new object[] { });
options.AfterLife = TimeSpan.FromMilliseconds(60000);
Sitecore.Jobs.JobManager.Start(options);
return JOBNAME;
}
protected void DoWork()
{
CurrentJob.Status.Messages.Add("I've started working");
Log("Starting a long running operation");
// Do Work here.. MyClass.DoSomething()
// Increment the items processed: CurrentJob.Status.Processed++;
Log("Job Ended");
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>