👨‍💻
wiki - owain.codes
  • 💻 Welcome
  • Coding
    • Tips / How-to
      • Where is the hosts file on Windows?
      • Wrapped up a site
    • Snippets
      • Non-coding
        • TinyMCE config generator for Umbraco
        • Git Markdown
        • Command Prompt / Terminal
      • 👨‍💻Coding
        • Compile FrontEnd via NVM and Gulp
        • Node-Sass
        • SQL Statements
        • Build up SQL statements
        • Get current logged in user from Controller
        • Dynamic BlockList Label
        • Alt Tag
    • Umbraco
      • Luke - Version helper
      • Umbraco 10+
        • Find out Model of Current page
        • error NU1301: Unable to load the service index for source
      • Umbraco 9
        • Get the current page content type alias
      • Fluent SQL
      • Unable to open ConfigSource file
      • Delete items from backoffice by DocType ID
      • [WIP] Setting up Examine
      • Umbraco.ModelsBuilder assembly error
      • Working with IPublishedContent
      • How to Strongly Type to Models
      • Setting up a custom form
      • Getting bounced away from /umbraco
      • Examine
        • Explaining GroupedOr / GroupedAnd methods
      • Rosyln error
      • Models Builder Settings
      • Adding content to the backoffice
      • Pagination
      • Creating YYYY/MM folders
      • Configuration Error - CodeDom
    • C Sharp
      • Useful Links
      • Regex
      • Null check .any()
      • internal static and internal const
      • Dependency Injection
      • Dictionary<Tkey, TValue>
      • Linq / Lambda
  • Git
    • Git Actions
      • Build your own Git Action
      • Create a readme file automatically
    • Command line
      • Unstage a file
      • Ignore web.config changes on commit
      • Allow for case-insensitivity in Windows
      • Making VSCode your Git editor and diff tool
      • Add, Push, Pull, Clone
      • Make Terminal look nice
    • Conventional Commit
Powered by GitBook
On this page
  • Adding content with random Page titles.
  • Adding random postcodes to the content

Was this helpful?

  1. Coding
  2. Umbraco

Adding content to the backoffice

Adding content programatically to the back office

PreviousModels Builder SettingsNextPagination

Last updated 3 years ago

Was this helpful?

Full blog :

Adding content with random Page titles.

Place this code on to a view of the parent node in the backoffice.

Root -> Parent Node --> Child.

This example makes a mix of BlogArticles and NewsArticles under the parent node.

@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 parentNodeId = Model.Id;
    var titleHeadings = 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"
                     }​​​​​​​​;
    var baseDate = DateTime.Today;
 
    // 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 < 300; i++)
    {​​​​​​​​
        Random rnd = new Random(DateTime.Now.Millisecond);
        var name = "Read about " + titleHeadings[rnd.Next(titleHeadings.Length)];
        var date = DateTime.Today.AddDays((rnd.NextDouble() * (28 - 1) + 1) * -1 ).AddMonths(rnd.Next(0, 12) * -1).AddYears(rnd.Next(0, 2) * -1);
        var contentType = rnd.Next(1, 2) == 1 ? BlogArticle.ModelTypeAlias : NewsArticle.ModelTypeAlias;
        var node = contentService.Create(name, parentNodeId, contentType);
        node.SetValue(Article.GetModelPropertyType(a => a.Title).Alias, name);
        node.SetValue(Article.GetModelPropertyType(a => a.PublishDate).Alias, date);
 
        contentService.SaveAndPublish(node);
    }​​​​​​​​

Adding random postcodes to the content

Another example - this time adding random postcodes in to the content.




    //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 parentNodeId = Model.Id;
    var titleHeadings = 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" };
    var postcodes = new string[]{"B15 1AZ","NE63 8JX","RH17 5EZ","BT32 9AY","SG7 6RG","SS8 7QN","DD2 4LU","LL18 4NG","B43 7EU","G64 2JZ","CF23 9JP","DN14 8JD","M24 1JP","OL9 0LW","SG5 1HX","PO31 7FL","GU24 9PP","B64 5RU","B31 1SE","SR8 5TB","WN3 6PF","PO12 3BP","PA12 4AD","M34 6HL","DG2 0RH","BT37 9SB","SY6 7EY","SA10 6DE","BS24 7FB","MK43 0SD","BB7 9NX","B62 9RJ","NR5 8HT","TN12 0AD","KY2 5XQ","LD1 5UW","L20 0BQ","TQ2 7GA"};

    var baseDate = DateTime.Today;

    // 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 < 300; i++)
    {
        Random rnd = new Random(DateTime.Now.Millisecond);
        var name = "Event " + titleHeadings[rnd.Next(titleHeadings.Length)];
        var date = DateTime.Today.AddDays((rnd.NextDouble() * (28 - 1) + 1) * -1).AddMonths(rnd.Next(0, 12) * -1).AddYears(rnd.Next(0, 2) * -1);
        var endDate = DateTime.Today.AddDays((rnd.NextDouble() * (28 - 1) + 1) * -1).AddMonths(rnd.Next(0, 12) * -1).AddYears(rnd.Next(0, 2) * -1);
        var postcode = postcodes[rnd.Next(postcodes.Length)];
        //var contentType = rnd.Next(1, 2) == 1 ? BlogArticle.ModelTypeAlias : NewsArticle.ModelTypeAlias;
        var node = contentService.Create(name, parentNodeId, EventItem.ModelTypeAlias);
        node.SetValue(EventItem.GetModelPropertyType(a => a.Title).Alias, name);
        node.SetValue(EventItem.GetModelPropertyType(a => a.EventStartDate).Alias, date);
        node.SetValue(EventItem.GetModelPropertyType(a => a.EventEndDate).Alias, endDate);
        node.SetValue(EventItem.GetModelPropertyType(a => a.AddressPostcode).Alias, postcode);

        contentService.SaveAndPublish(node);

Add content of a specific content type

  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"
                                     };
            if (child.ContentType.Alias == "flexibleTextPage")
            {
                Random rnd = new Random();
                var copiedChild = contentService.Copy(child, parentNodeToCopy, false);

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

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

                contentService.SaveAndPublish(copiedChild);
            }

        }
    }

https://owain.codes/blog/posts/2020/october/add-content-programmatically-to-umbraco-8/