Pages


List of examples:

Page creation

Creating pages in a site’s content tree



// Gets the current site's root "/" page, which will serve as the parent page
TreeNode parentPage = new DocumentQuery<TreeNode>()
                            .Path("/", PathTypeEnum.Single)
                            .OnSite("MySite")
                            .Culture("en-us")
                            .TopN(1)
                            .FirstOrDefault();

if (parentPage != null)
{
    // Creates a new page of the custom page type
    TreeNode newPage = TreeNode.New("Custom.Article");

    // Sets the properties of the new page
    newPage.DocumentName = "Articles";
    newPage.DocumentCulture = "en-us";

    // Inserts the new page as a child of the parent page
    newPage.Insert(parentPage);
}

> Back to list of examples

Creating a new culture version of an existing page



// Gets a single page from the "MySite" site and in the "en-us" culture
TreeNode page = new DocumentQuery<TreeNode>()
                            .Path("/Articles/Coffee", PathTypeEnum.Single)
                            .OnSite("MySite")
                            .Culture("en-us")
                            .TopN(1)
                            .FirstOrDefault();

if (page != null)
{
    // Sets new values in the "DocumentName" and "ArticleTitle" fields of the page
    page.DocumentName = "Translated article name";
    page.SetValue("ArticleTitle", "Translated article title");

    // Inserts a new version of the page in the "de-de" culture
    // Note that the culture must be assigned to the current site
    page.InsertAsNewCultureVersion("de-de");
}

> Back to list of examples

Creating a linked page



// Gets the page that will be linked
TreeNode originalPage = new DocumentQuery<TreeNode>()
                            .Path("/Archive/Articles", PathTypeEnum.Single)
                            .OnSite("MySite")
                            .Culture("en-us")
                            .TopN(1)
                            .FirstOrDefault();

// Gets the page that will be used as a parent page for the linked page
TreeNode parentPage = new DocumentQuery<TreeNode>()
                          .Path("/Articles", PathTypeEnum.Single)
                          .OnSite("MySite")
                          .Culture("en-us")
                          .TopN(1)
                          .FirstOrDefault();

if ((originalPage != null) && (parentPage != null))
{
    // Inserts a new linked page under the parent page
    originalPage.InsertAsLink(parentPage);
}

> Back to list of examples

Page management

Updating published pages



// Gets the published version of pages stored under the "/Articles/" path
// The pages are retrieved from the "MySite" site and in the "en-us" culture
IEnumerable<TreeNode> pages = new MultiDocumentQuery()
                                .Path("/Articles/", PathTypeEnum.Children)
                                .WhereStartsWith("DocumentName", "Coffee")
                                .OnSite("MySite")
                                .Culture("en-us")
                                .Published()
                                .PublishedVersion();

// Updates the "DocumentName" and "ArticleTitle" fields of each retrieved page
foreach (TreeNode page in pages)
{
    page.DocumentName = "Updated article name";
    page.SetValue("ArticleTitle", "Updated article title");

    // Updates the page in the database
    page.Update();
}

> Back to list of examples

Updating the latest edited version of pages (pages under workflow)



// Gets the latest version of pages stored under the "/Articles/" path whose name starts with "Coffee"
// The pages are retrieved from the "MySite" site and in the "en-us" culture
IEnumerable<TreeNode> pages = new MultiDocumentQuery()
                                  .Path("/Articles/", PathTypeEnum.Children)
                                  .WhereStartsWith("DocumentName", "Coffee")
                                  .OnSite("MySite")
                                  .Culture("en-us")
                                  .WithCoupledColumns()
                                  .LatestVersion();

// Note: When updating pages of multiple page types under workflow or versioning, always retrieve
// the pages with all columns to avoid data loss using the'WithCoupledColumns' parameterization. 
// Optionally, you can specify the page types to retrieve using the 'Types' parameterization.

// Updates the "DocumentName" and "ArticleTitle" fields of each retrieved page
foreach (TreeNode page in pages)
{
    // Allows the system to create a new version of the updated page (required even when not using content locking)
    // If using content locking, checks out the page
    page.CheckOut();

    page.DocumentName = "Updated article name";
    page.SetValue("ArticleTitle", "Updated article title");

    // Updates the page in the database
    page.Update();

    // Creates a new version of the updated page (required even when not using content locking)
    // If using content locking, checks in the page
    page.CheckIn();
}

> Back to list of examples



// Gets an existing page from the "MySite" site in the "en-us" culture
TreeNode page = new DocumentQuery<TreeNode>()
                    .Path("/Articles/", PathTypeEnum.Children)
                    .OnSite("MySite")
                    .Culture("en-us")
                    .TopN(1)
                    .FirstOrDefault();

