### Setting Up Simple Tasks in Conductor Sharp Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-task-examples Simple tasks configure basic operations like preparing email data by mapping workflow inputs to task inputs using string interpolation. Outputs are set via SetOutput for workflow propagation. This foundational setup depends on input classes and builder patterns, with no complex logic but supports naming utilities for dynamic values. ```csharp public EmailPrepareV1 EmailPrepare { get; set; } public override void BuildDefinition() { _builder.AddTask( wf => wf.EmailPrepare, wf => new() { Address = $"{wf.WorkflowInput.FirstInput},{wf.WorkflowInput.SecondInput}", Name = $"Workflow name: {NamingUtil.NameOf()}" } ); _builder.SetOutput(a => new() { EmailBody = a.EmailPrepare.Output.EmailBody }); } ``` -------------------------------- ### Start Workflow Instance with ConductorSharp Source: https://context7.com/codaxy/conductor-sharp/llms.txt Starts a new workflow instance using IWorkflowService with input parameters. Requires workflow name, version, and input data. Returns the generated workflow ID or error message if failed. Depends on ConductorSharp client library and proper workflow definition in Conductor server. ```csharp using ConductorSharp.Client; using ConductorSharp.Client.Generated; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Threading.Tasks; [ApiController] [Route("api/[controller]")] public class WorkflowController : ControllerBase { private readonly IWorkflowService _workflowService; private readonly ILogger _logger; public WorkflowController( IWorkflowService workflowService, ILogger logger ) { _workflowService = workflowService; _logger = logger; } [HttpPost("start")] public async Task StartWorkflow([FromBody] StartWorkflowDto request) { try { var workflowId = await _workflowService.StartAsync(new StartWorkflowRequest { Name = "ORDER_processing", Version = 1, Input = new Dictionary { { "orderId", request.OrderId }, { "customerEmail", request.CustomerEmail } }, CorrelationId = $"order-{request.OrderId}" }); _logger.LogInformation("Started workflow {WorkflowId} for order {OrderId}", workflowId, request.OrderId); return Ok(new { workflowId }); } catch (Exception ex) { _logger.LogError(ex, "Failed to start workflow"); return StatusCode(500, new { error = ex.Message }); } } } public class StartWorkflowDto { public int OrderId { get; set; } public string CustomerEmail { get; set; } } ``` -------------------------------- ### Create ProvisionService sub-workflow task in C# Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-task-examples Defines input/output models and implements a sub-workflow task for service provisioning. Takes dynamic context and service specification as inputs. ```csharp public class ProvisionServiceInput : IRequest { public dynamic Context { get;set; } public dynamic ServiceSpecification { get;set; } } public class ProvisionServiceOutput { } public class ProvisionService : SubWorkflowTaskModel { } public ProvisionService ProvisionService { get;set; } _builder.AddTask( a => a.ProvisionService, b => new() { Context = b.WorkflowInput.Context, ServiceSpecification = b.WorkflowInput.Specification } ); ``` -------------------------------- ### SimpleTaskModel Definition (C#) Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Shows an example of defining a SimpleTaskModel, including input and output classes, and the use of the [JsonProperty] attribute. ```csharp public partial class EmailPrepareV1Input : IRequest { public object Address { get; set; } public object Name { get; set; } } public partial class EmailPrepareV1Output { [JsonProperty("example_body") public object EmailBody { get; set; } } [OriginalName("EMAIL_prepare") public partial class EmailPrepareV1 : SimpleTaskModel { } ``` -------------------------------- ### Add raw LAMBDA task with JSON parameters in C# Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-task-examples Demonstrates creating a custom raw task with detailed JSON configuration. Maps multiple input parameters and includes JavaScript return expression. ```csharp _builder.AddTasks( new WorkflowDefinition.Task { Name = "LAMBDA_return_data", TaskReferenceName = "return_data", Type = "LAMBDA", Description = new JObject { new JProperty("description", "Lambda task to return data") }.ToString(Newtonsoft.Json.Formatting.None), InputParameters = new JObject { new JProperty("hostname", "${workflow.input.hostname}"), new JProperty("additional_template", "${workflow.input.additional_template}"), new JProperty("base_template", "${workflow.input.base_template}"), new JProperty("licence", "${workflow.input.licence}"), new JProperty("oam_domain", "${workflow.input.oam_domain}"), new JProperty("platform_codename", "${workflow.input.platform_codename}"), new JProperty("platform_name", "${workflow.input.platform_name}"), new JProperty("software_version", "${workflow.input.software_version}"), new JProperty("upstream_switch", "${workflow.input.upstream_switch}"), new JProperty( "upstream_switch_interface_name", "${workflow.input.upstream_switch_interface_name}" ), new JProperty( "scriptExpression", "return { " + "hostname : $.hostname," + "additional_template : $.additional_template," + "base_template : $.base_template," + "licence : $.licence," + "oam_domain : $.oam_domain," + "platform_codename : $.platform_codename," + "platform_name : $.platform_name," + "software_version : $.software_version," + "upstream_switch : $.upstream_switch," + "upstream_switch_interface_name : $.upstream_switch_interface_name," + "}" ) } } ); ``` -------------------------------- ### Implementing Dynamic Fork-Join Tasks in Conductor Sharp Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-task-examples Dynamic Fork-Join tasks handle runtime-determined parallel execution of tasks or sub-workflows using FORK_JOIN_DYNAMIC and JOIN via a single builder method. Inputs include lists of DynamicTasks and DynamicTasksI from prior task outputs. This simplifies wiring runtime lists for forking, collecting outputs post-join, but requires a preceding task to provide the dynamic lists. ```csharp public DynamicForkJoinTaskModel DynamicForkJoin { get; set; } _builder.AddTask( a => a.DynamicForkJoin, b => new() { DynamicTasks = b.PrepareDynamicProvisionTasks.Output.DynamicTasks, DynamicTasksI = b.PrepareDynamicProvisionTasks.Output.DynamicTasksI } ); ``` -------------------------------- ### POST /api/workflow/start Source: https://context7.com/codaxy/conductor-sharp/llms.txt Starts a new workflow instance of the ORDER_processing definition. Returns the unique workflow identifier. ```APIDOC ## POST /api/workflow/start ### Description Starts a new workflow instance of the ORDER_processing definition. ### Method POST ### Endpoint /api/workflow/start ### Parameters #### Request Body - **orderId** (integer) - Required - Identifier of the order. - **customerEmail** (string) - Required - Email of the customer. ### Request Example { "orderId": 123, "customerEmail": "customer@example.com" } ### Response #### Success Response (200) - **workflowId** (string) - Identifier of the started workflow. ### Response Example { "workflowId": "abcd-1234" } ``` -------------------------------- ### Configure ConductorSharp Service Registration in C# Source: https://context7.com/codaxy/conductor-sharp/llms.txt Demonstrates how to configure ConductorSharp in a .NET application's dependency injection container. Includes client connection setup, execution manager configuration, pipeline behaviors, and workflow/task registrations. Supports multi-cluster deployments and health checks. ```csharp using ConductorSharp.Client; using ConductorSharp.Engine; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var builder = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services // Add Conductor client connection .AddConductorSharp( baseUrl: "http://conductor-server:8080", apiPath: "api" ) // Add alternate client for multi-cluster support .AddAlternateClient( baseUrl: "http://backup-conductor:8080", key: "BackupCluster", apiPath: "api" ) // Add execution manager for task workers .AddExecutionManager( maxConcurrentWorkers: 10, sleepInterval: 500, longPollInterval: 100, domain: null, typeof(Program).Assembly ) // Set health check service .SetHealthCheckService() // Add MediatR pipeline behaviors .AddPipelines(pipelines => { pipelines.AddContextLogging(); pipelines.AddRequestResponseLogging(); pipelines.AddValidation(); pipelines.AddExecutionTaskTracking(); }) // Set build configuration .SetBuildConfiguration(new BuildConfiguration { DefaultOwnerApp = "MyApplication", DefaultOwnerEmail = "team@company.com" }); // Register worker tasks with options services.RegisterWorkerTask(options => { options.OwnerEmail = "team@company.com"; options.TimeoutSeconds = 120; options.RetryCount = 3; options.RetryLogic = TaskDefRetryLogic.FIXED; options.RetryDelaySeconds = 60; options.ResponseTimeoutSeconds = 60; options.TimeoutPolicy = TaskDefTimeoutPolicy.TIME_OUT_WF; options.ConcurrentExecLimit = 5; }); // Register workflows services.RegisterWorkflow(); }); await builder.Build().RunAsync(); ``` -------------------------------- ### SubWorkflowTaskModel Definition (C#) Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Provides an example of defining a SubWorkflowTaskModel, including input and output classes, and the use of the [OriginalName] and [Version] attributes. ```csharp public class VersionSubworkflowInput : IRequest { } public class VersionSubworkflowOutput { } [OriginalName("TEST_subworkflow") [Version(3)] public class VersionSubworkflow : SubWorkflowTaskModel { } ``` -------------------------------- ### Implement decision-based workflow termination in C# Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-task-examples Shows a conditional termination pattern with decision task and terminate task. Outputs workflow properties and sets termination status. ```csharp public DecisionTaskModel DecisionTask { get; set; } public TerminateTaskModel DecisionTerminate { get; set; } _builder.AddTask( wf => wf.DecisionTask, wf => new() { CaseValueParam = "value" }, new() { ["value"] = builder => builder.AddTask( wf => wf.DecisionTerminate, wf => new() { WorkflowOutput = new { Property = "Test" }, TerminationStatus = TerminationStatus.Completed } ) } ); ``` -------------------------------- ### Initialize arrays for task inputs (C# and JSON) Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Provides examples of initializing typed and dynamic arrays within a workflow input object. The C# snippet creates arrays of primitives, custom models, and anonymous objects, and the JSON output shows the corresponding Conductor array structures. ```csharp wf => new() { Integers = new[] { 1, 2, 3 }, TestModelList = new List { new ArrayTaskInput.TestModel { String = wf.Input.TestValue }, new ArrayTaskInput.TestModel { String = "List2" } }, Models = new[] { new ArrayTaskInput.TestModel { String = "Test1" }, new ArrayTaskInput.TestModel { String = "Test2" } }, Objects = new dynamic[] { new { AnonymousObjProp = "Prop" }, new { Test = "Prop" } } } ``` ```json "inputParameters": { "integers": [ 1, 2, 3 ], "test_model_list": [ { "string": "${workflow.input.test_value}" }, { "string": "List2" } ], "models": [ { "string": "Test1" }, { "string": "Test2" } ], "objects": [ { "anonymous_obj_prop": "Prop" }, { "test": "Prop" } ] } ``` -------------------------------- ### GET /api/task/queues Source: https://context7.com/codaxy/conductor-sharp/llms.txt Lists all task queues. Optional verbose flag provides detailed queue metrics. ```APIDOC ## GET /api/task/queues\n\n### Description\nReturns a list of all task queues. If the `verbose` query parameter is true, detailed metrics are included.\n\n### Method\nGET\n\n### Endpoint\n/api/task/queues\n\n### Parameters\n#### Query Parameters\n- **verbose** (boolean) - Optional - When true, includes detailed queue information. Default is false.\n\n### Request Example\nN/A\n\n### Response\n#### Success Response (200)\n- **queues** (array) - List of queue objects. Each object contains at minimum `taskType` and `queueSize`. Verbose responses include additional metrics such as `inProgressCount`.\n\n#### Response Example (non‑verbose)\n[\n {\n \"taskType\": \"typeA\",\n \"queueSize\": 10\n },\n {\n \"taskType\": \"typeB\",\n \"queueSize\": 5\n }\n]\n\n#### Response Example (verbose)\n[\n {\n \"taskType\": \"typeA\",\n \"queueSize\": 10,\n \"inProgressCount\": 2,\n \"completedCount\": 50\n }\n] ``` -------------------------------- ### GET /api/metadata/workflows/{name} Source: https://context7.com/codaxy/conductor-sharp/llms.txt Retrieve a specific workflow definition by name. Optionally specify a version to get a particular version of the workflow. ```APIDOC ## GET /api/metadata/workflows/{name} ### Description Get a workflow definition by name ### Method GET ### Endpoint /api/metadata/workflows/{name} ### Parameters #### Path Parameters - **name** (string) - Required - Name of the workflow #### Query Parameters - **version** (int) - Optional - Specific version of the workflow ### Response #### Success Response (200) - Returns the complete workflow definition object #### Response Example { "name": "sample_workflow", "version": 1, "tasks": [] } ``` -------------------------------- ### Add Task to Workflow (C#) Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Demonstrates adding a task to a workflow using the AddTask extension method. This example shows how to specify input properties for the task. ```csharp _builder.AddTask( wf => wf.EmailPrepare, wf => new() { Address = "${wf.WorkflowInput.FirstInput},${wf.WorkflowInput.SecondInput}", } ); ``` -------------------------------- ### GET /api/metadata/tasks Source: https://context7.com/codaxy/conductor-sharp/llms.txt Retrieve all task definitions registered with the Conductor server. ```APIDOC ## GET /api/metadata/tasks ### Description List all task definitions ### Method GET ### Endpoint /api/metadata/tasks ### Response #### Success Response (200) - Returns list of all task definitions #### Response Example [ { "name": "task1", "retryCount": 3 }, { "name": "task2", "retryCount": 5 } ] ``` -------------------------------- ### Defining Decision Tasks with Switch Cases in Conductor Sharp Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-task-examples Decision tasks use indexer syntax for cases and DefaultCase property to branch workflows based on input like task status. Each case adds subtasks conditionally; default handles unmatched cases. Outputs propagate through branches, supporting termination or further tasks, but case values must match exactly for correct routing. ```csharp public DecisionTaskModel ShouldRevertClassUpdateDecision { get;set; } public TerminateTaskModel TerminateWorkflow { get;set; } _builder.AddTask( a => a.ShouldRevertClassUpdateDecision, b => new() { CaseValueParam = "${original_workflow_tasks.output.tasks.update_class.status}" }, new() { ["COMPLETED"] = c => { c.AddTask( d => d.RevertRegistryChange, e => new() { Class = "${original_workflow_tasks.output.tasks.get_info.outputData.class}", ServiceId = "${original_workflow_tasks.output.tasks.get_info.outputData.id}", } ); c.AddTask(d => d.Wait, e => new() { Minutes = 1 }); }, DefaultCase = c => { c.AddTask( d => d.TerminateWorkflow, e => new() { TerminationStatus = TerminationStatus.Completed, WorkflowOutput = new { Message = "Class update was not reverted" } } ); } } ); ``` -------------------------------- ### GET /api/metadata/workflows Source: https://context7.com/codaxy/conductor-sharp/llms.txt Retrieve all workflow definitions registered with the Conductor server. ```APIDOC ## GET /api/metadata/workflows ### Description List all workflow definitions ### Method GET ### Endpoint /api/metadata/workflows ### Response #### Success Response (200) - Returns list of all workflow definitions #### Response Example [ { "name": "workflow1", "version": 1, "tasks": [] }, { "name": "workflow2", "version": 1, "tasks": [] } ] ``` -------------------------------- ### Register Worker Tasks and Workflows in C# Source: https://github.com/codaxy/conductor-sharp/wiki/Registration This example shows C# code for registering worker task handlers and workflow definitions in the DI container, typically in the service configuration phase. It uses IServiceCollection extension methods and supports configuration of task properties like retry policies. Inputs include workflow and handler classes; outputs are registered tasks and workflows sent to Conductor on startup. ```csharp services.RegisterWorkerTask(); services.RegisterWorkflow(); ``` -------------------------------- ### GET /api/task/{taskId}/logs Source: https://context7.com/codaxy/conductor-sharp/llms.txt Retrieves execution logs for the specified task. ```APIDOC ## GET /api/task/{taskId}/logs\n\n### Description\nFetches the list of log entries associated with a given task.\n\n### Method\nGET\n\n### Endpoint\n/api/task/{taskId}/logs\n\n### Parameters\n#### Path Parameters\n- **taskId** (string) - Required - Identifier of the task whose logs are requested.\n\n### Request Example\nN/A\n\n### Response\n#### Success Response (200)\n- **logs** (array) - Collection of log messages.\n\n#### Response Example\n[\n \"Task started\",\n \"Processing step 1 completed\",\n \"Task finished successfully\"n] ``` -------------------------------- ### Configuring Lambda Tasks in Conductor Sharp Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-task-examples Lambda tasks execute inline JavaScript code as the final parameter in AddTask, producing outputs accessible via task reference like some_task.output.result. Inputs from classes like ValidateMacInput are referenced in JS as $.property. This approach has been updated to INLINE tasks in newer Conductor versions; ensure the JS returns a valid object for workflow propagation. ```csharp public LambdaTaskModel MacValidateTask { get; set; } public override void BuildDefinition() { _builder.AddTask( wf => wf.MacValidateTask , wf => new() { MacAddress = wf.WorkflowInput.MacAddress. }, "return { transformed_mac : $.mac_address.toLowerCase().replaceAll(':','')}" ); } ``` -------------------------------- ### Register Custom Pipeline Behavior in ConductorSharp Source: https://context7.com/codaxy/conductor-sharp/llms.txt Registers the custom pipeline behavior with the ConductorSharp execution manager. The AddCustomBehavior method registers the PerformanceMonitoringBehavior to handle all IRequest requests. Requires an existing ConductorSharp configuration with baseUrl and execution manager setup. ```csharp // Register custom behavior services.AddConductorSharp(baseUrl: "http://conductor:8080") .AddExecutionManager(...) .AddPipelines(pipelines => { pipelines.AddContextLogging(); pipelines.AddValidation(); pipelines.AddCustomBehavior, object>(); }); ``` -------------------------------- ### Get Workflow Execution Status Source: https://context7.com/codaxy/conductor-sharp/llms.txt Retrieves detailed execution status of a workflow including tasks information. Accepts workflow ID as parameter and returns workflow status, timing information, output data, and nested task details. Requires workflow to exist in Conductor server. ```csharp [HttpGet("{workflowId}/status")] public async Task GetStatus(string workflowId) { var workflow = await _workflowService.GetExecutionStatusAsync( workflowId, includeTasks: true ); return Ok(new { workflowId = workflow.WorkflowId, status = workflow.Status.ToString(), startTime = workflow.StartTime, endTime = workflow.EndTime, output = workflow.Output, tasks = workflow.Tasks?.Select(t => new { taskType = t.TaskType, status = t.Status.ToString(), startTime = t.StartTime, endTime = t.EndTime }) }); } ``` -------------------------------- ### GET /api/metadata/tasks/{taskType} Source: https://context7.com/codaxy/conductor-sharp/llms.txt Retrieve a specific task definition by its type. ```APIDOC ## GET /api/metadata/tasks/{taskType} ### Description Get a task definition by type ### Method GET ### Endpoint /api/metadata/tasks/{taskType} ### Parameters #### Path Parameters - **taskType** (string) - Required - Type of the task ### Response #### Success Response (200) - Returns the complete task definition object #### Response Example { "name": "sample_task", "retryCount": 3 } ``` -------------------------------- ### Specify task input parameters with Conductor expressions (C# and JSON) Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Shows how to build a C# object for task inputs using Conductor expressions, which are then translated into the JSON inputParameters format required by Conductor. Demonstrates string interpolation and property mapping. ```csharp wf => new PrepareEmailRequest { CustomerName = $"{wf.GetCustomer.Output.FirstName} {wf.GetCustomer.Output.LastName}", Address = wf.WorkflowInput.Address } ``` ```json "inputParameters": { "customer_name": "${get_customer.output.first_name} ${get_customer.output.last_name}", "address": "${workflow.input.address}" } ``` -------------------------------- ### C# Dictionary Indexing to JSON Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Demonstrates how C# dictionary indexing is translated to JSON input parameters. This snippet uses both single and double dictionaries for value retrieval, showing the basic mapping process. Currently, indexing arbitrary types is not supported. ```csharp wf => new() { CustomerName = wf.WorkflowInput.Dictionary["test"].CustomerName, Address = wf.WorkflowInput.DoubleDictionary["test"]["address"] } ``` ```json "inputParameters": { "customer_name": "${workflow.input.dictionary['test'].customer_name}", "address": "${workflow.input.double_dictionary['test']['address']}" } ``` -------------------------------- ### GET /api/task/{taskId} Source: https://context7.com/codaxy/conductor-sharp/llms.txt Retrieves detailed information for a specific task identified by its taskId. ```APIDOC ## GET /api/task/{taskId}\n\n### Description\nFetches the details of a task using its unique identifier.\n\n### Method\nGET\n\n### Endpoint\n/api/task/{taskId}\n\n### Parameters\n#### Path Parameters\n- **taskId** (string) - Required - The unique identifier of the task to retrieve.\n\n### Request Example\nN/A\n\n### Response\n#### Success Response (200)\n- **taskId** (string)\n- **taskType** (string)\n- **status** (string)\n- **inputData** (object)\n- **outputData** (object)\n\n#### Response Example\n{\n \"taskId\": \"exampleTaskId\",\n \"taskType\": \"exampleType\",\n \"status\": \"COMPLETED\",\n \"inputData\": {\n \"param\": \"value\"\n },\n \"outputData\": {\n \"result\": \"ok\"\n }\n} ``` -------------------------------- ### Build Conductor Workflow in C# Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Inherits from Workflow abstract class, overrides BuildDefinition to use WorkflowDefinitionBuilder for adding tasks. Requires conductor-sharp NuGet package. Inputs include CustomerId; outputs like EmailBody. Best for new workflows; provides compile-time checks; tasks must use supported builders. ```csharp public class SendCustomerNotificationInput : WorkflowInput { public int CustomerId { get; set; } } public class SendCustomerNotificationOutput : WorkflowOutput { public dynamic EmailBody { get; set; } } [Version(3)] [OriginalName("NOTIFICATION_send_to_customer")] public class SendCustomerNotification : Workflow { public SendCustomerNotification( WorkflowDefinitionBuilder builder ) : base(builder) { } public GetCustomerHandler GetCustomer { get; set; } public EmailPrepareV1 PrepareEmail { get; set; } public override void BuildDefinition() { _builder.AddTask(a => a.GetCustomer, b => new() { CustomerId = b.WorkflowInput.CustomerId }); _builder.AddTask(a => a.PrepareEmail, b => new() { Address = b.GetCustomer.Output.Address, Name = b.GetCustomer.Output.Name }); } } ``` -------------------------------- ### GET /api/task/queue/{taskType} Source: https://context7.com/codaxy/conductor-sharp/llms.txt Returns the current queue size for a specific task type. ```APIDOC ## GET /api/task/queue/{taskType}\n\n### Description\nRetrieves queue information, including size, for the specified task type.\n\n### Method\nGET\n\n### Endpoint\n/api/task/queue/{taskType}\n\n### Parameters\n#### Path Parameters\n- **taskType** (string) - Required - The type of task whose queue information is requested.\n\n### Request Example\nN/A\n\n### Response\n#### Success Response (200)\n- **taskType** (string)\n- **queueSize** (integer)\n\n#### Response Example\n{\n \"taskType\": \"exampleType\",\n \"queueSize\": 42\n} ``` -------------------------------- ### Search Workflows by Query Source: https://context7.com/codaxy/conductor-sharp/llms.txt Searches for workflows using query parameters with pagination support. Accepts search query string and returns matching workflow instances. Supports free text search and structured query syntax. Limited to 50 results per request in this implementation. ```csharp [HttpPost("search")] public async Task SearchWorkflows([FromQuery] string query) { var results = await _workflowService.SearchV2Async( start: 0, size: 50, query: query, freeText: "" ); return Ok(results); } ``` -------------------------------- ### GET /api/workflow/{workflowId}/status Source: https://context7.com/codaxy/conductor-sharp/llms.txt Retrieves the execution status and task details of a specific workflow instance. ```APIDOC ## GET /api/workflow/{workflowId}/status ### Description Retrieves the execution status and task details of a specific workflow instance. ### Method GET ### Endpoint /api/workflow/{workflowId}/status ### Parameters #### Path Parameters - **workflowId** (string) - Required - Identifier of the workflow to query. ### Response #### Success Response (200) - **workflowId** (string) - Workflow identifier. - **status** (string) - Current status of the workflow. - **startTime** (string) - ISO timestamp when the workflow started. - **endTime** (string) - ISO timestamp when the workflow ended (if completed). - **output** (object) - Output payload of the workflow. - **tasks** (array) - List of task summaries. ### Response Example { "workflowId": "abcd-1234", "status": "COMPLETED", "startTime": "2024-10-01T12:00:00Z", "endTime": "2024-10-01T12:05:00Z", "output": { "result": "success" }, "tasks": [ { "taskType": "TASK_A", "status": "COMPLETED", "startTime": "2024-10-01T12:00:10Z", "endTime": "2024-10-01T12:00:30Z" } ] } ``` -------------------------------- ### Dynamic Fork-Join Parallel Execution Source: https://context7.com/codaxy/conductor-sharp/llms.txt Complete implementation showing workflow definition using DynamicForkJoinTaskModel for parallel execution and a handler for preparing dynamic tasks at runtime. Handles batch processing with dynamic task creation and result aggregation. ```csharp public class BatchProcessingInput : WorkflowInput { public List OrderIds { get; set; } } public class BatchProcessingWorkflow : Workflow { public PrepareDynamicTasksHandler PrepareTasks { get; set; } public DynamicForkJoinTaskModel DynamicFork { get; set; } public AggregatResultsHandler AggregateResults { get; set; } public BatchProcessingWorkflow( WorkflowDefinitionBuilder builder ) : base(builder) { } public override void BuildDefinition() { // Prepare dynamic task definitions _builder.AddTask( wf => wf.PrepareTasks, wf => new PrepareDynamicTasksRequest { OrderIds = wf.WorkflowInput.OrderIds } ); // Execute tasks in parallel using dynamic fork-join _builder.AddTask( wf => wf.DynamicFork, wf => new DynamicForkJoinInput { DynamicTasks = wf.PrepareTasks.Output.TaskDefinitions, DynamicTasksI = wf.PrepareTasks.Output.TaskInputs } ); // Aggregate results from parallel execution _builder.AddTask( wf => wf.AggregateResults, wf => new AggregateResultsRequest { Results = wf.DynamicFork.Output } ); _builder.SetOutput(wf => new BatchProcessingOutput { TotalProcessed = wf.AggregateResults.Output.Count, SuccessCount = wf.AggregateResults.Output.SuccessCount }); } } // Handler that prepares dynamic tasks [OriginalName("BATCH_prepare_tasks")] public class PrepareDynamicTasksHandler : ITaskRequestHandler { public Task Handle( PrepareDynamicTasksRequest request, CancellationToken cancellationToken) { // Create task definitions for each order var taskDefinitions = request.OrderIds.Select((orderId, index) => new WorkflowTask { Name = "PROCESS_order", TaskReferenceName = $"process_order_{index}", Type = "SIMPLE" } ).ToList(); // Create inputs for each task var taskInputs = request.OrderIds.Select(orderId => new Dictionary { { "orderId", orderId } } ).ToList(); return Task.FromResult(new PrepareDynamicTasksResponse { TaskDefinitions = taskDefinitions, TaskInputs = taskInputs }); } } ``` -------------------------------- ### Implement CSharp Task Handler Source: https://github.com/codaxy/conductor-sharp/wiki/Writing-task-handlers Demonstrates how to implement a task handler using the `ITaskRequestHandler` interface. The handler receives a request and returns a response, encapsulating a specific task logic. Task names are generated from class names or the `OriginalName` attribute. ```csharp [OriginalName("CUSTOMER_get")] public class GetCustomerHandler : ITaskRequestHandler { private static Customer[] customers = new Customer[] { new Customer { Id = 1, Address = "Baker Street 221b", Name = "Sherlock Holmes" } }; public Task Handle(GetCustomerRequest request, CancellationToken cancellationToken) { var customer = customers.First(a => a.Id == request.CustomerId); return Task.FromResult(new GetCustomerResponse { Name = customer.Name, Address = customer.Address }); } } ``` -------------------------------- ### Initialize nested objects for task inputs (C# and JSON) Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Demonstrates how to build complex nested objects, including anonymous sub-objects, within a workflow input definition. The C# code constructs the hierarchy, and the JSON snippet shows the flattened parameter structure expected by Conductor. ```csharp wf => new() { NestedObjects = new TestModel { Integer = 1, String = "test", Object = new TestModel { Integer = 1, String = "string", Object = new { NestedInput = "1" } } }, } ``` ```json "inputParameters": { "nested_objects": { "integer": 1, "string": "test", "object": { "integer": 1, "string": "string", "object": { "nested_input": "1" } } } } ``` -------------------------------- ### Define LambdaTaskModel in a ConductorSharp workflow (C#) Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Demonstrates how to create a workflow class that uses LambdaTaskModel to invoke a JavaScript lambda task The snippet defines input and output models, configures the lambda task, and builds the workflow definition. Requires ConductorSharp library and appropriate using directives. ```csharp public class StringAdditionInput : WorkflowInput { public string Input { get; set; } } public class StringAdditionOutput : WorkflowOutput { } [OriginalName("string_addition")] public class StringAddition : Workflow { public StringAddition(WorkflowDefinitionBuilder builder) : base(builder) { } public class StringTaskOutput { public string Output { get; set; } } public class StringTaskInput : IRequest { public string Input { get; set; } } public LambdaTaskModel StringTask { get; set; } public override void BuildDefinition() { _builder.AddTask( wf => wf.StringTask, wf => new() { Input = wf.WorkflowInput.Input }, "return {output: $.input + '_example_string'}" ); } } ``` -------------------------------- ### Define C# Workflow with Type-Safe Expressions Source: https://context7.com/codaxy/conductor-sharp/llms.txt Shows how to create a workflow in C# with type-safe expressions for task inputs, including string interpolation, array initialization, nested objects, and method calls. The workflow demonstrates input processing and output generation. ```csharp public class ExpressionExamplesWorkflow : Workflow { public Task1Handler Task1 { get; set; } public Task2Handler Task2 { get; set; } public ExpressionExamplesWorkflow( WorkflowDefinitionBuilder builder ) : base(builder) { } public override void BuildDefinition() { _builder.AddTask( wf => wf.Task1, wf => new Task1Request { FullName = $"{wf.WorkflowInput.FirstName} {wf.WorkflowInput.LastName}", IdString = "USER_" + wf.WorkflowInput.UserId + "_ACTIVE", Street = ((AddressType)wf.WorkflowInput.Address).StreetName, Tags = new[] { "new", "priority", wf.WorkflowInput.Category }, Items = new List { new ItemDto { Name = wf.WorkflowInput.ItemName, Quantity = wf.WorkflowInput.Quantity, Price = 10.99m }, new ItemDto { Name = "Static Item", Quantity = 1, Price = 5.00m } }, Metadata = new MetadataDto { Source = "web", CreatedBy = wf.WorkflowInput.Username, Timestamp = wf.WorkflowInput.Timestamp, Flags = new FlagsDto { IsActive = true, Priority = wf.WorkflowInput.Priority } }, PreferredLanguage = wf.WorkflowInput.Preferences["language"].Value, Status = wf.WorkflowInput.IsActive ? "ACTIVE" : "INACTIVE", WorkflowName = NamingUtil.NameOf(), UserId = wf.WorkflowInput.UserId, Email = wf.WorkflowInput.Email } ); _builder.AddTask( wf => wf.Task2, wf => new Task2Request { ProcessedName = wf.Task1.Output.FullName, Summary = $"User {wf.Task1.Output.FullName} with ID {wf.WorkflowInput.UserId}", ItemCount = wf.Task1.Output.Items.Count, FirstItemName = wf.Task1.Output.Items[0].Name } ); _builder.SetOutput(wf => new ExampleOutput { Result = wf.Task2.Output.FinalResult, ProcessedAt = wf.Task2.Output.Timestamp }); } } ``` -------------------------------- ### POST /api/workflow/search Source: https://context7.com/codaxy/conductor-sharp/llms.txt Searches for workflows based on a free‑text query and returns a paginated list of results. ```APIDOC ## POST /api/workflow/search ### Description Searches for workflows based on a free‑text query and returns a paginated list of results. ### Method POST ### Endpoint /api/workflow/search ### Parameters #### Query Parameters - **query** (string) - Required - Search query string. ### Response #### Success Response (200) - **results** (array) - List of workflow summaries matching the query. ### Response Example [ { "workflowId": "abcd-1234", "status": "COMPLETED", "startTime": "2024-10-01T12:00:00Z" }, { "workflowId": "efgh-5678", "status": "RUNNING", "startTime": "2024-10-02T08:30:00Z" } ] ``` -------------------------------- ### Implementing Conditional Branching with SwitchTaskModel in C# Source: https://context7.com/codaxy/conductor-sharp/llms.txt This code defines a PaymentWorkflow class that uses SwitchTaskModel to branch based on the payment method from the input, executing specific handlers for credit card, PayPal, or bank transfer, with a default failure case. It depends on WorkflowDefinitionBuilder, various handler classes like ProcessCreditCardHandler, and input/output models such as PaymentWorkflowInput and PaymentWorkflowOutput. Inputs include PaymentMethod, Amount, and CustomerId; outputs indicate success or error; limitations include requiring predefined cases and handling only supported payment methods. ```csharp public class PaymentWorkflowInput : WorkflowInput { public string PaymentMethod { get; set; } // "CREDIT_CARD", "PAYPAL", "BANK_TRANSFER" public decimal Amount { get; set; } public int CustomerId { get; set; } } public class PaymentWorkflow : Workflow { public SwitchTaskModel PaymentMethodSwitch { get; set; } public ProcessCreditCardHandler ProcessCreditCard { get; set; } public ProcessPayPalHandler ProcessPayPal { get; set; } public ProcessBankTransferHandler ProcessBankTransfer { get; set; } public LogPaymentHandler LogPayment { get; set; } public PaymentWorkflow( WorkflowDefinitionBuilder builder ) : base(builder) { } public override void BuildDefinition() { // Switch based on payment method _builder.AddTask( wf => wf.PaymentMethodSwitch, wf => new SwitchTaskInput { SwitchCaseValue = wf.WorkflowInput.PaymentMethod }, new DecisionCases { ["CREDIT_CARD"] = builder => { builder.AddTask( wf => wf.ProcessCreditCard, wf => new ProcessCreditCardRequest { Amount = wf.WorkflowInput.Amount, CustomerId = wf.WorkflowInput.CustomerId } ); }, ["PAYPAL"] = builder => { builder.AddTask( wf => wf.ProcessPayPal, wf => new ProcessPayPalRequest { Amount = wf.WorkflowInput.Amount, CustomerId = wf.WorkflowInput.CustomerId } ); }, ["BANK_TRANSFER"] = builder => { builder.AddTask( wf => wf.ProcessBankTransfer, wf => new ProcessBankTransferRequest { Amount = wf.WorkflowInput.Amount, CustomerId = wf.WorkflowInput.CustomerId } ); }, DefaultCase = builder => { builder.AddTask( wf => wf.TerminateTask, wf => new TerminateTaskInput { TerminationStatus = TerminationStatus.Failed, WorkflowOutput = new { Error = "Invalid payment method" } } ); } } ); // Add logging task after switch (executes regardless of branch) _builder.AddTask( wf => wf.LogPayment, wf => new LogPaymentRequest { PaymentMethod = wf.WorkflowInput.PaymentMethod, Amount = wf.WorkflowInput.Amount } ); _builder.SetOutput(wf => new PaymentWorkflowOutput { Success = true }); } } ``` -------------------------------- ### Define Conductor Workflow in JSON Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Raw JSON representation of a Conductor workflow definition without builders, used for legacy workflows or unsupported features. No compile-time checks; errors found at registration. Inputs like customer_id; structured with tasks array. Limitations: harder to maintain; lacks builder benefits; schema version dependent. ```json { "createTime": 0, "updateTime": 0, "name": "NOTIFICATION_send_to_customer", "description": "{\"description\":null,\"labels\":null}", "version": 3, "tasks": [ { "name": "CUSTOMER_get", "taskReferenceName": "get_customer", "description": "{\"description\":null}", "inputParameters": { "customer_id": "${workflow.input.customer_id}" }, "type": "SIMPLE", "startDelay": 0 }, { "name": "EMAIL_prepare", "taskReferenceName": "prepare_email", "description": "{\"description\":null}", "inputParameters": { "address": "${get_customer.output.address}", "name": "${get_customer.output.name}" }, "type": "SIMPLE", "startDelay": 0 } ], "inputParameters": [ "{\"customer_id\":{\"value\":\"\",\"description\":\" (optional)\"}}" ], "schemaVersion": 2, "restartable": true, "workflowStatusListenerEnabled": true, "timeoutSeconds": 0 } ``` -------------------------------- ### Implement Performance Monitoring Pipeline Behavior Source: https://context7.com/codaxy/conductor-sharp/llms.txt Creates a custom MediatR pipeline behavior for monitoring task performance and recording metrics. The behavior measures execution time, logs task start/completion events, and records duration and failure metrics through an injected metrics service. Requires MediatR, ILogger, and IMetricsService dependencies. ```csharp using MediatR; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; // Performance monitoring behavior public class PerformanceMonitoringBehavior : IPipelineBehavior where TRequest : IRequest { private readonly ILogger> _logger; private readonly IMetricsService _metricsService; public PerformanceMonitoringBehavior( ILogger> logger, IMetricsService metricsService ) { _logger = logger; _metricsService = metricsService; } public async Task Handle( TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken ) { var taskName = typeof(TRequest).Name; var stopwatch = Stopwatch.StartNew(); try { _logger.LogInformation("Starting task {TaskName}", taskName); var response = await next(); stopwatch.Stop(); _logger.LogInformation( "Completed task {TaskName} in {ElapsedMs}ms", taskName, stopwatch.ElapsedMilliseconds ); await _metricsService.RecordTaskDurationAsync( taskName, stopwatch.ElapsedMilliseconds ); return response; } catch (Exception ex) { stopwatch.Stop(); _logger.LogError( ex, "Task {TaskName} failed after {ElapsedMs}ms", taskName, stopwatch.ElapsedMilliseconds ); await _metricsService.RecordTaskFailureAsync(taskName); throw; } } } ``` -------------------------------- ### POST /api/metadata/tasks Source: https://context7.com/codaxy/conductor-sharp/llms.txt Register a new task definition with the Conductor server. ```APIDOC ## POST /api/metadata/tasks ### Description Register a new task definition ### Method POST ### Endpoint /api/metadata/tasks ### Parameters #### Request Body - **taskDef** (TaskDef) - Required - Complete task definition object ### Request Example { "name": "sample_task", "retryCount": 3 } ### Response #### Success Response (200) - **message** (string) - Success message #### Response Example { "message": "Task registered successfully" } ``` -------------------------------- ### C# String Concatenation to JSON Source: https://github.com/codaxy/conductor-sharp/wiki/Workflow-builder Illustrates how string concatenation, including numbers, input/output parameters, and interpolation strings, is translated to JSON input parameters. The `NamingUtil.NameOf` function is also used here for name retrieval. Attribute `[OriginalName]` is used with `StringAddition`. ```csharp wf => new() { Input = 1 + "Str_" + "2Str_" + wf.WorkflowInput.Input + $"My input: {wf.WorkflowInput.Input}" + NamingUtil.NameOf() + 1 } ``` ```json "inputParameters": { "input": "1Str_2Str_${workflow.input.input}My input: ${workflow.input.input}string_addition1", } ```