Pages


List of examples:

Dependency injection

Initialize required services

C#


// Initializes all services and provider classes used within
// the API examples on this page using dependency injection
private readonly IWebPageManager webPageManager;
private readonly IContentQueryExecutor contentQueryExecutor;

public PageServices(IContentQueryExecutor contentQueryExecutor,
                    IWebPageManagerFactory webPageManagerFactory,
                    IUserInfoProvider userInfoProvider,
                    IWebsiteChannelContext websiteChannelContext)
{
    // Gets the user responsible for management operations.
    // The user is used only for auditing purposes,
    // e.g., to be shown as the creator in 'Created by' fields.
    // The user's permissions are not checked for any of the operations.
    UserInfo user = userInfoProvider.Get("JimmieWonka");

    // Creates an instance of the manager class facilitating page operations
    this.webPageManager = webPageManagerFactory.Create(websiteChannelContext.WebsiteChannelID, user.UserID);
    this.contentQueryExecutor = contentQueryExecutor;
}

> Back to list of examples

Page management

Create pages

C#


/* Web pages consist of presentation data and metadata that drive system behavior.
   When creating new pages, you must provide an instance of 'CreateWebPageParameters' (metadata),
   which contains a 'ContentItemParameters' instance storing 'ContentItemData' (data).
   'ContentItemData' is a dictionary that stores item values in a <fieldName>:<fieldValue> format.
   The dictionary must contain records that correspond to the fields of the page's content type as
   defined in the field editor.
*/

// The code name of the content type on which the page is based
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";

// The page display name shown in the admin UI
string pageDisplayName = "Review of the Wonka Chocolate Excellence";

// The initial language in which the page gets created
// Must correspond to a language defined in the 'Languages' application
string languageName = "en";

/* Populates the page's content item data. This example assumes a content type with the following fields:
        -- Data type: Text; Code name: ReviewTitle
        -- Data type: Date; Code name: ReviewPublishDate
        -- Data type: Content items; Code name: ReviewImage
        -- Data type: Long text; Code name: ReviewText
        -- Data type: Content items; Code name: ReviewRelatedReviews
    To find the underlying C# type of other data types, see 'Data type management' in the Kentico documentation.
*/
var itemData = new ContentItemData(new Dictionary<string, object>{
    { "ReviewTitle", "Wonka Chocolate Excellence" },
    { "ReviewPublishDate", DateTime.Now },
    { "ReviewImage", new List<ContentItemReference>()
                { new ContentItemReference()
                        { Identifier = Guid.Parse("c4b1f72e-42d7-41dd-8130-00cd118f5f20")}}},
    { "ReviewText", "<Text of the review>" },
    { "ReviewRelatedReviews", new List<ContentItemReference>()
                { new ContentItemReference()
                        { Identifier = Guid.Parse("c6f453db-dd39-46ac-bdb1-78bdb5b20a9e")}}}
});

// Creates a page metadata object
var contentItemParameters = new ContentItemParameters(REVIEW_CONTENT_TYPE, itemData);
var createPageParameters = new CreateWebPageParameters(pageDisplayName,
                                                       languageName,
                                                       contentItemParameters);

// Creates the page in the database
await webPageManager.Create(createPageParameters);

> Back to list of examples

Clone pages

C#


/* When cloning a page you must provide an instance of 'ClonePageParameters', 
   which contains the ID of the page to clone, the language variant to
   clone, the display name and the url slug of the new page.                
 */

// Gets the ID of the source page that you want to clone
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    },
                    // Retrieves the latest version of the page
                    new ContentQueryExecutionOptions() { ForPreview = true });

// The language variant that you want to clone
string languageName = "en";

// The display name of the new page shown in the admin UI
string displayName = "Wonka Chocolate Brilliance";

// The url slug of the new page
string urlSlug = "wonka-brilliance";

// Creates a parameters object for the cloning operation
var cloneParameters = new ClonePageParameters
(
    pageId.First(),
    languageName,
    displayName,
    urlSlug
);

// Creates the new cloned page within the database
await webPageManager.Clone(cloneParameters);

> Back to list of examples

Create a folder for pages

C#


// Demonstrates how to create folders for better page organization

// The folder display name shown in the admin UI
string folderDisplayName = "Reviews of chocolate";

// The initial language in which the folder gets created
// Must correspond to a language defined in the 'Languages' application
string languageName = "en";

// Creates a folder metadata object
var createFolderParameters = new CreateFolderParameters(folderDisplayName,
                                                        languageName);

// Creates the folder in the database
await webPageManager.CreateFolder(createFolderParameters);

> Back to list of examples

Generate code names

C#


// The 'CreateWePageParameters' constructor in the 'create pages'
// example and 'CreateFolderParameters' in the 'create folders' example above
// use API that automatically generates a unique code name for
// the content item being created.
// You can also transparently generate code names using 'IContentItemCodeNameProvider'.

// An example content item display name
string displayName = "Review of the Wonka Chocolate Excellence";

