Orchardcore workflows

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore workflows is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for authoring Orchard Core 4.0 workflows and custom workflow activities. Covers the workflow designer, drafts, publishing and versions, typed variables and activity outputs, per-expression syntaxes (Literal, Liquid, JavaScript), branching, workflows as activities, real-time updates, the execut

How to use this skill

Skill file

Orchard Core Workflows

A workflow type (definition) is a set of activities connected by outcome transitions. Events start or resume a workflow; tasks do work and return outcomes. Orchard Core 4.0 replaces the jsPlumb editor with a Vue designer, saves edits to a draft, and creates a numbered version on each publish; every instance runs on the version it started on.

Enable the features

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "OrchardCore.Workflows",
        "OrchardCore.Workflows.Http",
        "OrchardCore.Workflows.Timers",
        "OrchardCore.Contents"
      ],
      "disable": []
    }
  ]
}

| Feature | Provides |

|---|---|

| OrchardCore.Workflows | Designer, engine, core activities, trimming, journal, variables, expression syntaxes. Depends on OrchardCore.Liquid and OrchardCore.Scripting. |

| OrchardCore.Workflows.Http | HTTP events and tasks, signals, signal_url, HTTP script functions. |

| OrchardCore.Workflows.Timers | TimerEvent. |

| OrchardCore.Workflows.Session | CommitTransactionTask. |

| OrchardCore.SignalR (separate module) | Turns on real-time updates of the designer and instance pages. |

User tasks (UserTaskEvent) are available when Workflows, Contents and Roles are enabled. Enable every feature that contributes an activity before importing a workflow that uses it.

The designer

Overrides of WorkflowType/Edit, Workflow/Details, the activity create/edit pages or Activity_DesignReadOnly no longer apply; remove or rewrite them.

Drafts, publishing and versions

Keep only the most recent versions per workflow (versions that instances run on are never deleted; every version is kept by default):

{
  "OrchardCore": {
    "Workflows": {
      "Versions": {
        "MaxCount": 20
      }
    }
  }
}

The WorkflowType recipe step

WorkflowTypeStep deserializes each data entry into WorkflowType:

| Property | Notes |

|---|---|

| WorkflowTypeId | Stable id. An existing id is updated: the import becomes the next version, its instances are kept on their versions, and its draft is discarded. A new id is created. |

| Name, IsEnabled | Not versioned. |

| IsSingleton, IsSingletonPerCorrelation, LockTimeout, LockExpiration, DeleteFinishedWorkflows | Execution settings. |

| IsActivity | Usable by Execute Workflow. |

| BranchingMode | "FirstOnly" (default) or "All". |

| FaultOnScriptErrors, RecordActivityData | Both default to false when omitted (the designer checks Record activity data for new workflows). |

| Variables | Name, TypeName, DefaultValue (JSON), Description, IsInput, IsOutput. |

| Activities | ActivityId, Name (activity type name), X, Y, IsStart, Properties. |

| Transitions | SourceActivityId, SourceOutcomeName, DestinationActivityId. |

Exports omit Id and VersionId. On import, an HttpRequestEvent whose Url is missing or was generated by another site is given a new URL; a valid one is kept, so re-importing does not create a version.

Common activity Properties keys: ActivityMetadata (Title), expressions as { "Expression": "...", "Syntax": "Liquid" }, OutputBindings ({ "outputName": "variableName" }) and ActivityRetryPolicy on tasks.

{
  "steps": [
    {
      "name": "WorkflowType",
      "data": [
        {
          "WorkflowTypeId": "orderhook",
          "Name": "Order webhook",
          "IsEnabled": true,
          "BranchingMode": "FirstOnly",
          "RecordActivityData": true,
          "Variables": [
            { "Name": "quantity", "TypeName": "number", "DefaultValue": 1 },
            { "Name": "message", "TypeName": "string" }
          ],
          "Activities": [
            {
              "ActivityId": "received",
              "Name": "HttpRequestEvent",
              "X": 40,
              "Y": 40,
              "IsStart": true,
              "Properties": {
                "ActivityMetadata": { "Title": "Order received" },
                "HttpMethod": "GET",
                "ValidateAntiforgeryToken": false
              }
            },
            {
              "ActivityId": "compose",
              "Name": "SetVariableTask",
              "X": 380,
              "Y": 40,
              "IsStart": false,
              "Properties": {
                "VariableName": "message",
                "Value": {
                  "Expression": "{{ Workflow.Variables.quantity }} item(s) ordered.",
                  "Syntax": "Liquid"
                }
              }
            },
            {
              "ActivityId": "reply",
              "Name": "HttpResponseTask",
              "X": 720,
              "Y": 40,
              "IsStart": false,
              "Properties": {
                "Content": { "Expression": "{{ Workflow.Variables.message }}" },
                "HttpStatusCode": 200,
                "ContentType": { "Expression": "text/plain" }
              }
            }
          ],
          "Transitions": [
            { "SourceActivityId": "received", "SourceOutcomeName": "Done", "DestinationActivityId": "compose" },
            { "SourceActivityId": "compose", "SourceOutcomeName": "Done", "DestinationActivityId": "reply" }
          ]
        }
      ]
    }
  ]
}

