1

I want to delete block with broken links from my page. Fx we use EPi Server Commerce, and sometime a product is deleted from the PIM in Commerce and I need to remove all the Blocks that had that product referred.

But something is 'wonky'...

Some blocks sometimes still exists after I've tried to delete them. If I put a new block in the ContentArea, it seems to remove the old values and the ContentArea is fine again. It's like EPi server does not see my change as a change and doesnt publish anything.

        private void CleanNonExistingBlocks(PageData page)
    {
        page = page.CreateWritableClone();
        var type = page.GetType();
        var props = type.GetProperties();
        bool isPageDirty = false;
        foreach (var propertyInfo in props)
        {
            if (propertyInfo.PropertyType != typeof(ContentArea))
                continue;

            ContentArea value = propertyInfo.GetValue(page, null) as ContentArea;
            if (value == null)
                continue;
            List<ContentAreaItem> list = value.Items.ToList();
            bool isListDirty = false;
            foreach (var contentAreaItem in list.ToList())
            {
                IContent found;
                if (_contentRepository.TryGet<IContent>(contentAreaItem.ContentLink, out found))
                    continue;

                isPageDirty = true;
                isListDirty = true;
                list.RemoveAll(c => c.Equals(contentAreaItem));

            }
            if (isListDirty)
            {
                value.Items.Clear();
                foreach (ContentAreaItem contentAreaItem in list)
                    value.Items.Add(contentAreaItem);
                propertyInfo.SetValue(page, value);
            }
        }
        if (isPageDirty)
        {
            _contentRepository.Save(page, SaveAction.Publish, AccessLevel.NoAccess);
            _outputMessages.Add(page.Name + " - ");
        }
    }
MazeezaM
  • 149
  • 1
  • 10

1 Answers1

1

The problem is you are using .NET Reflection API:s and not EPiServers API. See this questions accepted answer for an example of how to work with ContentArea in code:

EpiServer - Add block to a content area programmatically

Community
  • 1
  • 1
Andreas
  • 1,355
  • 9
  • 15
  • The reflection part is just to find all the different ContentArea properties on differnet PageData models. I'm using the contentRepository to save the changes to the models. Are you saying there is a different in working directly on the models property, then using reflection? – MazeezaM Nov 13 '15 at 08:46
  • I believe so. The properties of a page or block are modified at runtime by EPiServer framework using dynamic proxy. That is why they have to be virtual and there is a GetOriginalType method: http://world.episerver.com/documentation/Class-library/?documentId=cms/7.5/F36089A4 – Andreas Nov 13 '15 at 14:36