// 'IContentItemCodeNameProvider.Get' ensures a unique code name from the provided
// string by appending a random suffix in case an identical code name already exists
string codeName = await contentItemCodeNameProvider.Get(displayName);

// Use the 'codeName' value in content item APIs...

> Back to list of examples

Create page language variants

C#


/* Page language variants must be based on existing pages.
   When creating new page variants, prepare 'ContentItemData' (data) and provide
   an instance of 'CMS.Websites.CreateLanguageVariantParameters' (metadata).
*/

// Gets the id of the page on which to base the new language variant
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    },
                    // Retrieves the latest version of the page
                    new ContentQueryExecutionOptions() { ForPreview = true });

// The new language variant display name shown in the admin UI
string variantDisplayName = "Rezension der Wonka Chocolate Excellence";

// The language of the new variant
// Must correspond to a language defined in the 'Languages' application
string languageName = "de";

// Prepares the page's content item data for the new language variant
var itemData = new ContentItemData(new Dictionary<string, object>{
    { "ReviewTitle", "Wonka Schokoladenexzellenz" },
    { "ReviewPublishDate", DateTime.Now },
    { "ReviewImage", new List<ContentItemReference>()
                { new ContentItemReference()
                        { Identifier = Guid.Parse("c4b1f72e-42d7-41dd-8130-00cd118f5f20")}}},
    { "ReviewText", "<Translated text of the review>" },
    { "ReviewRelatedReviews", new List<ContentItemReference>()
                { new ContentItemReference()
                        { Identifier = Guid.Parse("c6f453db-dd39-46ac-bdb1-78bdb5b20a9e")}}}
});

// Prepares the metadata needed for the new language variant
var createLanguageVariantParameters =
            new CMS.Websites.CreateLanguageVariantParameters(pageId.First(),
                                                             languageName,
                                                             variantDisplayName,
                                                             itemData);

// Creates the new language variant in the database
if (await webPageManager.TryCreateLanguageVariant(createLanguageVariantParameters))
{
    Console.WriteLine("Language variant successfully created.");
}
else
    throw new Exception("Something went wrong");

> Back to list of examples

Create page drafts

C#


// Demonstrates how to create a new draft version for a page with the 'Published' or 'Unpublished' status

// The language of the page variant for which the draft is created
string languageName = "en";

// Gets the id of the page
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    });

// Creates a new draft version of the page
if (await webPageManager.TryCreateDraft(pageId.First(), languageName))
{
    Console.WriteLine($"New draft version successfully created.");
}
else
    throw new Exception("Something went wrong.");

> Back to list of examples

Update page drafts

C#


// Demonstrates how to update pages

// The language of the page variant that is updated
string languageName = "en";

// Gets the id of the page to update
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    },
                    // Retrieves the latest version of the page
                    new ContentQueryExecutionOptions() { ForPreview = true });

// Prepares updated content item data for the page
var itemData = new ContentItemData(new Dictionary<string, object>{
    { "ReviewTitle", "Review of the Wonka Chocolate Excellence" },
    { "ReviewPublishDate", DateTime.Now },
    { "ReviewImage", new List<ContentItemReference>()
                { new ContentItemReference()
                        { Identifier = Guid.Parse("c4b1f72e-42d7-41dd-8130-00cd118f5f20")}}},
    { "ReviewText", "<Updated text of the review>" },
    { "ReviewRelatedReviews", new List<ContentItemReference>()
                { new ContentItemReference()
                        { Identifier = Guid.Parse("c6f453db-dd39-46ac-bdb1-78bdb5b20a9e")}}}
});

// Updates the draft with the new item data
if (await webPageManager.TryUpdateDraft(pageId.First(), languageName, new UpdateDraftData(itemData)))
{
    Console.WriteLine($"Draft version successfully updated.");
}
else
    throw new Exception("Something went wrong.");

> Back to list of examples

Publish pages

C#


// Demonstrates how to publish pages
// That is, move a page from 'Draft' (or the final step in a workflow) to 'Published'

// The language of the page variant that will be published
string languageName = "en";

// Gets the id of the page to publish
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    },
                    // Retrieves the latest version of the page
                    new ContentQueryExecutionOptions() { ForPreview = true });

// Publishes the page
// For pages under workflow, 'TryPublish' bypasses all remaining workflow steps and moves the page to the 'Published' status
if (await webPageManager.TryPublish(pageId.First(), languageName))
{
    Console.WriteLine("Page successfully published.");
}
else
    throw new Exception("Something went wrong.");

> Back to list of examples

Schedule publishing for pages

C#


// This example demonstrates how to schedule pages to be published at a future date and time

// Prepares a publish date 7 days from the current date and time
var publishDateTime = DateTime.Now.AddDays(7);

// Gets the id of the page to schedule
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
string languageName = "en";

var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    },
                    // Retrieves the latest version of the page
                    new ContentQueryExecutionOptions() { ForPreview = true });