if (page != null)
{
    // Updates the "DocumentName" and "ArticleTitle" fields of the page
    page.DocumentName = "Updated article name";
    page.SetValue("ArticleTitle", "Updated article name");

    // Gets a List of the fields that were updated
    var changedColumns = page.ChangedColumns();

    page.Update();

    // Check if search is enabled for the page and that the modified fields are included in search indexes
    if (DocumentHelper.IsSearchTaskCreationAllowed(page) && page.SearchTriggerFieldChanged(changedColumns))
    {
        // Creates search tasks for updating the content of the page in related search indexes
        SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, page.GetSearchID(), page.DocumentID);
    }
}

> Back to list of examples

Copying a page



// Gets the page that will be moved
TreeNode page = new DocumentQuery<TreeNode>()
                    .Path("/Articles/Coffee-Beverages-Explained", PathTypeEnum.Single)
                    .OnSite("MySite")
                    .Culture("en-us")
                    .TopN(1)
                    .FirstOrDefault();

// Gets the page to copy under
TreeNode targetPage = new DocumentQuery<TreeNode>()
                          .Path("/Archive", PathTypeEnum.Single)
                          .OnSite("MySite")
                          .Culture("en-us")
                          .TopN(1)
                          .FirstOrDefault();

if ((page != null) && (targetPage != null))
{
    // Copies the page to the new location, including any child pages
    DocumentHelper.CopyDocument(page, targetPage, true);
}

> Back to list of examples

Moving a page



// Gets the page that will be moved
TreeNode page = new DocumentQuery<TreeNode>()
                    .Path("/Articles/Coffee-Beverages-Explained", PathTypeEnum.Single)
                    .OnSite("MySite")
                    .Culture("en-us")
                    .TopN(1)
                    .FirstOrDefault();

// Gets the parent page to move under
TreeNode targetPage = new DocumentQuery<TreeNode>()
                          .Path("/Archive", PathTypeEnum.Single)
                          .OnSite("MySite")
                          .Culture("en-us")
                          .TopN(1)
                          .FirstOrDefault();

if ((page != null) && (targetPage != null))
{
    // Moves the page to the new location, including any child pages
    DocumentHelper.MoveDocument(page, targetPage, keepPermissions: true);
}

> Back to list of examples

Changing the order of individual pages in the content tree



// Gets the parent page
TreeNode page = new DocumentQuery<TreeNode>()
                    .Path("/Parent", PathTypeEnum.Single)
                    .OnSite("MySite")
                    .Culture("en-us")
                    .TopN(1)
                    .FirstOrDefault();

if (page != null)
{
    // Initializes a provider used for manipulation of nodes in the content tree
    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

    // Moves the page up in the content tree
    tree.MoveNodeUp(page.DocumentID);

    // Moves the page down in the content tree
    tree.MoveNodeDown(page.DocumentID);
    
    // Creates a corresponding staging task for the page move event. Useful only in environments utilizing staging.
    DocumentSynchronizationHelper.LogDocumentChangeOrder(SiteContext.CurrentSiteName, page.NodeAliasPath, tree);
}

> Back to list of examples

Sorting pages in the content tree



// Gets the parent page to sort under
TreeNode page = new DocumentQuery<TreeNode>()
                    .Path("/Parent", PathTypeEnum.Single)
                    .OnSite("MySite")
                    .Culture("en-us")
                    .TopN(1)
                    .FirstOrDefault();

if (page != null)
{
    // Initializes a provider used for bulk manipulation of nodes in the content tree
    TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

    bool orderIsAscending = true;

    // Sorts all child pages under the specified parent page alphabetically in ascending order
    tree.SortNodesAlphabetically(page.NodeID, SiteContext.CurrentSiteID, orderIsAscending);

    // Sorts all child pages under the specified parent page in an ascending order based on the last modification date
    tree.SortNodesByDate(page.NodeID, SiteContext.CurrentSiteID, orderIsAscending);
}

> Back to list of examples

Page deletion

Deleting a page in a single culture



// Gets the culture version that will be deleted
TreeNode page = new DocumentQuery<TreeNode>()
                    .Path("/Example", PathTypeEnum.Single)
                    .OnSite("MySite")
                    .Culture("en-us")
                    .TopN(1)
                    .FirstOrDefault();

if (page != null)
{
    // Deletes the page and moves it to the recycle bin (only the specified culture version)
    page.Delete();

    // Creates search tasks that remove the deleted page from the content of related search indexes
    if (SearchIndexInfoProvider.SearchEnabled)
    {
        SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Delete, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, page.GetSearchID(), page.DocumentID);
    }
}

> Back to list of examples

Deleting all culture versions of a page



