Working in Episerver's PublishedContent event

The site in question has a subscription service where a user can subscribe and get a notification e-mail or alert inside the site when a page is published in the subscribed pagebranch. A challenge was how to only send once; we tried to solve it outside of our subscription system.

Using a IInitializableModule, IContentEvents and the PublishedContent event seemed obvious but there are some safe guard considerations to make. This is how it ended up with some code comments added for extra clarity.

private void PublishedContent(object sender, ContentEventArgs e)
{
    var page = e.Content as PageData;

    if (page == null)
    {
        return;
    }

    var saveEventArgs = e as SaveContentEventArgs;

    if (saveEventArgs == null)
    {
        return;
    }

    var versionRepository = ServiceLocator.Current
        .GetInstance<IContentVersionRepository>();

    var versions = versionRepository
        .List(e.ContentLink, page.Language.Name);

    // Escape if page has been published before.
    // At first this was the only guard and incorrect
    // notifications were sent.
    if (versions.Any(v => v.Status == VersionStatus.PreviouslyPublished))
    {
        return;
    }

    // Escape if stop publish time is in the past.
    // When editor sets as expired; a page version is not added.
    if (page.StopPublish.HasValue
        && DateTime.UtcNow > page.StopPublish.Value.ToUniversalTime())
    {
        return;
    }

    // Escape if transition is published to published.
    // Typically reached when future stop publish time is entered.
    if (saveEventArgs.Transition.CurrentStatus == VersionStatus.Published
        && saveEventArgs.Transition.NextStatus == VersionStatus.Published)
    {
        return;
    }

    if (saveEventArgs.Transition.NextStatus == VersionStatus.Published)
    {
        // It's probably smart to also handle future start publish time
        // as a greater than condition when processing notifications.
        this.AddToNotificationsQueue(page);
    }
}

This will handle scheduled publish and not message on start/stop publish time actions we've found to not trigger a new content version.

Published and tagged with these categories: Episerver, ASP.NET, Troubleshooting