A common scenario is to have a separate workflow server that handles the orchestration of tasks, and a separate application that is responsible for executing these tasks.
To see how this works, we will create two ASP.NET Core Web applications that communicate with each other using webhooks:
ElsaServer: an ASP.NET Core Web application scaffolded from this guide.
Onboarding: another ASP.NET Core Web Application that exposes a webhook endpoint to receive events from the workflow server and provides UI to the user to view and complete tasks.
Together, the two applications implement an employee onboarding process. The role of the workflow server is to orchestrate the process, while the onboarding app is responsible for executing individual tasks requested by the workflow server to execute. The workflow server will leverage the RunTask activity to request tasks to be executed by the Onboarding app.
These tasks will be completed by a human user. As a task is marked as completed, a signal in the form of an HTTP request is sent back to the workflow server, which then proceeds to the next step in the process.
With this setup, the workflow server will invoke the configured URL everytime the RunTask activity executes.
Creating the Workflow
We'll see how to create the workflow using the programmatic approach as well as using the designer.
Programmatic
To create the Onboarding workflow, follow these steps:
1
Create Workflow Class
Create a new class called Onboarding:
Workflows/Onboarding.cs
usingElsa.Extensions;usingElsa.Workflows;usingElsa.Workflows.Activities;usingElsa.Workflows.Contracts;usingElsa.Workflows.Runtime.Activities;usingParallel=Elsa.Workflows.Activities.Parallel;namespaceElsaServer.Workflows;publicclassOnboarding:WorkflowBase{protectedoverridevoidBuild(IWorkflowBuilder builder) {var employee =builder.WithVariable<object>();builder.Root=newSequence { Activities = {newSetVariable { Variable = employee, Value =new(context =>context.GetInput("Employee")) },newRunTask("Create Email Account") { Payload =new(context =>newDictionary<string,object> { ["Employee"] =employee.Get(context)!, ["Description"] ="Create an email account for the new employee." }) },newParallel { Activities = {newRunTask("Create Slack Account") { Payload =new(context =>newDictionary<string,object> { ["Employee"] =employee.Get(context)!, ["Description"] ="Create a Slack account for the new employee." }) },newRunTask("Create GitHub Account") { Payload =new(context =>newDictionary<string,object> { ["Employee"] =employee.Get(context)!, ["Description"] ="Create a GitHub account for the new employee." }) },newRunTask("Add to HR System") { Payload =new(context =>newDictionary<string,object> { ["Employee"] =employee.Get(context)!, ["Description"] ="Add the new employee to the HR system." }) } } },newEnd() } }; }}
The above workflow will be registered with the workflow engine automatically since the Elsa Server is configured to find all workflows in the same assembly of the Program class.
With that in place, let's create the Onboarding application next.
You can download the workflow and import it using Elsa Studio.
Designing the Workflow
Start the workflow server application and the Elsa Studio container connected to the server.
To create the workflow, follow these steps:
1
Create Workflow
2
Add Employee Variable
When we execute the workflow later on, we will be sending along information about the employee to onboard.
To capture this employee input, we will store it in a variable called Employee.
From the Variables tab, create a new variable called Employee of type Object.
3
Add Set Employee Activity
From the Activity Picker, drag and drop the Set Variable activity on the design canvas and configure its input fields as follows:
Variable
Employee
Value
getInput("Employee")
returnInput.Get("Employee");
4
Add Create Email Account Activity
Now it is time to create an email account for the new employee.
The workflow server itself will not perform this task; instead, it will send a webhook event to the Onboarding application that we will create later on.
To send this webhook event, we leverage the Run Task activity.
Add the Run Task activity to the design surface and configure it as follows:
Task NameCreate Email Account
Payload
return { employee:getEmployee(), description:"Create an email account for the new employee."}
returnnew{ Employee =Variables.Employee, Description ="Create an email account for the new employee."};
5
Add Create Slack Account Activity
Now that the email account has been setup for the new employee, it is time to setup their Slack account.
Just like the Create Email Account task, the workflow should send a webhook event to the Onboarding application using another Run Task activity.
Add the Run Task activity to the design surface and configure it as follows:
Task NameCreate Slack Account
Payload
return { employee:getEmployee(), description:"Create a Slack account for the new employee."}
returnnew { Employee =Variables.Employee, Description ="Create a Slack account for the new employee."};
6
Add Create GitHub Account Activity
At the same time that the Slack account is being created, the Onboarding app should be able to go ahead and create a GitHub account at the same time.
Here, too, the workflow should send a webhook event to the Onboarding application using another Run Task activity.
Add another Run Task activity to the design surface and configure it as follows:
Task Name
Create GitHub Account
Payload
return { employee:getEmployee(), description:"Create a GitHub account for the new employee."}
return new { Employee = Variables.Employee, Description = "Create a GitHub account for the new employee."};
7
Add Add to HR System Activity
While a Slack account and a GitHub account are being provisioned for the new employee, they should be added to the HR system.
As you might have guessed, the workflow should send a webhook event to the Onboarding application using another Run Task activity.
Add another Run Task activity to the design surface and configure it as follows:
Task Name
Add to HR System
Payload
return { employee:getEmployee(), description:"Add the new employee to the HR system."}
return new { Employee = Variables.Employee, Description = "Add the new employee to the HR system."};
8
Add End Activity
Although this step is optional, it is generally a good idea to be explicit and signify the end of the workflow.
9
Connect Activities
Now that we have all the pieces on the board, let's connect them together as shown in the above visual.
10
Publish the Workflow
Before we can invoke the workflow, we need to publish our changes by clicking the Publish button.
Creating the Onboarding Application
To create the Onboarding application, we will create a new project based on the MVC Web Application template.
The purpose of this application is to receive webhook events from the workflow server and create Task records in the database.
The UI of the application will display a list of these tasks and allow the user to click a Complete button.
Upon clicking this button, the application will send an HTTP request to the workflow server to resume the Onboarding workflow.
Follow these steps to create the Onboarding application:
1
Create Project
Run the following command to generate a new MVC Application:
For this application, we'll use Entity Framework Core to store the onboarding tasks in a SQLite database. First, let's model the onboarding task by creating a new class called OnboardingTask:
Entities/OnboardingTask.cs
namespaceOnboarding.Entities;/// <summary>/// A task that needs to be completed by the user./// </summary>publicclassOnboardingTask{ /// <summary> /// The ID of the task. /// </summary>publiclong Id { get; set; } /// <summary> /// An external ID that can be used to reference the task. /// </summary>publicstring ExternalId { get; set; } =default!; /// <summary> /// The ID of the onboarding process that the task belongs to. /// </summary>publicstring ProcessId { get; set; } =default!; /// <summary> /// The name of the task. /// </summary>publicstring Name { get; set; } =default!; /// <summary> /// The task description. /// </summary>publicstring Description { get; set; } =default!; /// <summary> /// The name of the employee being onboarded. /// </summary>publicstring EmployeeName { get; set; } =default!; /// <summary> /// The email address of the employee being onboarded. /// </summary>publicstring EmployeeEmail { get; set; } =default!; /// <summary> /// Whether the task has been completed. /// </summary>publicbool IsCompleted { get; set; } /// <summary> /// The date and time when the task was created. /// </summary>publicDateTimeOffset CreatedAt { get; set; } /// <summary> /// The date and time when the task was completed. /// </summary>publicDateTimeOffset? CompletedAt { get; set; }}
In order to have the application generate the necessary database structure automatically for us, we need to generate migration classes.
Run the following command to do so:
dotnetefmigrationsaddInitial
7
Apply Migrations
Run the following command to apply the migrations:
dotnetefdatabaseupdate
This will apply the migration and generate the Task table in the onboarding.db SQLite database.
8
Task List UI
Now that we have our database access layer setup, let's work on the UI to display a list of tasks. For that, we will first introduce a view model called IndexViewModel for the Index action of the homeController:
The HomeController is able to list pending tasks. Now, let's add another action to it that can handle the event when a user clicks the Complete button.
Add the following action method to HomeController:
The above listing uses the ElsaClient to report the task as completed, which we will create next.
12
Elsa API Client
To interact with the Elsa Server's REST API, we will create an HTTP client called ElsaClient.
Create a new class called ElsaClient:
Services/ElsaClient.cs
namespaceOnboarding.Services;/// <summary>/// A client for the Elsa API./// </summary>publicclassElsaClient(HttpClient httpClient){ /// <summary> /// Reports a task as completed. /// </summary> /// <paramname="taskId">The ID of the task to complete.</param> /// <paramname="result">The result of the task.</param> /// <paramname="cancellationToken">An optional cancellation token.</param>publicasyncTaskReportTaskCompletedAsync(string taskId,object? result =default,CancellationToken cancellationToken =default) {var url =newUri($"tasks/{taskId}/complete",UriKind.Relative);var request =new { Result = result };awaithttpClient.PostAsJsonAsync(url, request, cancellationToken); }}
13
Register ElsaClient
Update Program.cs to configure the Elsa HTTP client as follows:
Program.cs
var configuration =builder.Configuration;builder.Services.AddHttpClient<ElsaClient>(httpClient =>{var url =configuration["Elsa:ServerUrl"]!.TrimEnd('/') +'/';var apiKey =configuration["Elsa:ApiKey"]!;httpClient.BaseAddress=newUri(url);httpClient.DefaultRequestHeaders.Authorization=newAuthenticationHeaderValue("ApiKey", apiKey);});
14
appsettings.json
The Elsa configuration section used in the previous step is defined in appsettings.json as follows:
Now that we have both the Elsa Server and Onboarding applications ready, let's try it out.
1
Start Onboarding App
Run the Onboarding project:
dotnetrun--urls=https://localhost:5002
2
Start Onboarding Workflow
To initiate a new execution of the Onboarding workflow, we will send an HTTP request to Elsa Server's REST API that can execute a workflow by its definition ID and receive input.
As input, we will send a small JSON payload that represents the new employee to onboard:
Make sure to replace {workflow_definition_id} with the actual workflow definition ID of the Onboarding workflow.
3
View Tasks
The effect of the above request is that a new task will be created in the database, which will be displayed in the web application:
4
Complete Tasks
When you click the Complete button, the task will be marked as completed in the database and the workflow will continue. When you refresh the Task list page, the task will be gone, but 3 new tasks will be created in the database:
5
Workflow Completed
Once you complete all tasks, the workflow will be completed:
Summary
In this guide, we have seen how to set up an Elsa Server project and configure it to send webhook events to the Onboarding application.
We have seen how to leverage the Run Task activity that generates Run Task webhook events.
From the Onboarding app, we leveraged an Elsa REST API to report a given task as completed, which causes the workflow to resume,
Source Code
The completed code for this guide can be found here.