I have a timer job running in SP 2013 Server but the Status field is not updating correctly. When the expiration date > 90 days, the status field should display GREEN, if the expiration date is < 60 days, the status field should display YELLOW and if the expiration date is < 30 days the status field should display RED. Here is my code:
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace SPTimerJob
{
class TimerJob : SPJobDefinition
{
public TimerJob()
: base()
{ }
public TimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
: base(jobName, service, server, targetType)
{ }
public TimerJob(string jobName, SPWebApplication webApplication)
: base(jobName, webApplication, null, SPJobLockType.Job)
{ this.Title = jobName.ToString(); }
public override void Execute(Guid contentDbId)
{
using (SPSite site = new SPSite("http://sharepoint/sites/test/")
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPListItem item = null;
SPList listST = web.Lists["TestList"];
string STQuery = "<Where><Or><Eq><FieldRef Name='Renewal' /><Value Type='Boolean'>Yes</Value></Eq><IsNull><FieldRef Name='State' /></IsNull></Or></Where>";
SPQuery qryST = new SPQuery();
qryST.Query = STQuery;
SPListItemCollection Asset_Item_Collection = listST.GetItems(qryST);
int itemcount = Asset_Item_Collection.Count;
for (int i = 0; i < itemcount; i++)
{
try
{
string current_state = string.Empty;
string new_state = "Green"; //default
string status = string.Empty;
DateTime? LastExpiration = null;
item = Asset_Item_Collection[i];
if (item["Status"] != null)
{
current_state = item["Status"].ToString().Trim();
}
if (item["Renewal"] != null)
{
status = item["Renewal"].ToString().Trim();
}
if (item["ExpirationDate"] != null)
{
LastExpiration = Convert.ToDateTime(item["ExpirationDate"].ToString().Trim());
}
if (status.ToString().Trim() == "No")
{
new_status = "Green";
}
else
{
if (LastExpiration == null)
{
new_status = "Green";
}
else
{
TimeSpan ts = DateTime.Today - LastExpiration.Value;
if (ts.Days > 0 && ts.Days <= 30)
{
new_status = "Red";
}
else if (ts.Days > 30 && ts.Days <= 60)
{
new_status = "Yellow";
}
else
{
new_status = "Green";
}
}
}
item["Status"] = new_status.ToString();
item.SystemUpdate(false);
}
catch { }
double decprogress = (double)i / itemcount * 100;
int progress = (int)decprogress;
this.UpdateProgress(progress);
}
web.AllowUnsafeUpdates = false;
this.UpdateProgress(100);
}
}
}
}
}