Monday, February 28, 2011

Remove old versions job in EPiServer CMS 6

At the moment I’m creating a new EPiServer site for a customer. They have an existing CMS 6 site, and we need to migrate some content from the existing site to the new one.

The existing site was upgraded from EPiServer 4 to CMS 6, and it has never had a max value set for the number of page versions allowed per page. This means that for some pages there were 500 different page version.

So we definitely needed to do some cleaning before migrating the content. I found the Remove old versions job, but this is only for EPiServer 4.

I’ve rewritten the job so that it works on CMS 6. Mind you that I've not written this piece of code, I’ve only edited it to work for CMS 6. Unfortunately, I don’t know who wrote this code but all credit should be given to him/her!

Here’s the code:

[ScheduledPlugIn(DisplayName = "Clear old version job")]

public class RemoveOldPageVersionsJob


  private static RemoveOldVersionsDb _removeOldVersionsDb;

  private static int _maxVersions;

  private static int _numberOfPagesRun;


  /// <summary>

  /// Start job

  /// </summary>

  public static string Execute()


    _numberOfPagesRun = 0;

    _removeOldVersionsDb = new RemoveOldVersionsDb();


    _maxVersions = EPiServer.Configuration.Settings.Instance.UIMaxVersions;

    PageData rootPage = DataFactory.Instance.GetPage(PageReference.StartPage);



    return "Removed all old versions except " + _maxVersions + " for all pages (" + _numberOfPagesRun + ") as the following user: " + HttpContext.Current.User.Identity.Name;



  private static void FixBranch(PageData page)



    _removeOldVersionsDb.RemoveVersions(page.PageLink.ID, _maxVersions);

    PageDataCollection children = DataFactory.Instance.GetChildren(page.PageLink);

    foreach (PageData child in children)





public class RemoveOldVersionsDb : DataAccessBase


  public void RemoveVersions(int pageId, int maxVersions)






      IDbCommand cmd = CreateCommand("editDeleteObsoletePageVersions");

      cmd.Parameters.Add(CreateParameter("PageID", pageId));

      cmd.Parameters.Add(CreateParameter("MaxVersions", maxVersions));