The Workflow Variables Samples recipe (workflows-variables-samples) in the Workflows module is a complete reference for variables, output bindings and Execute Workflow. More payloads are in workflow-examples.md.

Built-in activities

Activity class names (stored in ActivityRecord.Name), not UI labels:

| Feature area | Events | Tasks |

|---|---|---|

| Workflows | WorkflowFaultEvent (Catch Workflow Fault Event), StartedByWorkflowEvent | NotifyTask, SetPropertyTask, SetVariableTask, SetOutputTask, CorrelateTask, ExecuteWorkflowTask, ForkTask, JoinTask, ForLoopTask, ForEachTask, WhileLoopTask, IfElseTask, ScriptTask, LiquidTask, LogTask |

| Workflows Session | — | CommitTransactionTask |

| HTTP | HttpRequestEvent, HttpRequestFilterEvent, SignalEvent | HttpRedirectTask, HttpRequestTask, HttpResponseTask |

| Timers | TimerEvent (CronExpression, UseLocalTime) | — |

| User tasks | UserTaskEvent | — |

| Contents | ContentCreatedEvent, ContentDeletedEvent, ContentPublishedEvent, ContentUnpublishedEvent, ContentUpdatedEvent, ContentDraftSavedEvent, ContentVersionedEvent | CreateContentTask, RetrieveContentTask, UpdateContentTask, DeleteContentTask, PublishContentTask, UnpublishContentTask |

| Users | UserCreatedEvent, UserDeletedEvent, UserEnabledEvent, UserDisabledEvent, UserUpdatedEvent, UserLoggedInEvent, UserLoggedOutEvent, UserConfirmedEvent | AssignUserRoleTask, ValidateUserTask, RegisterUserTask |

| Data Pipelines | DataPipelineRunCompletedEvent | RunDataPipelineTask |

| Other modules | — | EmailTask, SmsTask, NotifyUserTask, NotifyContentOwnerTask, UpdateTwitterStatusTask, ValidateReCaptchaTask, MetaConversionsApiEventTask, ValidateAntiforgeryTokenTask, AddModelValidationErrorTask, ValidateFormTask, ValidateFormFieldTask, BindModelStateTask, HttpRedirectToFormLocationTask, UnassignUserRoleTask, GetUsersByRoleTask, DisableTenantTask, EnableTenantTask, CreateTenantTask, SetupTenantTask |

Expressions and syntaxes

Each expression of Correlate, For Each, For Loop, If/Else, Set Output, Set Property, Set Variable and While Loop has its own syntax, chosen next to the expression. Other activities keep a fixed syntax (for example LogTask.Text and HttpRequestTask.Url are Liquid, ScriptTask.Script is JavaScript).

| Syntax | WorkflowExpressionSyntaxes | Value |

|---|---|---|

| Literal | Literal | The text itself converted to the expected type (true, invariant numbers, JSON objects, JSON arrays or comma-separated lists). |

| Liquid | Liquid | A Liquid template ({{ Workflow.Properties.Count > 0 }}). |

| JavaScript | JavaScript | A JavaScript expression (input("Count") > 0). |

An expression is stored with its syntax:

"Condition": {
  "Expression": "{{ Workflow.Properties.Count > 0 }}",
  "Syntax": "Liquid"
}

Activities stored the 3.x way (one Syntax setting plus a JavaScript and a Liquid... property per expression, such as ConditionExpression/LiquidCondition) run as before and move to the new shape when saved in the designer. WorkflowExpression<T>.Syntax is null for them, and the activity picks the syntax (WorkflowExpressionSyntaxes.Resolve(...) does this for the built-ins).

JavaScript and Liquid

var item = input("ContentItem");
setVariable("total", variable("quantity") * variable("unitPrice"));
setProperty("Count", (property("Count") || 0) + 1);
output("Result", item);
setCorrelationId(item.ContentItemId);
{{ Workflow.Input.ContentItem.DisplayText }}
{{ Workflow.Input.ContentEvent.ContentType }}
{{ Workflow.Variables.total }}
{{ Workflow.Properties.Count }}
{{ Workflow.LastResult }}
{{ Workflow.CorrelationId }}
{{ 'Approved' | signal_url }}

