It can be little tricky when working with version histories. I've created and tested following example of scheduled task. Here you go:
using CMS;
using CMS.DocumentEngine;
using CMS.EventLog;
using CMS.Helpers;
using CMS.Scheduler;
using CMS.SiteProvider;
using CMS.Synchronization;
using System;
using System.Data;
[assembly: RegisterCustomClass("Custom.RecycleBinCleaner", typeof(RecycleBinCleaner))]
public class RecycleBinCleaner : ITask
{
public string Execute(TaskInfo ti)
{
var deleteAfterDays = 1;
// Handle objects
var recycleBinObjects = GetRecycleBinObjects();
if (!DataHelper.IsEmpty(recycleBinObjects))
{
foreach (DataRow dr in recycleBinObjects.Tables[0].Rows)
{
// check date
var deletionDate = ValidationHelper.GetDate(dr["VersionDeletedWhen"], DateTime.Now.AddYears(-1));
// destroy version if its older then X days
if (DateTime.Now > deletionDate.AddDays(deleteAfterDays))
{
string versionObjType = Convert.ToString(dr["VersionObjectType"]);
string objName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(dr["VersionObjectDisplayName"], string.Empty)));
// Destroy the version
int versionObjId = ValidationHelper.GetInteger(dr["VersionObjectID"], 0);
ObjectVersionManager.DestroyObjectHistory(versionObjType, versionObjId);
EventLogProvider.LogInformation("RecycleBinCleaner", "Cleanup", string.Format("Object {0} of {1} type was pernamently destroyed", objName, versionObjType));
}
}
}
// Handle pages
var recycleBinPages = GetRecycleBinPages();
if (!DataHelper.IsEmpty(recycleBinPages))
{
TreeProvider tree = new TreeProvider();
tree.AllowAsyncActions = false;
VersionManager verMan = VersionManager.GetInstance(tree);
foreach (DataRow dr in recycleBinPages.Tables[0].Rows)
{
// check date
var deletionDate = ValidationHelper.GetDate(dr["VersionDeletedWhen"], DateTime.Now.AddYears(-1));
// destroy version if its older then X days
if (DateTime.Now > deletionDate.AddDays(deleteAfterDays))
{
int versionHistoryId = Convert.ToInt32(dr["VersionHistoryID"]);
string documentNamePath = ValidationHelper.GetString(dr["DocumentNamePath"], string.Empty);
// Destroy the version
verMan.DestroyDocumentHistory(ValidationHelper.GetInteger(dr["DocumentID"], 0));
EventLogProvider.LogInformation("RecycleBinCleaner", "Cleanup", string.Format("Page {0} was destroyed", documentNamePath));
}
}
}
return "Finished";
}
private DataSet GetRecycleBinPages()
{
int topN = -1; // all pages
return VersionHistoryInfoProvider.GetRecycleBin(SiteContext.CurrentSiteID, 0, null, null, topN, null, DateTimeHelper.ZERO_TIME, DateTimeHelper.ZERO_TIME);
}
private DataSet GetRecycleBinObjects()
{
int topN = -1; // all objects
string columns = "VersionID, VersionObjectDisplayName, VersionObjectType, VersionObjectID, VersionDeletedWhen";
return ObjectVersionHistoryInfoProvider.GetRecycleBin(null, null, topN, columns);
}
}
Hope it helps :-)