Add content programmatically to Umbraco 8

First of all, I can't take any credit for this code. I have kindly been given permission to share it with you by Paul Seal from codeshare.co.uk.

I had the requirement to add a lot of data in to a project so that I can test pagination and filtering. In the past, I would add each content node manually but Nik suggested I script it so it can be reused for other sections of the project we are working on.

This got me thinking. How the heck would I do this and where would I start?

I had a look at the Umbraco Documentation and spotted I could maybe use the Content Service in Umbraco 8 but honestly, that was as far as I got. I started thinking about building a backoffice package or dashboard, basically over thinking things, when I saw over thinking, I actually got myself in to a pickle so turned to the Umbraco Community.

I put a tweet out :

#umbraco friends - @HotChilliCode made a suggestion today about programmatically creating a load of content in to the backoffice to aid testing - anyone done this and got examples or is it documented? #lateNightCoding
— Owain Williams (@ScottishCoder) October 12, 2020

A number of people had done something very similar but unfortunately didn't have any code examples.

Paul to the rescue.

He kindly shared the following code with me:

@using Umbraco.Core.Composing;
@using System;


  //Used to mass create content in the backoffice.
    var contentService = Current.Services.ContentService;
   
    // This is the id of the 'folder' you want to copy. 
    // Place a child within the folder and it will be replicated
    var parentNodeToCopy = 3625;

    // Keep this < n low, remember it replicates the folder so 1, 2, 4, 8, 16, 32 items are created for 5 loops.
    for (var i = 0; i < 2; i++)
    {
      

        var children = contentService.GetPagedChildren(parentNodeToCopy, 0, 904, out var totalRecords);
        foreach (var child in children)
        {

            String[] titleHeading = new string[]
            {
               "rainstorm","preach","weary","gun","plain","zany","helpful","long","various","development","foamy","melted","narrow","freezing","reduce","burly","price","curl","bell",
                "distribution","glow","turkey","meddle","men","boundless","scratch","excuse","mature","post","file","unsuitable","writer","eatable","magical","mere","tray","bump","spotted",
            "volcano","squash","hushed","maddening","smooth","edge","tongue","scorch","gainful","please","decide","porter","jaded","ski","yoke","hospital","mask","barbarous","bubble","business",
            "normal","ashamed","underwear","superb","bore","tedious","beginner","pigs","disagree","earth","verse","perpetual","scattered","rhetorical","workable","cuddly","furry","seemly","puzzled","load",
            "sloppy","ludicrous","queen","ethereal","religion","psychotic","nifty","puzzling","truthful","connection","vulgar","lumpy","bake","bike","mixed","clover","flag","deafening","soak","flaky","statement","lucky"
                     };

            Random rnd = new Random();
            var copiedChild = contentService.Copy(child, parentNodeToCopy, false);

            copiedChild.Name = "Learn with " + titleHeading[rnd.Next(titleHeading.Length)];

            if (copiedChild.HasProperty("titleHeadingOne"))
            {
                copiedChild.SetValue("titleHeadingOne", copiedChild.Name);
            }

            contentService.SaveAndPublish(copiedChild);
        }
    }

I edited it slightly to add the array of strings so that the node names and titleHeadingOne property, which is the property alias of a textstring on the node. This makes each node name bit more unique. Without this array, the node names are copied and (0), (1), (2), is just appended to the end of the name.

Before you run the code

In the backoffice, you need to have a parent folder setup with a single child beneath it:

Before running the code

The code explained

This code is dropped in to a page that you are able to load from the front end, I put it in a partial that is only used on a specific page. You put it on a Masterpage or a hidden page somewhere, it's really up to you.

The parentNodeToCopy value is the id of the September folder. In this case, 3625.

What the code now does is makes a copy of the content within this folder. This is when you need to be careful, the for loop can really go crazy. You start with 1 item which then duplicates and now you have 2 times, the next time the loop goes round, you go from 2 to 4 items. I made the mistake of putting the for loop to 10.

2, 4, 8, 16, 32, 64, 128, 256, 512, 1024.

Yip, I ended up with 1025 items under my September folder! I deleted everything and dialled it back!

Folder content after running the code

You can now see I have 4 items with random names from the array of strings and each one has been saved and published.

Thanks Paul for sharing this code with me, the original 10 or so lines of code saved me a lot of time and I hope this blog helps others in future.

Published on: 10 November 2020