Page type code generation with Xperience by Kentico

15/03/2022

How does code generation work for generating classes for your page types?

Working with strongly typed objects for page types has always been a preference for Kentico Xperience developers.  Nobody wants to work with a TreeNode directly, right?  You want a class that inherits from TreeNode, contains all the page type fields, and uses the correct data types throughout.

In previous versions of Kentico Xperience, we were provided with a few different ways of generating strongly typed classes.  In all scenarios, you had to authenticate with the administration portal and navigate to the Page Types module.  From there you could either copy and paste the individual generated classes or click a button to save them to a folder within the project.

Xperience by Kentico, being the next generation of Kentico Xperience, wanted to improve and build upon this key piece of developer functionality.  Since Xperience by Kentico is entirely rewritten in .NET Core, it is more appropriate that the new code generation tool sits outside of the administration portal and is access through a .NET CLI command.

The new .NET CLI command is so simple to use and was extremely useful when migrating my blog website to Xperience by Kentico.  If I created or edited a page type, I just opened PowerShell and reran the same command:

dotnet run --no-build -- --kxp-codegen --type "All" --location "../Goldfinch.Core/{type}/{dataClassNamespace}/{name}/"

The example above would generate all page type classes, without rebuilding the project first.   The last parameter for location allowed me to customize where the generated class files were placed in my project.  The CLI command comes with other options for including or excluding objects based on patterns, skipping the confirmation warning message, and customizing the namespaces of the files being generated.

If you need any further help getting started with the code generation tool, then I would highly recommend checking the documentation page.  It covers all aspects of the code generation tool and provides explanations and examples for each of the parameters available.

PowerShell window showing page type generation.
PowerShell window showing page type generation.