Orchardcore content items

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore content items is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for working with Orchard Core content items. Covers the content item lifecycle, IContentManager API including batched GetAsync, content item JSON structure, querying with YesSql and the IDX_ContentItemIndex_ContentItemId index, content handlers, recipe import and export, links to the Contents

How to use this skill

Skill file

Orchard Core Content Items - Prompt Templates

Working with Content Items

You are an Orchard Core expert. Generate code and configuration for managing content items in Orchard Core.

Guidelines

current session. If validation follows a mutation, call

ISession.CancelAsync() explicitly when the result fails.

Content Item Lifecycle

A content item progresses through the following states:

  1. New - Created in memory with NewAsync, not yet persisted.
  2. Draft - Saved but not published. Only visible to editors.
  3. Published - Live and visible to all users. Sets Published = true and Latest = true.
  4. Unpublished - Previously published, now reverted to draft state.
  5. Removed - Soft-deleted from the system.

When a published content item is edited, a new draft version is created while the published version remains live. Publishing the draft replaces the previous published version.

Content Item JSON Structure

{
  "ContentItemId": "{{unique-content-item-id}}",
  "ContentItemVersionId": "{{unique-version-id}}",
  "ContentType": "{{ContentTypeName}}",
  "DisplayText": "{{Display Title}}",
  "Latest": true,
  "Published": true,
  "CreatedUtc": "2025-01-01T00:00:00Z",
  "ModifiedUtc": "2025-01-01T00:00:00Z",
  "PublishedUtc": "2025-01-01T00:00:00Z",
  "Owner": "{{userId}}",
  "Author": "{{userName}}",
  "TitlePart": {
    "Title": "{{Display Title}}"
  },
  "AutoroutePart": {
    "Path": "{{url-slug}}",
    "SetHomepage": false
  },
  "{{ContentTypeName}}": {
    "{{FieldName}}": {
      "Text": "{{field value}}"
    }
  }
}

IContentManager API

Use IContentManager to perform all content item operations:

public sealed class {{ServiceName}}
{
    private readonly IContentManager _contentManager;

    public {{ServiceName}}(IContentManager contentManager)
    {
        _contentManager = contentManager;
    }

    public async Task ManageContentAsync()
    {
        // Create a new content item in memory (not yet saved).
        var contentItem = await _contentManager.NewAsync("{{ContentTypeName}}");

        // Persist the content item as a draft.
        await _contentManager.CreateAsync(contentItem, VersionOptions.Draft);

        // Retrieve a content item by its ID (latest version).
        var latest = await _contentManager.GetAsync(
            contentItem.ContentItemId, VersionOptions.Latest);

        // Retrieve the published version of a content item.
        var published = await _contentManager.GetAsync(
            contentItem.ContentItemId, VersionOptions.Published);

        // Retrieve several content items in one query (published by default).
        var items = await _contentManager.GetAsync(
            ["{{id1}}", "{{id2}}"], VersionOptions.Published);

        // Update an existing content item.
        await _contentManager.UpdateAsync(contentItem);

        // Publish a draft content item.
        await _contentManager.PublishAsync(contentItem);

        // Unpublish a published content item (revert to draft).
        await _contentManager.UnpublishAsync(contentItem);

        // Remove (soft-delete) a content item. The result is false when a
        // removing handler cancels the operation.
        var removed = await _contentManager.RemoveAsync(contentItem);
    }
}

Reads by id (GetAsync(id) and GetAsync(ids)) use the IDX_ContentItemIndex_ContentItemId SQL index added in Orchard Core 4.0 (ContentItemId, DocumentId, Published, Latest). Prefer one batched GetAsync(ids) over a loop of single reads. GetVersionAsync seeks IDX_ContentItemIndex_ContentItemVersionId, and filters on one content type or owner seek IDX_ContentItemIndex_ContentType / IDX_ContentItemIndex_Owner (see orchardcore-content-queries).

When a content type generates its title from a TitlePart pattern, the pattern is also evaluated when a version is published (Orchard Core 4.0), so republishing an item sets its display text from the pattern, at most once per item per request.

Linking to the Contents Admin List

/Admin/Contents/ContentItems accepts several content types or stereotypes, as repeated or comma-separated values (Orchard Core 4.0); single values work as before:

/Admin/Contents/ContentItems?contentTypeId=Article&contentTypeId=BlogPost
/Admin/Contents/ContentItems?contentTypeId=Article,BlogPost
/Admin/Contents/ContentItems?stereotype=Widget,Page

Use these URLs in admin menu links (see orchardcore-admin-menu) to give editors a list scoped to a family of types. Column providers of the list receive the filtered types and stereotypes under ContentsAdminList.ContentTypesKey and ContentsAdminList.StereotypesKey (see orchardcore-admin-lists).

Accessing Parts and Fields

Content items store data in parts and fields. Use TryGet<T>() and Get<T>() for reads, and GetOrCreate<T>() when you intentionally need a writable part instance:

public sealed class {{ServiceName}}
{
    private readonly IContentManager _contentManager;

    public {{ServiceName}}(IContentManager contentManager)
    {
        _contentManager = contentManager;
    }