Variables

Declare typed variables in the designer's Variables tab (versioned with the workflow). Each instance has its own values.

| Type name | Values |

|---|---|

| string | Text; numbers, dates, booleans and JSON convert to text. |

| number | double, from numbers and invariant text. |

| boolean | true/false. |

| datetime | UTC date and time, ISO 8601 text without offset is UTC. |

| object | Dictionary from objects or JSON object text. |

| array | List from lists or JSON array text. |

| any | Any value, unconverted. |

| contentItem | Content item (Contents feature); stored as the id and reloaded on resume. |

Available data and last result

The activity panel's Available data tab lists what the selected activity's expressions can read, with a JavaScript and a Liquid expression for each (click to insert): Variables, This activity (values set before its own expressions run), From an activity (inputs, properties and outputs of activities on a path to it), Workflow (last result, correlation id), Inputs, Global Liquid values (Site, User, Request, Culture, Environment, Content) and Functions. Script editors offer the same completions.

lastResult() / {{ Workflow.LastResult }} is what the previous activity returned: the content item after Retrieve Content, the response (Body, Headers, StatusCode, ReasonPhrase, IsSuccessStatusCode) after HTTP Request, the send result after Email/SMS, the outputs (or fault message) after Execute Workflow, the current item or index in loops. Content events provide ContentItem and ContentEvent (Name, ContentType, ContentItemId, ContentItemVersionId, IsStart); Catch Workflow Fault Event provides WorkflowFault.

Branching

Workflows as activities

  1. In the child workflow's settings, check Usable as an activity (IsActivity).
  2. Mark its variables Input (IsInput) and Output (IsOutput).
  3. Start it with Started By Workflow (StartedByWorkflowEvent); otherwise its first start activity is used.

Child workflows appear in the activities pane's Workflows category as presets of Execute Workflow (ExecuteWorkflowTask: WorkflowTypeId, Inputs as a dictionary of expressions, WaitForCompletion, Outputs). With WaitForCompletion, the task follows Done when the child finishes (even if it waits on events), stores the child outputs, and follows Failed when the child faults; without it, Done follows as soon as the child starts. The child runs on its published version with ParentWorkflowId/ParentActivityId; nesting is limited to 16 levels. Re-edit the task after changing the child's outputs.

Code can start a child with IWorkflowManager.StartChildWorkflowAsync(workflowType, parentContext, parentActivityId, input); the parent activity resumes with a ChildWorkflowResult input (ChildWorkflowResult.InputKey). Report a started child to the journal with workflowContext.ReportChildWorkflow(workflowId). Modules add activities-pane entries with preset properties through IActivityPresetProvider (see custom-activity-examples.md).

Execution journal and retries

{
  "OrchardCore": {
    "Workflows": {
      "Journal": {
        "Enabled": true,
        "MaxRecordsPerInstance": 1000
      }
    }
  }
}

Script errors and execution limits

Real-time updates

With OrchardCore.SignalR enabled, the designer shows who else has the workflow open and offers Reload when someone changes, publishes or discards the draft, and instance pages follow running instances. Pages connect to the tenant's /hubs/workflows hub, which requires Manage workflows; it works with the Redis and Azure SignalR backplanes. IWorkflowDesignerNotifier (WorkflowTypeChangedAsync, InstanceChangedAsync) receives the changes; without SignalR a no-op implementation is used.

Correlation, blocking and resuming

CorrelateTask sets WorkflowExecutionContext.CorrelationId; use a stable id (content item id, order id) so a later event resumes the right instance. An EventActivity halts by default; the manager persists the instance, and TriggerEventAsync resumes matching halted instances (and starts workflows whose start activity matches) after the event's CanExecuteAsync.

await workflowManager.TriggerEventAsync(
    nameof(OrderApprovedEvent),
    new Dictionary<string, object>
    {
        ["OrderId"] = orderId,
    },
    correlationId: orderId);

isExclusive avoids starting a duplicate instance already halted on the start event; isAlwaysCorrelated resumes by event type regardless of correlation. Prefer normal correlation or One per correlated item. Resuming an instance whose blocking activity is missing from its version faults it.

Custom activities

| Need | Base class |

|---|---|

| Do work and return an outcome | TaskActivity<TActivity> (Name is the type name) |

| Start or wait for something external | EventActivity (override Name; Execute halts by default) |

