7

I would like to clean sitecore and delete all local data sources that are not in use.

I know that I can go through each DataSource item and check in LinkDatabase if it has referrer or not. But I have a lot of items in sitecore so it will take a lot of time and server resources. Is there a faster way to do it?

  • 1
    Are you doing this via code, SPE or manually? – Richard Seal Oct 31 '17 at 13:25
  • I would like to do it via code. So I will have create some page that shows list with all DataSource items that can be deleted... – Ihor Oct 31 '17 at 13:29
5

You can do that in a few steps:

  1. Rebuild your link database
  2. Search for datasource items for example by template id
  3. For each item check if it has referrers
  4. Delete item

The code can looks like this:

public void Cleanup()
{
    using (new SecurityDisabler())
    {
        var coreDb = Factory.GetDatabase("core");
        var masterDb = Factory.GetDatabase("master");

        // 1. Rebuild link db
        Globals.LinkDatabase.Rebuild(coreDb);
        Globals.LinkDatabase.Rebuild(masterDb);

        // 2. Search for datasource items
        var items = masterDb.SelectItems("/sitecore/content/home/*[@@templateid='{3B0461BF-9ABC-4AF1-B937-C8D225FC2313}']");
        foreach (var item in items)
        {
            // 3. Check if item has referrers
            var referrers = Globals.LinkDatabase.GetReferrers(item);

            if (referrers == null || !referrers.Any() || referrers.All(x => x.GetSourceItem() == null))
            {
                // 4. Delete item
                item.Delete();
            }
        }
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.