Computer Magic Logo
First publish date

Wednesday, March 9, 2016

Published by Aristotelis Pitaridis

Sometimes we want to have the date of the first publish for a content in order to display it for an article. The following class will be executed every time that we publish a content and check if this is the first time that we publish this content and if this is the first time we set the value of the property with alias name publishDate to be equal to the current date.

using System;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Services;

namespace UmbracoExample
{
    public class PublishDateApplicationEventHandler : ApplicationEventHandler
    {
        protected override void ApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            ContentService.Publishing += ContentService_Publishing;
        }

        private void ContentService_Publishing(Umbraco.Core.Publishing.IPublishingStrategy sender, Umbraco.Core.Events.PublishEventArgs<Umbraco.Core.Models.IContent> e)
        {
            var contentService = ApplicationContext.Current.Services.ContentService;
            foreach (var content in e.PublishedEntities.Where(m => m.HasProperty("publishDate")))
            {
                var existingValue = content.GetValue("publishDate");
                if (existingValue == null)
                {
                    content.SetValue("publishDate", DateTime.Now);
                }
            }

        }
    }
}