/* Schedules the page to be published
   - Throws an exception if the page's status is not 'VersionStatus.Draft' or 'VersionStatus.InitialDraft' (this includes custom workflow steps).
   - If the specified date and time is not in the future, the page gets published immediately.
   - For pages  under workflow, 'SchedulePublish' bypasses all remaining workflow steps
     and moves the page to a system step representing the 'Scheduled' status in the UI.
*/
await webPageManager.SchedulePublish(pageId.First(), languageName, publishDateTime);

> Back to list of examples

Cancel scheduled publishing for pages

C#


// This example demonstrates how to cancel scheduled publishing of a page

// Gets the id of the page for which publishing will be canceled
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
string languageName = "en";

var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    },
                    // Retrieves the latest version of the page
                    new ContentQueryExecutionOptions() { ForPreview = true });


// Checks that the page is scheduled to be published
if (await webPageManager.IsPublishScheduled(pageId.First(), languageName))
{
    /* Cancels the scheduled publishing for the page
       - For pages under workflow, 'CancelScheduledPublish' returns the page to the final custom-defined workflow step.
       - If the page is also scheduled to be unpublished, the unpublish is canceled as well.
    */
    await webPageManager.CancelScheduledPublish(pageId.First(), languageName);
}

> Back to list of examples

Unpublish pages

C#


// Demonstrates how to unpublish published pages

// The language of the page variant that will be unpublished
string languageName = "en";

// Gets the id of the page to unpublish
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    });

// Unpublishes the page
if (await webPageManager.TryUnpublish(pageId.First(), languageName))
{
    Console.WriteLine("Page successfully unpublished.");
}
else
    throw new Exception("Something went wrong.");

> Back to list of examples

Schedule unpublishing for pages

C#


// This example demonstrates how to schedule pages to be unpublished at a future date and time

// Prepares an unpublish date 7 days from the current date and time
var unpublishDateTime = DateTime.Now.AddDays(7);

// Gets the id of the page to schedule
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
string languageName = "en";

var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    },
                    // Retrieves the latest version of the page
                    new ContentQueryExecutionOptions() { ForPreview = true });

/* Schedules the page to be unpublished
   - The page must either be published or scheduled to be published. If the page is scheduled to be published,
     the publish date must be before the specified unpublish date. Otherwise the method throws an exception.
   - If the specified unpublish date and time is not in the future, the page gets unpublished immediately.
*/
await webPageManager.ScheduleUnpublish(pageId.First(), languageName, unpublishDateTime);

> Back to list of examples

Cancel scheduled unpublishing for pages

C#


// This example demonstrates how to cancel a page's scheduled unpublishing

// Gets the id of the page for which unpublishing will be canceled
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
string languageName = "en";

var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    },
                    // Retrieves the latest version of the page
                    new ContentQueryExecutionOptions() { ForPreview = true });


// Checks that the page is scheduled to be unpublished
if (await webPageManager.IsUnpublishScheduled(pageId.First(), languageName))
{
    // Cancels the scheduled unpublishing for the page
    await webPageManager.CancelScheduledUnpublish(pageId.First(), languageName);
}

> Back to list of examples

Move pages

C#


// Demonstrates how to move pages across the content tree

// Gets the id of the page to be moved
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    });

// Gets the id of the new parent page under which the desired page will be moved
string PARENT_PAGE_CONTENT_TYPE = "Wonka.ReviewSection";
builder = new ContentItemQueryBuilder()
                .ForContentType(PARENT_PAGE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                });

var parentId = await contentQueryExecutor
                .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                {
                    var pageRowId = rowData.ContentItemID;
                    return pageRowId;
                });

// Prepares the metadata needed for the page move
var movePageParameters = new MoveWebPageParameters(pageId.First(), parentId.First());

// Moves the page in the content tree
await webPageManager.Move(movePageParameters);

> Back to list of examples

Secure pages

C#


// Demonstrates how to change the security settings of page

// Gets the id of the page for which security settings will be updated
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    });

// The new security settings for the page
bool isSecured = true;

// Changes the security settings for the page
await webPageManager.UpdateSecuritySettings(pageId.First(), isSecured);

> Back to list of examples

Delete pages

C#


// Demonstrates how to delete a page

// Language of the page variant to be deleted
string languageName = "en";

// Gets the id of the page to be deleted
string REVIEW_CONTENT_TYPE = "Wonka.ChocolateReview";
var builder = new ContentItemQueryBuilder()
                    .ForContentType(REVIEW_CONTENT_TYPE, q =>
                    {
                        q.TopN(1)
                            .Where(w => w.WhereEquals("ReviewTitle", "Wonka Chocolate Excellence"));
                    });

var pageId = await contentQueryExecutor
                    .GetWebPageResult<int>(builder: builder, resultSelector: rowData =>
                    {
                        var pageRowId = rowData.ContentItemID;
                        return pageRowId;
                    });

// Deletes the language variant of the page from the database.
// If this was the last language variant remaining,
// all associated page metadata is also deleted.
await webPageManager.Delete(pageId.First(), languageName);

> Back to list of examples