Client Pay Portal
 kentico

Site Generation using the Kentico API

Over the years I’ve been asked about automated site generation with Kentico CMS numerous times. Because Kentico’s extensive API is so accessible, this is much easier than people think. In this blog I’ll review some of the API calls to automate site content within a Kentico application.


NOTE

Most the examples leverage the “clone” method of objects. Almost every object in the system has this ability and it’s a great way to get all the properties of an object quickly to populate in your new one.


Creating page templates

One of the first steps in creating content is creating page templates for the menu items. These templates can be created from scratch, however, you may want to base the new templates on existing objects.
 
//**MASTER PAGE TEMPLATE***
// Get the page template
PageTemplateInfo masterTemplate = PageTemplateInfoProvider.GetPageTemplateInfo(strRegionName + "Master");
if (masterTemplate == null)
{
    //Get the base master page template
    masterTemplate = PageTemplateInfoProvider.GetPageTemplateInfo("RegionGeneratorMaster");
 
    //Create a new master template for the region
    masterTemplate = masterTemplate.Clone(true);
    masterTemplate.CodeName = strRegionName + "Master";
    masterTemplate.DisplayName = strRegionName + "Master";
    masterTemplate.PageTemplateSiteID = CMSContext.CurrentSiteID;
    masterTemplate.CategoryID = regionCategory.CategoryId;
 
    // Reset the Ad-hoc status
    masterTemplate.IsReusable = true;
    masterTemplate.PageTemplateNodeGUID = Guid.Empty;
    masterTemplate.PageTemplateSiteID = 0;
    PageTemplateInfoProvider.SetPageTemplateInfo(masterTemplate);
 
    //Get the new master page
    masterTemplate = PageTemplateInfoProvider.GetPageTemplateInfo(strRegionName + "Master");
 
    //Assign the template to the region
    PageTemplateSiteInfoProvider.AddPageTemplateToSite(masterTemplate.PageTemplateId, CMSContext.CurrentSiteID);
 
    strMessage += "Master Page Template created!<br />";
}
else
{
    strMessage += "Master Page Template exists!<br />";
}


Creating CSS

You may need to create a separate style sheet for your content. This code clones an existing stylesheet and updates paths within the new version.
 
//Create a base CSS for the region
// Get the css stylesheet
CssStylesheetInfo stylesheet = CssStylesheetInfoProvider.GetCssStylesheetInfo(strRegionName + "CSS");
if (stylesheet == null)
{
    //Create the new stylesheet
    stylesheet = CssStylesheetInfoProvider.GetCssStylesheetInfo("RegionGeneratorCSS");
    if (stylesheet != null)
    {
        stylesheet = stylesheet.Clone(true);
        stylesheet.StylesheetDisplayName = strRegionNameDisplay + " CSS";
        stylesheet.StylesheetName = strRegionName + "CSS";
        stylesheet.StylesheetText = stylesheet.StylesheetText.Replace("##REGIONNAME##", strRegionName);
 
        // Save the changes
        CssStylesheetInfoProvider.SetCssStylesheetInfo(stylesheet);
        strMessage += "Style Sheet created!<br />";
    }
 
    //Get the new style sheet
    stylesheet = CssStylesheetInfoProvider.GetCssStylesheetInfo(strRegionName + "CSS");
 
    //Assign the CSS to the site
    CssStylesheetSiteInfoProvider.AddCssStylesheetToSite(stylesheet.StylesheetID, CMSContext.CurrentSiteID);
}
else
{
    strMessage += "Style Sheet exists!<br />";
}


Note

This code utilizes a custom string to insert a path into the CSS text. This could be used to replace a base path with a dynamic one during the creation process.


Creating New Roles / Users

If your site uses role-based security you may need to create a new role/user for your new content. The following code creates a new role and assigns a user to it.
 
//***ADMIN ROLE***
// Get the role
RoleInfo regionAdminRole = RoleInfoProvider.GetRoleInfo(strRegionName + "Admins"CMSContext.CurrentSiteID);
if (regionAdminRole == null)
{
    // Create new role object
    regionAdminRole = new RoleInfo();
 
    // Set the properties
    regionAdminRole.DisplayName = strRegionNameDisplay + " Admins";
    regionAdminRole.RoleName = strRegionName + "Admins";
    regionAdminRole.SiteID = CMSContext.CurrentSiteID;
 
    // Save the role
    RoleInfoProvider.SetRoleInfo(regionAdminRole);
    strMessage += "Region Admin Role created!<br />";
    regionAdminRole = RoleInfoProvider.GetRoleInfo(strRegionName + "Admins"CMSContext.CurrentSiteID);
}
else
{
    strMessage += "Region Admin Role exists!<br />";
}
//**ADMIN USER***
//Assign the selected user to the role
if (adminuserselector1.Value != "")
{
    // Get role and user objects
    UserInfo regionAdminUser = UserInfoProvider.GetUserInfo(Convert.ToInt32(adminuserselector1.Value.ToString()));
 
    if ((regionAdminRole != null) && (regionAdminUser != null))
    {
        if (!regionAdminUser.IsInRole(regionAdminRole.RoleName, CMSContext.CurrentSiteName))
        {
            // Create new user role object
            UserRoleInfo userAdminRole = new UserRoleInfo();
 
            // Set the properties
            userAdminRole.UserID = regionAdminUser.UserID;
            userAdminRole.RoleID = regionAdminRole.RoleID;
 
            // Save the user role
            UserRoleInfoProvider.SetUserRoleInfo(userAdminRole);
            strMessage += "User added to Region Admin Role!<br />";
        }
        else
        {
            strMessage += "User already in Region Admin Role!<br />";
        }
    }
}


