Content items


List of examples:

Dependency injection

Initialize required services



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

public ContentItemsServices(IContentItemManagerFactory contentItemManagerFactory,
                            IContentQueryExecutor contentQueryExecutor,
                            IUserInfoProvider userInfoProvider)
{
    // 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 content item operations
    this.contentItemManager = contentItemManagerFactory.Create(user.UserID);
    this.contentQueryExecutor = contentQueryExecutor;
}

> Back to list of examples

Content item management

Create content items



/* Content items consist of presentation data and metadata that drive system behavior.
    When creating new items, you must provide instances of 'CreateContentItemParameters' (metadata),
    and '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 content item's content type as
    defined in the field editor.
*/

// The code name of the content type on which the item is based
string STORE_CONTENT_TYPE = "Wonka.CandyStore";

// The content item display name as shown in the admin UI
// Used to generate the item code name
string contentItemDisplayName = "Prague-Hradcany";

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

// Creates a content item metadata object
CreateContentItemParameters createParams = new CreateContentItemParameters(
                                                                STORE_CONTENT_TYPE,
                                                                contentItemDisplayName,
                                                                languageName);

/* Populates content item data. This example assumes a content type with the following fields:
        -- Data type: Text; Code name: StoreName
        -- Data type: Long text; Code name: StoreDescription
        -- Data type: Content items; Code name: StoreReferences
    To find the underlying C# type of other data types, see 'Data type management' in the Kentico documentation.
*/
ContentItemData itemData = new ContentItemData(new Dictionary<string, object>{
    { "StoreName", "Prague-Hradcany" },
    { "StoreDescription", "The first Wonka candy shop in Czech Republic." },
    // A reference to an existing content item
    { "StoreReferences", new List<ContentItemReference>()
                { new ContentItemReference()
                        { Identifier = Guid.Parse("a82ad562-c411-47c9-8fee-ee55428a706f") } } }
});

/* Creates the content item in the database
   IContentItemManager always creates new content items with the 'All content items' location (not under a folder)
*/
await contentItemManager.Create(createParams, itemData);

> Back to list of examples

Generate content item code names



// The 'CreateContentItemParameters' constructor in the 'create a content item'
// example above uses 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 = "Prague-Hradcany";

// '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 content item language variants



/* Content item language variants must be based on existing content items.
    When creating new items, provide instances of 'CreateLanguageVariantParameters' (metadata),
    and 'ContentItemData' (data).
*/

// Gets the id of the item on which to base the new language variants
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                },
                // Retrieves the latest version of items
                new ContentQueryExecutionOptions() { ForPreview = true });

// Prepares the language variant metadata
string languageVariantDisplayName = "Prague-Hradcany-de";
// Must correspond to a language defined in the 'Languages' application.
string languageName = "de";
var languageVariantParams =
                new CMS.ContentEngine.CreateLanguageVariantParameters(itemId.First(),
                                                    languageVariantDisplayName,
                                                    languageName);

/* Prepares the item data for the target language variant
    This example assumes a content type with the following fields:
        -- Data type: Text; Code name: StoreName
        -- Data type: Long text; Code name: StoreDescription
        -- Data type: Content items; Code name: StoreReferences
    To find the underlying C# type of other data types, see 'Data type management' in the documentation. */
ContentItemData itemData = new ContentItemData(new Dictionary<string, object>{
    { "StoreName", "Prag-Hradcany" },
    { "StoreDescription", "Der erste Wonka-Süßwarenladen in der Tschechischen Republik." },
    // Creates a reference to an existing content item
    { "StoreReferences", new List<ContentItemReference>()
                { new ContentItemReference()
                        { Identifier = Guid.Parse("a82af562-c411-47c9-8fee-ee55428a706f") }
                }
    }
});

if (await contentItemManager.TryCreateLanguageVariant(languageVariantParams, itemData))
{
    Console.WriteLine("Language variant successfully created.");
}
else
    throw new Exception("Something went wrong.");

> Back to list of examples

Publish content items



