While back I blogged about indexing blocks with EPiServer Search. Last week someone told me it might be useful to republish the pages containing the Block automatically when a Block is updated, so the search index will also be updated.
To do this, just add another event handler that responds to a Block being published.
public void Initialize(InitializationEngine context) { DataFactory.Instance.PublishingPage += this.OnPublishingPage; DataFactory.Instance.PublishedContent += this.OnPublishedContent; }
In the attached handler, get all references to the Block that was published, and (re)publish all pages that contain the Block.
public void OnPublishedContent(object sender, ContentEventArgs e) { // Check if the content that is published is indeed a block. BlockData blockData = e.Content as BlockData; // If it's not, don't do anything. if (blockData == null) { return; } // Get the softlink repository. ContentSoftLinkRepository linkRepository = ServiceLocator.Current.GetInstance<ContentSoftLinkRepository>(); // Get the references to this block List<ContentReference> referencingContentLinks = linkRepository.Load(e.ContentLink, true).Where(link => link.SoftLinkType == ReferenceType.PageLinkReference && !ContentReference.IsNullOrEmpty(link.OwnerContentLink)) .Select(link => link.OwnerContentLink) .ToList(); // Loop through each reference foreach (ContentReference referencingContentLink in referencingContentLinks) { StandardPage parent; DataFactory.Instance.TryGet(referencingContentLink, out parent); // If it is not a standard page, do nothing if (parent == null) { continue; } // Check if the containing page is published. if (!parent.IsPendingPublish) { // Republish the containing page. DataFactory.Instance.Save(parent.CreateWritableClone(), EPiServer.DataAccess.SaveAction.Publish); } } }
Don’t forget to remove the handler when uninitializing.
public void Uninitialize(InitializationEngine context) { DataFactory.Instance.PublishingPage -= this.OnPublishingPage; DataFactory.Instance.PublishedContent -= this.OnPublishedContent; }
The rest of the code can stay the same.
Hope this helps.