Wednesday, February 24, 2016

Publish items only if version available in target database

Publish items only, if available in the target database.

One of my client requirement was to publish only those items which have version available in the target database, if we found any item which doesn’t exist in target database or don’t have a version in current language then don’t publish that particular item.
So here is the solution:

Override the publish:itemProcessing

Add below config file in App_config>Include>ItemProcessedEvent.config 

<?xml version="1.0"?>
<configuration>
  <sitecore>
    <events timingLevel="custom">
      <event name="publish:itemProcessing">
        <handler type="Namespace.className, " method="OnItemProcessing" />
      </event>
     
    </events>
  </sitecore>
</configuration>


Create the class with desired name and add below method: 

  public void OnItemProcessing(object sender, EventArgs args)
        {
            try
            {
                var argsProcessing = (ItemProcessingEventArgs)args;
                var context = argsProcessing.Context;
                Assert.IsNotNull(context, "ItemProcessedIndexingEvent.OnItemProcessing: Cannot get PublishItem context");

                var sourceItem = context.PublishHelper.GetSourceItem(context.ItemId);
                var targetItem = context.PublishHelper.GetTargetItem(context.ItemId);

               if (targetItem == null || (sourceItem.Database.GetItem(sourceItem.ID, Sitecore.Context.Language).Versions.Count > 0 && targetItem.Database.GetItem(sourceItem.ID, Sitecore.Context.Language).Versions.Count <= 0))
                    {
                        argsProcessing.Cancel = true;
                        return;
                    }

            }
            catch (Exception ex)
            {
                //
            }
        }


Solution: if you publish site, folder with sub items or single item, the publishing will check if item and language version is available in target database, then only it will publish it otherwise that particular item will skip from publishing.
Please feel free to provide your valuable input/feedback

Happy sitecoreJ