// Gets the page that will be deleted
TreeNode page = new DocumentQuery<TreeNode>()
                    .Path("/Example", PathTypeEnum.Single)
                    .OnSite("MySite")
                    .Culture("en-us")
                    .TopN(1)
                    .FirstOrDefault();

if (page != null)
{
    // Indicates whether to delete all culture versions of the page or only the current one
    bool deleteAllCultureVersions = true;
    // Indicates whether the page will be deleted permanently with no restoration possible
    bool deletePermanently = true;

    // Permanently deletes all culture versions of the page and its version history
    page.Delete(deleteAllCultureVersions, deletePermanently);

    // Creates search tasks that remove the deleted page from the content of related search indexes
    if (SearchIndexInfoProvider.SearchEnabled)
    {
        SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Delete, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, page.GetSearchID(), page.DocumentID);
    }
}

> Back to list of examples

Restoring pages from the recycle bin



// Gets the "/Articles/On-Roasts" page from the recycle bin for the current site
VersionHistoryInfo pageVersion = VersionHistoryInfo.Provider.Get()
                                           .WhereEquals("VersionNodeAliasPath", "/Articles/On-Roasts")
                                           .WhereEquals("NodeSiteID", SiteContext.CurrentSiteID)
                                           .TopN(1)
                                           .FirstOrDefault();

// Checks that the deleted page exists in the recycle bin
if (pageVersion != null)
{
    // Creates a new version manager instance and restores the deleted page from the recycle bin
    VersionManager manager = VersionManager.GetInstance(new TreeProvider(MembershipContext.AuthenticatedUser));
    manager.RestoreDocument(pageVersion.VersionHistoryID);
}

> Back to list of examples

Retrieving pages in web applications

Retrieving pages using IPageRetriever



/* The IPageRetriever is a service class that wraps the standard DocumentQuery API. 
 * The service is intended to be used for page retrieval in Xperience web applications (projects using the 
 * Kentico.Xperience.AspNet.Mvc5 or Kentico.Xperience.AspNetCore.WebApp NuGet packages).
 * The service ensures the following default parameterization for each query:
 *  -- Determines whether to retrieve the latest or published versions of pages based on the context. 
 *       -- Latest version is retrieved under preview mode (e.g., when viewing a page in the Pages application)
 *       -- Published version in all other cases
 *        
 *  -- Parameterizes the query to retrieve pages from the current site (determined by the correspondence to the
 *   presentation URL configured in the Sites application in the administration interface).
 *   
 *  -- Retrieves pages only in the culture matching the culture of the current thread (Thread.CurrentThread.CurrentCulture.Name).
 *  
 *  -- Takes into account the 'Combine with default culture' setting for pages that do not exist in the specific culture. 
 *   The setting determines whether to retrieve a page in a site's default culture if the currently requested 
 *   version of the page does not exist.
 *   
 * You can further parameterize the queries (and override their default parameterization) using regular DocumentQuery syntax.
 *
 * See the following code for examples: 
 */

// Initializes an instance of a service used for page retrieval
IPageRetriever pageRetriever = Service.Resolve<IPageRetriever>();

// Retrieves a single page from the current site and using the culture of the current thread
TreeNode page = pageRetriever.Retrieve<TreeNode>(query => query
                    .Path("/Articles/Article", PathTypeEnum.Single)
                    .TopN(1))
                    .FirstOrDefault();


// Retrieves multiple pages of the same type from the current site and using the culture of the current thread
IEnumerable<TreeNode> pages = pageRetriever.Retrieve("Custom.Article", query => query
                    .Path("/Articles", PathTypeEnum.Section));


// Retrieves multiple pages of different types from the current site and using the culture of the current thread
IEnumerable<TreeNode> pagesMultiple = pageRetriever.RetrieveMultiple(query => query
                    .Path("/Articles", PathTypeEnum.Section)
                     // Ensures fields of the specific page types get added to the result
                    .WithCoupledColumns());


// Additionally, you can immediately cache the retrieved pages by providing a caching delegate together with the query
TreeNode pageCached = pageRetriever.Retrieve<TreeNode>(
                        query => query
                            .Path("/Articles/Article", PathTypeEnum.Single)
                            .TopN(1),
                        cache => cache
                             // Constructs a cache key from sufficiently unique values.
                             // Substitute the string placeholders with actual parameters.
                             // Note: This is only an example of a possible cache key format. The purpose of a cache is key is to 
                             // ensure caching with adequate granularity. When deciding on the format of cache keys,
                             // always consider the specific requirements and use cases of your site.
                            .Key($"ClassName|MethodName|NodeAliasPath|count")
                             // Includes path dependency to flush cache when a new child page is created
                             // under the specified path.
                            .Dependencies((_, builder) => builder.PagePath("NodeAliasPath", PathTypeEnum.Children)))
                        .FirstOrDefault();

> Back to list of examples