A Function That Reads the Document File¶
A county records office wants a SHA-256 fingerprint of every incoming file, stored on the document, so it can find exact duplicates later. A Custom Step cannot read file bytes, and Call External API cannot send a file. Your own function can: it downloads each file through the KnowledgeLake API, hashes it, and writes the result back.
At a glance
- Extension point Your own endpoint, called by Call External API
- You need An Azure Function app (in-process, .NET 8); the
KL.APIClientclient, generated from your tenant's spec; an API token for a service account with Manage Work Items; permission to edit the workflow. The function writes documentGeneral.FileSha256andGeneral.FileName. - Teaches Finding a document's input file, downloading it with
GetDocumentFile, and disposing the stream.
How file access works¶
V1_KWorkItemAPI/GetWorkItemreturns each document withFiles[]. Each file hasId,Type(Input,OutputorOCR),FileNameandExtension.V1_KWorkItemAPI/GetDocumentFiletakesWorkItemId,DocumentIdandDocumentFileIdand returns the bytes as a stream.- The Input file is the file as it arrived. An Output file exists after a step creates one, for example a conversion.
Set it up¶
- Create the project from the three files below. Generate
KL.APIClientfrom your tenant's spec into aKLClientfolder next to the project folder (not inside it). See Generate the client. - Deploy the function app. Add the app settings
KnowledgeLakeApiURL(https://{tenant}/api),KnowledgeLakeApiTokenandFUNCTIONS_INPROC_NET8_ENABLED=1. - In the workflow, add Call External API after the documents arrive:
- External API URL:
https://{function-app}.azurewebsites.net/api/FingerprintFiles?code={function key} - REST Verb:
POST - Response Metadata Key:
FingerprintResult - Timeout: below 230 seconds, for example
180 - Save the workflow.
Script¶
The project has three files. The function hashes one file per document and writes document General.FileSha256 and General.FileName.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using KL.APIClient.Client;
using KL.APIClient.Model;
namespace KLFunctionExample
{
// Called from a workflow by a Call External API step (POST).
// Per document: General.FileSha256 (hex SHA-256 of the input file), General.FileName.
public static class FingerprintFilesFunction
{
[FunctionName("FingerprintFiles")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
try
{
if (!req.Headers.ContainsKey("WorkItemId"))
{
throw new Exception("Missing WorkItemId header");
}
Guid workItemId = Guid.Parse(req.Headers["WorkItemId"]);
string token = Environment.GetEnvironmentVariable("KnowledgeLakeApiToken");
string apiUrl = Environment.GetEnvironmentVariable("KnowledgeLakeApiURL");
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(apiUrl))
{
throw new Exception("KnowledgeLakeApiToken or KnowledgeLakeApiURL is not set");
}
var config = new Configuration { BasePath = apiUrl };
config.AddApiKey("TempIdentityToken", token);
var client = new KL.APIClient.Api.V1KWorkItemAPIApi(config);
var workItem = await client.V1KWorkItemAPIControllerGetWorkItemAsync(
new PaasWorkItemIdDTO { WorkItemId = workItemId });
if (!workItem.Success)
{
throw new Exception("GetWorkItem failed");
}
int done = 0;
foreach (var document in workItem.Data.Documents)
{
// Prefer the file as it arrived; fall back to the first file.
var file = document.Files.FirstOrDefault(f => f.Type == DocumentFileType.Input)
?? document.Files.FirstOrDefault();
if (file == null)
{
throw new Exception("Document " + document.Id + " has no file");
}
string hash;
using (var stream = await client.V1KWorkItemAPIControllerGetDocumentFileAsync(
new GetDocumentFileParameter
{
WorkItemId = workItemId,
DocumentId = document.Id,
DocumentFileId = file.Id
}))
using (var sha = SHA256.Create())
{
hash = Convert.ToHexString(sha.ComputeHash(stream));
}
var update = await client.V1KWorkItemAPIControllerUpsertDocumentMetadataAsync(
new UpsertPaasDocumentMetadataParameter
{
WorkItemId = workItemId,
DocumentId = document.Id,
Metadata = new List<MetadataValueDTO>
{
new MetadataValueDTO { Bucket = "General", Key = "FileSha256", Value = hash },
new MetadataValueDTO { Bucket = "General", Key = "FileName", Value = file.FileName }
}
});
if (!update.Success)
{
throw new Exception("UpsertDocumentMetadata failed for " + document.Id);
}
done++;
}
// This body lands in ApiResults.FingerprintResult.
return new OkObjectResult(new { documents = done });
}
catch (Exception ex)
{
log.LogError(ex, "FingerprintFiles failed");
return new BadRequestObjectResult("Error: " + ex.Message);
}
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.4.1" />
</ItemGroup>
<ItemGroup>
<!-- The KnowledgeLake client you generated from your tenant's spec. -->
<ProjectReference Include="..\KLClient\src\KL.APIClient\KL.APIClient.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"FUNCTIONS_INPROC_NET8_ENABLED": "1",
"KnowledgeLakeApiURL": "https://your-tenant.example.com/api"
}
}
Copy it to local.settings.json (not in source control). Put the token in your user environment variable KnowledgeLakeApiToken, never in the file.
How it works¶
WorkItemIdcomes from the header that Call External API adds. Without it the function fails at once.- For each document, the function picks the Input file, or the first file when there is no Input file.
GetDocumentFilereturns a stream. Theusingblocks dispose the stream and the hash object as soon as the hash is done.- Read the stream once. It does not seek back.
UpsertDocumentMetadatawrites the hash and the file name. A second run writes the same values, so a retry is safe.- Any failure returns HTTP 400, so the workflow step fails instead of reporting success with nothing done.
Test it¶
- Upload the same PDF twice, as two work items, on a non-production tenant.
- Open each work item in Monitor or Insight and read
General.FileSha256on the document. - Read
ApiResults.FingerprintResulton the work item.
You should see
the same 64-character General.FileSha256 on both documents, General.FileName with the uploaded name, and ApiResults.FingerprintResult = {"documents":1}.
What can go wrong¶
Watch out
- The step times out on large work items. Downloading many large files takes time. Keep the step timeout below 230 seconds and test with your largest expected work item. For very large work items, split the work or process files asynchronously.
GetDocumentFilethrows a client exception. The API returned an error instead of a file, for example because the token lacks Manage Work Items. Check the token's features.- "Document ... has no file". The document has no stored file yet, for example an empty document created by a Custom Step. Run the function after the documents have files.
- The hash differs between two "identical" files. One copy was rescanned or re-saved, so the bytes differ. A byte hash finds exact duplicates only.
Variations¶
- Find the duplicate. Write the hash, then let a later step look it up in your records system, or write it to a data source with Insert Into Data Source and check for an existing row.
- Send the file to another service. Replace the hash with an upload to your storage or OCR service, and write back the service's id. Keep the same stream handling.