Skip to content

Writing a custom Activity (with example)

Legacy (Process Designer)

This page describes a custom activity for Process Designer, built as an Azure Function and called by the Send to Azure Function activity. It was replaced by the Call External API step, which calls your own endpoint from a Workflow. For new work, use Your own endpoint.

Every business has it's own needs and most of your use cases will not be resolved with the below example. However, we want to provide you with a real-life example of what a custom activity looks like in Visual Studio when writing these yourselves.

After proceeding through the first 5 steps in the Add Custom Activities using Azure Functions guide, you're ready to write your custom activity. This example will add two new metadata properties to the first document in any batch processed by this activity.

NOTE: The full set of code for this example is attached to this article in a text file called CustomActivityExample.txt.

  1. Open your Solution in Visual Studio.
  2. Right-click and open Function1.cs under the Model folder in the Solution Explorer.
  3. Add the following using statements to allow for use with the KnowledgeLake API for this example.
using Microsoft.Extensions.Configuration;
using IO.Swagger.Client;
using IO.Swagger.Api;
using IO.Swagger.Model;
using System.Collections.Generic;
  1. Add a new class below the Function1 class.
public class StepDefinitionRequestDTO
    {
        public Guid WorkItemId { get; set; }
        public Guid HoldId { get; set; }
        public string KLAPIRUI { get; set; }
    }
  1. Clear out the code in the body of the Run.
  2. Replace the parameters of the Run function so it looks as follows:
public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ExecutionContext executionContext,
            ILogger logger)
  1. Next, we will get the APIToken value from our Function app. To do this, add the following to the Run function.
var config = new ConfigurationBuilder()
            .SetBasePath(executionContext.FunctionAppDirectory)
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

var token = config["APIToken"];
logger.LogInformation($"API token was: '{token}'"); 

var client = new ApiClient();
if (!Configuration.ApiKey.ContainsKey("TempIdentityToken"))
{
         Configuration.ApiKey.Add("TempIdentityToken", token);
}
  1. The Send to Azure Function activity passes over the Batch ID for the batch it is processing. We need to assign that to a variable so we can retrieve it later using the batch service.
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var data = JsonConvert.DeserializeObject<StepDefinitionRequestDTO>(requestBody);

           var batchId = data.WorkItemId;
           logger.LogInformation($"BatchId was: '{batchId}'");
  1. We need to initialize the clients for the two API systems we will be using, the Batch API and the Processing API.
var batchClient = new V1BatchAPIApi(client);
var processingClient = new V1ProcessingAPIApi(client);
  1. In order to get our batch and make modifications to it, we first need to lock the batch. The response from this request can be used to make a BatchToken object which we will pass to the API in subsequent calls.
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var data = JsonConvert.DeserializeObject<StepDefinitionRequestDTO>(requestBody);

var batchId = data.WorkItemId;

var lockBatchRespone = batchClient.V1BatchAPIControllerLockBatch(new IO.Swagger.Model.BatchIdentifierParameter { BatchId = batchId }); 

var locationId = lockBatchRespone.Data.LocationId;
var lockId = lockBatchRespone.Data.LockId; 

var batchToken = new BatchTokenDTO()
{
         BatchId = batchId,
         LocationId = locationId,
         LockId = lockId
};
  1. Next, we will get the batch from the batch service and assign the id of the first document to a variable.
var getBatchResponse = batchClient.V1BatchAPIControllerGetBatch(batchToken); 
var firstDocId = Guid.NewGuid();
if (getBatchResponse.Success.HasValue && getBatchResponse.Success.Value && getBatchResponse.Data.Documents.Count > 0)
{
        firstDocId = getBatchResponse.Data.Documents[0].Id.Value;
}
else
{
        return new BadRequestObjectResult("Batch does not contain documents.");
}
  1. To construct a DocumentMetadataAPIParameter object, add some key-value pairs, and then upsert that metadata onto the document.
var metadata = new List<BatchMetadataAPIParameterMetadata>();
metadata.Add(new BatchMetadataAPIParameterMetadata()
{ Bucket = "Index", Key = "Vegetable", Value = "Carrot" });
metadata.Add(new BatchMetadataAPIParameterMetadata()
{ Bucket = "Index", Key = "Fruit", Value = "Kiwi" });
var upsertMetadataResponse = batchClient.V1BatchAPIControllerUpsertDocumentMetadata(new DocumentMetadataAPIParameter() 
{ BatchToken = batchToken, DocumentId = firstDocId, Metadata = metadata });
  1. We must now commit these changes back to the Batch Authority. The below code will remove the lock on the batch and release the hold so that it can continue to the next step in its document process.
13. We must now commit these changes back to the Batch Authority. The below code will remove the lock on the batch and release the hold so that it can continue to the next step in its document process.
  1. Right-click your solution in the Solution Explorer and Build your solution.

If you are following along with the Add Custom Activities using Azure Functions walkthrough, your next step will be to Publish your Function to your Function App in Azure.