using Elsa.Common.Models;
using Elsa.Expressions.Contracts;
using Elsa.Workflows.Core.Contracts;
using Elsa.Workflows.Core.Models;
using Elsa.Workflows.Core.State;
using Elsa.Workflows.Management.Contracts;
using Elsa.Workflows.Management.Entities;
using Elsa.Workflows.Management.Models;
using Elsa.Workflows.Runtime.Contracts;
using Microsoft.Extensions.DependencyInjection;
namespace Elsa.Testing.Shared;
///
/// Provides extension methods for .
///
public static class ServiceProviderExtensions
{
///
/// Updates the registries.
///
/// The services.
public static async Task PopulateRegistriesAsync(this IServiceProvider services)
{
var activityRegistryPopulator = services.GetRequiredService();
var expressionSyntaxRegistryPopulator = services.GetRequiredService();
await activityRegistryPopulator.PopulateRegistryAsync();
await expressionSyntaxRegistryPopulator.PopulateRegistryAsync();
}
///
/// Imports a workflow definition from a file.
///
/// The services.
/// The file name.
/// The workflow definition.
public static async Task ImportWorkflowDefinitionAsync(this IServiceProvider services, string fileName)
{
var json = await File.ReadAllTextAsync(fileName);
var serializer = services.GetRequiredService();
var workflowDefinitionRequest = serializer.Deserialize(json);
workflowDefinitionRequest.Publish = true;
var workflowDefinitionImporter = services.GetRequiredService();
return await workflowDefinitionImporter.ImportAsync(workflowDefinitionRequest);
}
///
/// Runs a workflow until its end, automatically resuming any bookmark it encounters.
///
/// The services.
/// The ID of the workflow definition.
/// The workflow state.
public static async Task RunWorkflowUntilEndAsync(this IServiceProvider services, string workflowDefinitionId)
{
var startWorkflowOptions = new StartWorkflowRuntimeOptions(null, new Dictionary(), VersionOptions.Published);
var workflowRuntime = services.GetRequiredService();
var result = await workflowRuntime.StartWorkflowAsync(workflowDefinitionId, startWorkflowOptions);
var bookmarks = new Stack(result.Bookmarks);
// Continue resuming the workflow for as long as there are bookmarks to resume.
while (bookmarks.TryPop(out var bookmark))
{
var resumeOptions = new ResumeWorkflowRuntimeOptions(BookmarkId: bookmark.Id);
var resumeResult = await workflowRuntime.ResumeWorkflowAsync(result.WorkflowInstanceId, resumeOptions);
foreach (var newBookmark in resumeResult.Bookmarks)
bookmarks.Push(newBookmark);
}
// Return the workflow state.
return (await workflowRuntime.ExportWorkflowStateAsync(result.WorkflowInstanceId))!;
}
}