// This example demonstrates how to publish content items
// That is, move an item from 'Draft' (or the final step in a workflow) to 'Published'

// Gets the id of the item to publish
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";

ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                },
                // Retrieves the latest version of items
                new ContentQueryExecutionOptions() { ForPreview = true });

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

> Back to list of examples

Schedule publishing for content items



// This example demonstrates how to schedule content items 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 item to schedule
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";

ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                },
                // Retrieves the latest version of items
                new ContentQueryExecutionOptions() { ForPreview = true });

/* Schedules the item to be published
   - Throws an exception if the item'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 item gets published immediately.
   - For items under workflow, 'SchedulePublish' bypasses all remaining workflow steps
     and moves the item to a system step representing the 'Scheduled' status in the UI.
*/
await contentItemManager.SchedulePublish(itemId.First(), languageName, publishDateTime);

> Back to list of examples

Cancel scheduled publishing for content items



// This example demonstrates how to cancel a content item's scheduled publishing

// Gets the id of the item for which publishing will be canceled
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";

ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                },
                // Retrieves the latest version of items
                new ContentQueryExecutionOptions() { ForPreview = true });


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

> Back to list of examples

Unpublish content items



// This example demonstrates how to unpublish content items --
// move the items from the 'Published' status to 'Unpublished'.

// Gets the id of the item to unpublish
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";

ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                });

// Unpublishes the content item
if (await contentItemManager.TryUnpublish(itemId.First(), languageName))
{
    Console.WriteLine("Item successfully unpublished.");
}
else
    throw new Exception("Something went wrong.");

> Back to list of examples

Schedule unpublishing for content items



// This example demonstrates how to schedule content items 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 item to schedule
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";

ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                },
                // Retrieves the latest version of items
                new ContentQueryExecutionOptions() { ForPreview = true });

/* Schedules the item to be unpublished
   - The item must either be published or scheduled to be published. If the item 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 item gets unpublished immediately.
*/
await contentItemManager.ScheduleUnpublish(itemId.First(), languageName, unpublishDateTime);

> Back to list of examples

Cancel scheduled unpublishing for content items



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

// Gets the id of the item for which unpublishing will be canceled
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";

ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                },
                // Retrieves the latest version of items
                new ContentQueryExecutionOptions() { ForPreview = true });


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

> Back to list of examples

Delete content items



// Demonstrates how to delete content items

// Gets the id of the item to delete
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";

ContentItemQueryBuilder builder =
    new ContentItemQueryBuilder()
            .ForContentType(STORE_CONTENT_TYPE, q =>
            {
                q.TopN(1)
                    .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
            });

var itemId = await contentQueryExecutor
            .GetResult<int>(builder, rowData =>
            {
                var contentItemId = rowData.ContentItemID;
                return contentItemId;
            });

// Deletes the item language variant from the database.
// If this is was the last language variant remaining,
// deletes all associated metadata as well.
await contentItemManager.Delete(itemId.First(), languageName);

> Back to list of examples

Create content item drafts



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

// Gets the id of the item
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";
ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                });

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

> Back to list of examples

Update content item drafts



// This example demonstrates how to update content items

// Gets the id of the item to update
string STORE_CONTENT_TYPE = "Wonka.CandyStore";
string languageName = "en";
ContentItemQueryBuilder builder =
        new ContentItemQueryBuilder()
                .ForContentType(STORE_CONTENT_TYPE, q =>
                {
                    q.TopN(1)
                        .Where(w => w.WhereEquals("StoreName", "Prague-Hradcany"));
                });

var itemId = await contentQueryExecutor
                .GetResult<int>(builder, rowData =>
                {
                    var contentItemId = rowData.ContentItemID;
                    return contentItemId;
                },
                new ContentQueryExecutionOptions() { ForPreview = true });

ContentItemData updatedItemData = new ContentItemData(new Dictionary<string, object> {
        { "StoreName", "Prague-Hradcany" },
        { "StoreDescription", "The first Wonka candy shop in Czech Republic." },
        // A reference to an existing content item
        { "StoreReferences", new List<ContentItemReference>()
                    { new ContentItemReference()
                            { Identifier = Guid.Parse("a82ad562-c411-47c9-8fee-ee55428a706f") } } }
    });