Lifecycle: GetPossibleOutcomes/GetPossibleOutcomesAsync declares ports; CanExecuteAsync gates; ExecuteAsync returns Outcome("..."), Halt() or Noop(); after a halt, ResumeAsync/Resume returns the outcome. Hooks: OnInputReceivedAsync, OnWorkflowStartingAsync/StartedAsync, OnWorkflowRestartingAsync/RestartedAsync, OnWorkflowResumingAsync/ResumedAsync, OnActivityExecutingAsync/ExecutedAsync.

Rules for 4.0 activities:

using Microsoft.Extensions.Localization;
using OrchardCore.Localization;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.Services;

namespace MyModule.Workflows.Activities;

public sealed class ApproveOrderTask : TaskActivity<ApproveOrderTask>, IActivityDescription
{
    private readonly IWorkflowExpressionManager _expressionManager;
    private readonly IStringLocalizerFactory _localizerFactory;
    private readonly IStringLocalizer S;

    public ApproveOrderTask(
        IWorkflowExpressionManager expressionManager,
        IStringLocalizerFactory localizerFactory,
        IStringLocalizer<ApproveOrderTask> localizer)
    {
        _expressionManager = expressionManager;
        _localizerFactory = localizerFactory;
        S = localizer;
    }

    public static LocalizationSource DisplayName { get; } = LocalizationSource.Create<ApproveOrderTask>("Approve Order Task");

    public static LocalizationSource CategoryName { get; } = LocalizationSource.Create<ApproveOrderTask>("Orders");

    public override LocalizedString DisplayText => _localizerFactory.Localize(DisplayName);

    public override LocalizedString Category => _localizerFactory.Localize(CategoryName);

    public WorkflowExpression<bool> Condition
    {
        get => GetProperty(() => new WorkflowExpression<bool>());
        set => SetProperty(value);
    }

    public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
        => Outcome(S["Approved"], S["Rejected"]);

    public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
    {
        var approved = await _expressionManager.EvaluateAsync(Condition, workflowContext, WorkflowExpressionSyntaxes.JavaScript);

        return Outcome(approved ? "Approved" : "Rejected");
    }
}

Register the activity with its driver; the optional callback sets the designer icon (otherwise the category icon from WorkflowOptions.CategoryIcons, keyed by the untranslated category Value, is used):

services.AddActivity<ApproveOrderTask, ApproveOrderTaskDisplayDriver>(activity => activity.Icon = "fa-solid fa-check");
services.Configure<WorkflowOptions>(options => options.CategoryIcons[ApproveOrderTask.CategoryName.Value] = "fa-solid fa-cart-shopping");

ActivityDisplayDriver<TActivity> renders {Activity}_Fields_Thumbnail (activities pane card) and {Activity}_Fields_Design (canvas body); ActivityDisplayDriver<TActivity, TViewModel> adds {Activity}_Fields_Edit. Put the views in Views/Items/. The designer draws the card, icon and outcome ports itself. Register activities that depend on another feature in a [RequireFeatures("...")] startup. Trigger custom events through IWorkflowManager.TriggerEventAsync; AddActivity does not.

The full task (outputs, provided values, driver, views), a custom event, and the extension points (custom syntax, variable type, presets, global values) are in custom-activity-examples.md.

Activity editors in the designer

The designer injects {Activity}_Fields_Edit into its activity panel without a page reload and posts it as a form when a field changes. Plain form fields need nothing more. Editors with scripts must:

Permissions

OrchardCore.Workflows.WorkflowsPermissions (in OrchardCore.Workflows.Abstractions):

| Permission | Default roles | Gates |

|---|---|---|

| ManageWorkflows | Administrator | Workflows list, designer, instances, the /hubs/workflows hub. Security critical. |

| ExecuteWorkflows | Administrator, Editor | Run…, Retry from here and bulk retry. Security critical. |

| ManageWorkflowSettings | Administrator | Workflow settings (trimming); implied by ManageWorkflows. |

if (!await _authorizationService.AuthorizeAsync(User, WorkflowsPermissions.ManageWorkflows))
{
    return Forbid();
}

Trimming

Trimming deletes old instances (and their journal). Configure it in Settings → Workflow Trimming or with the settings step; it runs daily and removes at most 5000 instances per run.

{
  "steps": [
    {
      "name": "settings",
      "WorkflowTrimmingSettings": {
        "RetentionDays": 90,
        "Disabled": false,
        "Statuses": [
          "Finished",
          "Faulted",
          "Aborted"
        ]
      }
    }
  ]
}

Change the batch size with OrchardCore:Workflows:Trimming:BatchSize in appsettings.json.

Upgrading from 3.x

Upgrading from earlier 4.0 previews

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.