    public async Task ReadPartAndFieldValuesAsync(string contentItemId)
    {
        var contentItem = await _contentManager.GetAsync(
            contentItemId, VersionOptions.Published);

        // Access a well-known part using the strongly-typed helper.
        var title = contentItem.TryGet<TitlePart>(out var titlePart)
            ? titlePart.Title
            : null;

        // Access a named part as a content element.
        var customPart = contentItem.Get<ContentPart>("{{ContentTypeName}}");

        // Access a field within the named part.
        var textField = customPart?.Get<TextField>("{{FieldName}}");
        var fieldValue = textField?.Text;
    }

    public async Task SetPartAndFieldValuesAsync()
    {
        var contentItem = await _contentManager.NewAsync("{{ContentTypeName}}");

        // Set a well-known part value.
        contentItem.Alter<TitlePart>(part =>
        {
            part.Title = "{{Title}}";
        });

        // Set a field value on a named part.
        contentItem.Alter<ContentPart>("{{ContentTypeName}}", part =>
        {
            part.Alter<TextField>("{{FieldName}}", field =>
            {
                field.Text = "{{value}}";
            });
        });

        await _contentManager.CreateAsync(contentItem, VersionOptions.Published);
    }
}

Querying Content Items with YesSql

Use ISession to query content items through YesSql indexes:

public sealed class {{ServiceName}}
{
    private readonly ISession _session;

    public {{ServiceName}}(ISession session)
    {
        _session = session;
    }

    public async Task<IEnumerable<ContentItem>> QueryContentItemsAsync()
    {
        // Query published content items of a specific type.
        var items = await _session
            .Query<ContentItem, ContentItemIndex>(index =>
                index.ContentType == "{{ContentTypeName}}"
                && index.Published)
            .ListAsync();

        return items;
    }

    public async Task<ContentItem?> FindByDisplayTextAsync(string displayText)
    {
        // Query by display text.
        var item = await _session
            .Query<ContentItem, ContentItemIndex>(index =>
                index.DisplayText == displayText
                && index.Published)
            .FirstOrDefaultAsync();

        return item;
    }
}

Content Handlers

Implement IContentHandler to respond to content lifecycle events. Handlers are invoked by IContentManager during create, update, publish, unpublish, and remove operations:

public sealed class {{HandlerName}} : ContentHandlerBase
{
    private readonly ILogger<{{HandlerName}}> _logger;

    public {{HandlerName}}(ILogger<{{HandlerName}}> logger)
    {
        _logger = logger;
    }

    public override Task PublishedAsync(PublishContentContext context)
    {
        if (context.ContentItem.ContentType == "{{ContentTypeName}}")
        {
            _logger.LogInformation(
                "Content item '{DisplayText}' was published.",
                context.ContentItem.DisplayText);
        }

        return Task.CompletedTask;
    }

    public override Task RemovedAsync(RemoveContentContext context)
    {
        if (context.ContentItem.ContentType == "{{ContentTypeName}}")
        {
            _logger.LogInformation(
                "Content item '{DisplayText}' was removed.",
                context.ContentItem.DisplayText);
        }

        return Task.CompletedTask;
    }
}

Register the handler in a Startup class:

public sealed class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IContentHandler, {{HandlerName}}>();
    }
}

Common handler methods include:

CreatingAsync and UpdatingAsync run before the corresponding persistence

operation. CreatedAsync and UpdatedAsync run after it. Use the matching

context type (CreateContentContext or UpdateContentContext) and do not

treat an update as a create operation.

Validate and Cancel Explicitly

ValidateAsync only invokes validation handlers and returns the result. It no

longer cancels the session for an invalid item. Cancel a preceding mutation

explicitly when required:

public sealed class ContentValidationService
{
    private readonly IContentManager _contentManager;
    private readonly ISession _session;

    public ContentValidationService(
        IContentManager contentManager,
        ISession session)
    {
        _contentManager = contentManager;
        _session = session;
    }

    public async Task<bool> UpdateAsync(ContentItem contentItem)
    {
        await _contentManager.UpdateAsync(contentItem);

        var result = await _contentManager.ValidateAsync(contentItem);
        if (!result.Succeeded)
        {
            await _session.CancelAsync();
            return false;
        }

        return true;
    }
}

When a removing handler sets RemoveContentContext.Cancel, check the boolean

returned by RemoveAsync to detect the canceled operation.

Content Item Import via Recipes

Use the content recipe step to import content items. Use a deployment plan when exporting content.

{
  "steps": [
    {
      "name": "Content",
      "data": [
        {
          "ContentItemId": "{{unique-id-1}}",
          "ContentType": "{{ContentTypeName}}",
          "DisplayText": "{{Title}}",
          "Latest": true,
          "Published": true,
          "TitlePart": {
            "Title": "{{Title}}"
          },
          "{{ContentTypeName}}": {
            "{{FieldName}}": {
              "Text": "{{value}}"
            }
          }
        }
      ]
    }
  ]
}

ContentElement, ContentPart, and ContentField

public sealed class {{PartName}} : ContentPart
{
    public string? Subtitle { get; set; }
    public bool IsFeatured { get; set; }
}
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.