Set default values on existing pages for newly created property

Vote:
 

Hello, 

I have a page type called Interior Page. I added a new property for this page type, which is a checkbox. 

I am able to set a default value for this property using SetDefaultValues: 

public override void SetDefaultValues(ContentType contentType)
        {
            newproperty = true;
        }

However, the default value only works for newly created instances of Interior Page type.

I have 100s of already existing Interior Pages that need to have this new property set to the default value of true. How can I achieve this? 

I tried defining the new property like below, but that didn't seem to do the trick:  

        public virtual bool NewProperty {
            get => this.GetPropertyValue(page => page.newProperty); 
            set { this.SetPropertyValue(page => page.newProperty, true); }

        }

Any suggestions on how I could set the default value for the new property on all existing pages of Interior Page type? 

Thanks!

#288174
Sep 27, 2022 15:09
Vote:
 

You will need to create some sort of scheduled job or tool to achieve this, setting defaults only works when first creating content. It does not replace / overwrite existing items. 

#288175
Sep 27, 2022 15:38
Vote:
 

Example below on how to achieve something like this (Done long time ago), you can use GetChildren rather than FindPagesWithCriteria but should get the jist of it 

    [ScheduledPlugIn(DisplayName = "Set Default Profile Seniority")]
    public class SetDefaultProfileSeniority : ScheduledJobBase
    {
        private const int DefaultSeniority = 100;

        private bool _stopSignaled;

        protected readonly ISiteDefinitionRepository _siteDefinitionRepository;
        protected readonly IContentRepository _contentRepository;
        protected readonly IContentTypeRepository _contentTypeRepository;
        protected readonly IPageCriteriaQueryService _searchPages;
        protected readonly ILanguageBranchRepository _languageBranchRepository;

        public SetDefaultProfileSeniority(
            ISiteDefinitionRepository siteDefinitionRepository,
            IContentRepository contentRepository,
            IContentTypeRepository contentTypeRepository,
            IPageCriteriaQueryService searchPages,
            ILanguageBranchRepository languageBranchRepository)
        {
            GuardValidator.ValidateObject(siteDefinitionRepository);
            GuardValidator.ValidateObject(contentRepository);
            GuardValidator.ValidateObject(contentTypeRepository);
            GuardValidator.ValidateObject(searchPages);
            GuardValidator.ValidateObject(languageBranchRepository);

            _siteDefinitionRepository = siteDefinitionRepository;
            _contentRepository = contentRepository;
            _contentTypeRepository = contentTypeRepository;
            _searchPages = searchPages;
            _languageBranchRepository = languageBranchRepository;

            IsStoppable = true;
        }

        /// <summary>
        /// Called when a user clicks on Stop for a manually started job, or when ASP.NET shuts down.
        /// </summary>
        public override void Stop()
        {
            _stopSignaled = true;
        }

        /// <summary>
        /// Called when a scheduled job executes
        /// </summary>
        /// <returns>A status message to be stored in the database log and visible from admin mode</returns>
        public override string Execute()
        {
            OnStatusChanged(string.Format("Starting execution of {0}", this.GetType()));

            var updatedCounter = 0;
            foreach (var site in _siteDefinitionRepository.List())
            {
                if (_stopSignaled)
                {
                    return "Stop of job was called";
                }

                updatedCounter += ProcessSite(site);
            }

            return $"{updatedCounter} page(s) have been updated.";
        }

        public int ProcessSite(SiteDefinition site)
        {
            if (ContentReference.IsNullOrEmpty(site.RootPage))
            {
                return 0;
            }

            var contentType = _contentTypeRepository.Load(typeof(ProfilePage));
            var productPageTypeCriterion = new PropertyCriteria
            {
                Name = "PageTypeID",
                Type = PropertyDataType.PageType,
                Value = contentType.ID.ToString(),
                Condition = CompareCondition.Equal,
                Required = true
            };

            var criteria = new PropertyCriteriaCollection { productPageTypeCriterion };

            var pageDataCollection = _searchPages.FindPagesWithCriteria(
                new PageReference { ID = site.StartPage.ID },
                criteria);

            var cultures = _languageBranchRepository.ListEnabled().Select(x => x.Culture);

            var processedCounter = 0;
            var updatedCounter = 0;

            var progressTimer = new Timer(5000);
            progressTimer.Elapsed += (o, e) =>
            {
                OnStatusChanged($"Processing site {site.Name} [{processedCounter} / {pageDataCollection.Count}]");
            };
            progressTimer.AutoReset = true;
            progressTimer.Enabled = true;

            foreach (var pageData in pageDataCollection)
            {
                foreach (var culture in cultures)
                {
                    var page = _contentRepository.Get<ProfilePage>(pageData.ContentLink, culture);
                    if (ProcessProfilePage(page))
                    {
                        updatedCounter++;
                    }
                }

                processedCounter++;
            }

            progressTimer.Stop();
            progressTimer.Dispose();
            OnStatusChanged($"Processing site {site.Name} completed.");

            return updatedCounter;
        }

        private bool ProcessProfilePage(ProfilePage page)
        {
            if (page is null || page.Seniority != default)
            {
                return false;
            }

            var clone = page.CreateWritableClone() as ProfilePage;
            if (clone != null)
            {
                clone.Seniority = DefaultSeniority;
                _contentRepository.Save(clone, SaveAction.Patch | SaveAction.SkipValidation);
                return true;
            }

            return false;
        }
    }
#288176
Sep 27, 2022 15:41
Vote:
 

Thank you for sharing this @Minesh!

I was able to repurpose your code to create a scheduled job to achieve exactly what I needed. Approx. 400 pages updated with a click of a button. 

#288182
Sep 27, 2022 18:24
Vote:
 

Or, if you could invert new bool property:

From "IsActive" => false when created

To "IsNotActive" => false when created; therefor true  :)

#288407
Sep 30, 2022 11:36
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.