Moving stuff to EPiServer 7.5: Old GetLastVersion method using obsolete code

Taking your EPiServer CMS 6 site to 7.5 requires you to make a few code changes. I thought I’d share a piece of code for getting the latest version of a page (published or not), as all you seem to get from Google is EPiServer 6 examples using obsolete methods; like in the one below.

public static PageData GetLastVersion(PageReference pageRef)
{
  PageVersionCollection pageVersions = PageVersion.List(pageRef);
  PageReference lastVersion = pageVersions[0].ID;

  foreach (PageVersion pageVersion in pageVersions)
  {
    if (pageVersion.IsMasterLanguageBranch)
    {
      lastVersion = pageVersion.ID;
    }
  }

  return DataFactory.Instance.GetPage(lastVersion, LanguageSelector.AutoDetect(true));
}

The new way of achieving this would be to get an instance of EPiServer’s IContentVersionRepository and use it to get hold of the version list. This can then be sorted to find the latest version. As each ContentVersion has a ContentLink with a version number, it is possible to use the IContentRepository to get that specific version.

public static IContent GetLastVersion(this ContentReference reference)
{
  var versionRepository = ServiceLocator.Current .GetInstance<IContentVersionRepository>();
  var contentRepository = ServiceLocator.Current .GetInstance<IContentRepository>();

  var versions = versionRepository.List(reference);
  var lastVersion = versions
    .OrderByDescending(v => v.Saved)
    .FirstOrDefault(version => version.IsMasterLanguageBranch);

  if (lastVersion == null)
  {
    var msg = string.Format("Unable to find last version for ContentReference '{0}'.", reference.ID);
    throw new Exception(msg);
  }

  return contentRepository.Get<IContent>(lastVersion.ContentLink, LanguageSelector.AutoDetect(true));
}

You may want to consider caching with some sort of content dependency if this turns out to use alot of resources in your environment.