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
// e.g., shown as the creator in 'Created by' fields
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;
}
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);
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...
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.");
Publish content items
// This example demonstrates how to publish content items
// That is, how to move an item from 'Draft' 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
if (await contentItemManager.TryPublish(itemId.First(), languageName))
{
Console.WriteLine("Item successfully published");
}
else
throw new Exception("Something went wrong.");
Archive content items
// This example demonstrates how to archive content items --
// move the items from the 'Published' status to 'Archived'.
// Gets the id of the item to archive
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;
});
// Archives the content item
if (await contentItemManager.TryArchive(itemId.First(), languageName))
{
Console.WriteLine($"Item successfully archived");
}
else
throw new Exception("Something went wrong.");
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);
Create content item drafts
// Demonstrates how to create a new version in the 'Draft' step
// for a content item in 'Published' or 'Archived' step.
// 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 version in the 'Draft' step
if (await contentItemManager.TryCreateDraft(itemId.First(), languageName))
{
Console.WriteLine($"New draft version successfully created.");
}
else
throw new Exception("Something went wrong.");
Update content item drafts
// This example demonstrates how to update items in the 'Draft' state
// 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);
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);
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);