Search code examples
kentico

How to prevent global event handlers from firing caused by an API call


I have a custom module that uses Kentico API (DocumentHelper) to update certain fields of my document and then publish but I do not want it to trigger the event handlers that are linked to my document page type. I tried adding comments to .Publish("admin_edit") hoping that I can catch it from the WorkflowEventargs parameter but the VersionComment property always return null. Is there a way to accomplish this in Kentico?

update field:

    var document = DocumentHelper.GetDocument(documentID, tree);
    var workflowManager = WorkflowManager.GetInstance(tree);
    var workflow = workflowManager.GetNodeWorkflow(document);
    if (workflow != null)
    {
        document.CheckOut();
        document.SetValue("SomeFIeld", "some value");
        document.Update(true);
        document.CheckIn();
        document.Publish("admin_edit");            
    }

event handler:

    public override void Init()
    {
        WorkflowEvents.Publish.After += Publish_After;
    }

    private void Publish_After(object sender, WorkflowEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.VersionComment) &&
            e.VersionComment.Contains("admin_edit"))
            return;
    }

Solution

  • You always get null for Version information, because that is related to the 'Page versioning' events, specially for 'SaveVersion'. You can find more about that on this link. If you expand 'Properties' you will see which properties are populated for the specific event. In your case, you can try something like this, to add your message for last version and then check for that comment on 'Publish_After' event, see code bellow:

    var document = DocumentHelper.GetDocument(documentID, tree);
    var workflowManager = WorkflowManager.GetInstance(tree);
    var workflow = workflowManager.GetNodeWorkflow(document);
    if (workflow != null)
    {
        document.CheckOut();
        document.SetValue("SomeFIeld", "some value");
        document.Update(true);
        document.CheckIn(versionComment: "admin_edit");
        document.Publish();            
    }
    

    and then, in event handler, take last version and check for comment like this:

        if (e.PublishedDocument?.VersionHistory?.Count > 0)
        {
            var lastVersion = e.PublishedDocument.VersionHistory[0] as VersionHistoryInfo;
            if (lastVersion.VersionComment.Equals("admin_edit"))
            {
                return;
            }
        }
    

    NOTE: In case that you have a lot of concurrent content editors, there is a chance that your last version is not version from API (someone changed content and saved it right after your API call made change). There is a low chance for that, but still is possible. If this is something that you will use often, you must take it in consideration. This code is tested for Kentico 11.