Creating Media Libraries

Another aspect of site creation is Media Libraries. This code creates a new media library and assigns permissions for the new role. It populates the new library by copying files from an existing library.
 
//***MEDIA LIBRARY
// Get the media library
MediaLibraryInfo mediaLibrary = MediaLibraryInfoProvider.GetMediaLibraryInfo(strRegionName, CMSContext.CurrentSiteName);
if (mediaLibrary == null)
{
//Get the base media library
mediaLibrary = new MediaLibraryInfo();
// Set the properties
mediaLibrary.LibraryDisplayName = strRegionNameDisplay;
mediaLibrary.LibraryName = strRegionName;
mediaLibrary.LibraryDescription = strRegionNameDisplay + " files";
mediaLibrary.LibraryFolder = strRegionName;
mediaLibrary.LibrarySiteID = CMSContext.CurrentSiteID;
mediaLibrary.LibraryGUID = Guid.NewGuid();
mediaLibrary.LibraryLastModified = DateTime.Now;
// Create the media library
MediaLibraryInfoProvider.SetMediaLibraryInfo(mediaLibrary);
mediaLibrary = MediaLibraryInfoProvider.GetMediaLibraryInfo(strRegionName, CMSContext.CurrentSiteName);
 
strMessage += "Media Library created!<br />";
 
//**MEDIA LIBRARY PERMISSIONS***
//Set permissions on media library for new role
//Add all the CMS.MediaLibrary permissions for the region role
InfoDataSet<PermissionNameInfo> libraryPermissions = PermissionNameInfoProvider.GetResourcePermissions(140);
 
// Loop through the individual items
foreach (PermissionNameInfo libraryPermission in libraryPermissions)
{
    if ((mediaLibrary != null) && (regionAdminRole != null) && (libraryPermission != null))
    {
        // Create a new media library role permission info
        MediaLibraryRolePermissionInfo rolePermission = new MediaLibraryRolePermissionInfo();
 
        // Set the values
        rolePermission.LibraryID = mediaLibrary.LibraryID;
        rolePermission.RoleID = regionAdminRole.RoleID;
        rolePermission.PermissionID = libraryPermission.PermissionId;
 
        // Add role permission to media library
        MediaLibraryRolePermissionInfoProvider.SetMediaLibraryRolePermissionInfo(rolePermission);
    }
}
 
strMessage += "Media Library permissions assigned!<br />";
 
//Copy the media library files
if (mediaLibrary != null)
{
    //Get the base media library
    MediaLibraryInfo basemediaLibrary = MediaLibraryInfoProvider.GetMediaLibraryInfo("RegionGeneratorRoot"CMSContext.CurrentSiteName);
    if (basemediaLibrary != null)
    {
        CloneSettings settings = new CloneSettings();
        settings.IncludeChildren = true;
        settings.IncludeMetafiles = true;
        CloneResult result = new CloneResult();
        MediaLibraryHelper.CloneLibraryFiles(basemediaLibrary.LibraryID, mediaLibrary.LibraryID, settings, result);
 
        strMessage += "Media Library files copied!<br />";
    }
  }
}
else
{
strMessage += "Media Library already exists!<br />";
}


Note

This code is based on cloning an existing media library and its files. The one line of code simplifies the copying of the physical files on the file system.


Bizforms

For this example code we have some template forms created within the site. This code clones the object and updates some settings based on the values specified.
 
//***REGION FORMS***
BizFormInfo existingForm;
string strFormName = "";
foreach (string strForm in strForms)
{
    //General Contact
    existingForm = BizFormInfoProvider.GetBizFormInfo(strForm, CMSContext.CurrentSiteID);
    if (existingForm != null)
    {
        strFormName = strRegionName + existingForm.FormName.Replace("RegionGenerator""");
        string strEmail = "";
        //Check if the user has filled in a notifiction email for the current form
        TextBox tb = (TextBox)pnlNotificationEmails.FindControl("txt" + strForm);
        if (tb != null)
        {
            if (tb.Text != "")
            {
                strEmail = tb.Text;
            }
        }
        //Clone the bizform
        if (CloneForm(existingForm, strFormName, strEmail, regionAdminRole, regionSalesRole))
        {
            strMessage += "Biz form (" + strForm + ") created!<br />";
        }
    }
}


NOTE

The "CloneForm" function above is a custom method written to perform the actual data cloning. This is based on the sample code provided here.

This blogs details only a fraction of what’s packed into Kentico’s API and what you can do with it. Check out their API Guide to get the lowdown on all of the classes and functionality.

Author

Wiz E. Wig, Mascot & Director of Magic
Wiz E. Wig

Director of Magic