await contentItemManager.TryUpdateDraft(itemId.First(),
                                        languageName,
                                        updatedItemData);

> Back to list of examples

Content item assets

Upload content item assets from files



// This example shows how to upload content item assets from a file
// on the filesystem. The process can be used both when creating or updating assets.


// Gets the metadata for content item creation.
// Identical to regular content item operations.
string LOGO_CONTENT_TYPE = "Wonka.StoreLogo";
string contentItemDisplayName = "Prague-Hradcany-Logo";
string languageName = "en";
CreateContentItemParameters createParams = new CreateContentItemParameters(
                                                                LOGO_CONTENT_TYPE,
                                                                contentItemDisplayName,
                                                                languageName);

// Gets the file information from a file on the filesystem
var assetPath = "C:/data/images/hradcany-logo.jpg";
var file = new FileInfo(assetPath);

// Creates a metadata object that describes the uploaded asset
var assetMetadata = new ContentItemAssetMetadata()
{
    Extension = file.Extension,
    Identifier = Guid.NewGuid(),
    LastModified = DateTime.Now,
    Name = file.Name,
    Size = file.Length
};

// Creates a source object used to locate the asset and merges it with the metadata object
var fileSource = new ContentItemAssetFileSource(file.FullName, false);
var assetMetadataWithSource = new ContentItemAssetMetadataWithSource(fileSource, assetMetadata);

/* Populates content item data. This example assumes a content type with the following fields:
        -- Data type: Content item asset; Code name: StoreLogo
    To find the underlying C# type of other data types, see 'Data type management' in the Kentico documentation.
*/
ContentItemData itemData = new ContentItemData(new Dictionary<string, object>{
    { "StoreLogo", assetMetadataWithSource }
});

// Creates the content item in the database
await contentItemManager.Create(createParams, itemData);

> Back to list of examples

Upload content item assets from data streams



// This example shows how to upload content item assets from 'System.IO.Stream'
// The process can be used both when creating or updating assets.


// Gets the metadata for content item creation.
// Identical to regular content item operations.
string LOGO_CONTENT_TYPE = "Wonka.StoreLogo";
string contentItemDisplayName = "Prague-Hradcany-Logo";
string contentItemCodeName = "Prague-Hradcany-CandyStore-Logo";
string languageName = "en";
CreateContentItemParameters createParams = new CreateContentItemParameters(
                                                                LOGO_CONTENT_TYPE,
                                                                contentItemCodeName,
                                                                contentItemDisplayName,
                                                                languageName);

// Opens a 'System.IO.Stream' with the asset binary
var assetPath = "C:/data/images/hradcany-logo.jpg";
var fileStream = File.Open(assetPath, FileMode.Open);

// Creates a metadata object that describes the uploaded asset
var assetMetadata = new ContentItemAssetMetadata()
{
    Extension = Path.GetExtension(assetPath),
    Identifier = Guid.NewGuid(),
    LastModified = DateTime.Now,
    Name = Path.GetFileName(assetPath),
    Size = fileStream.Length
};

// Creates a source object used to locate the asset and merges it with the metadata object
var fileSource = new ContentItemAssetStreamSource((CancellationToken cancellationToken) => Task.FromResult<Stream>(fileStream));
var assetMetadataWithSource = new ContentItemAssetMetadataWithSource(fileSource, assetMetadata);

/* Populates content item data. This example assumes a content type with the following fields:
        -- Data type: Content item asset; Code name: StoreLogo
    To find the underlying C# type of other data types, see 'Data type management' in the Kentico documentation.
*/
ContentItemData itemData = new ContentItemData(new Dictionary<string, object>{
    { "StoreLogo", assetMetadataWithSource }
});

// Creates the content item in the database
await contentItemManager.Create(createParams, itemData);

> Back to list of examples