Saraff.Twain.Aux.Contracts
2.0.0
dotnet add package Saraff.Twain.Aux.Contracts --version 2.0.0
NuGet\Install-Package Saraff.Twain.Aux.Contracts -Version 2.0.0
<PackageReference Include="Saraff.Twain.Aux.Contracts" Version="2.0.0" />
<PackageVersion Include="Saraff.Twain.Aux.Contracts" Version="2.0.0" />
<PackageReference Include="Saraff.Twain.Aux.Contracts" />
paket add Saraff.Twain.Aux.Contracts --version 2.0.0
#r "nuget: Saraff.Twain.Aux.Contracts, 2.0.0"
#:package Saraff.Twain.Aux.Contracts@2.0.0
#addin nuget:?package=Saraff.Twain.Aux.Contracts&version=2.0.0
#tool nuget:?package=Saraff.Twain.Aux.Contracts&version=2.0.0
Saraff.Twain.Aux 2.0
Out-of-process bridge for Saraff.Twain.NET based on StreamJsonRpc, Saraff.IoC and Saraff.Twain 1.0.34.
A small Host executable owns the real Twain32 object on a dedicated STA thread and exposes it to any client process over stdin/stdout JSON-RPC. This avoids TWAIN/DSM problems inside 64-bit, service, IIS or web processes.
Status
Implemented:
- JSON-RPC 2.0 transport (
LengthHeaderMessageHandler+SystemTextJsonFormatter), protocol handshake and version checks. - Host/client sessions with
Saraff.IoC2.0.0;AuxServiceSitebridgesTwain32.Siteto the container. - Dedicated STA dispatcher with WinForms message pump and nested pumping for callbacks.
- Native transfer over a named pipe (client-created server, ACL by user SID, BMP
bfSizeframing, TIFF EOF), automatic image materialization and memory fallback. - Memory transfer chunks (JSON/base64), assembler for uncompressed BMP and compressed/
MemFilepayloads, palette from the TWAIN capability, configurable limits. - File transfer with a client session directory, DACL for the client/host SIDs, path policy, cleanup and automatic file read/delete.
- Custom
BmpImageHandler/TiffImageHandlerforIStreamProvider/IImageHandlerextension points. SetPalette/ResetPalette,ShowUI,ParentWindowDto(Host/Desktop/Handle).- Extended image info (
ExtImageInfo) and a best-effortCancelAcquireAsync. - Async-first client API and obsolete
TwainAuxClientSyncfacade. - Interactive-user host launch (
CreateProcessAsUser) for services/non-interactive processes. ITwainHost/ITwainClientCallbackswire contracts and fake-engine tests.
Validated locally against the virtual Saraff Screen DS: native BMP, memory, MemoryTiff (NONE/LZW/DEFLATE), MemoryMultipageTiff and file transfers (1920x1080, 24 bpp). MemFile is unsupported by that source. Multi-page TIFF and external codec plugins are covered by tests. x86 TWAIN 1.x/2.x acquisition is verified by scripts/test-x86-twain-modes.ps1. Physical scanner multi-page, real cross-user ACL, palette/UI validation remain.
Requirements
- Windows.
- .NET Framework 4.8 or .NET 8 (
net8.0-windows). - Saraff.Twain 1.0.34, Saraff.IoC 2.0.0, Saraff.Tiff 2.1.0.
- Host and client must use the same
Saraff.Twain.Aux.Contractsprotocol version.
net48 and Saraff.IoC
Saraff.IoC 2.0.0 ships a legacy net40 asset, which NuGet selects for net48 by default. That asset does not support the new registration/scopes API. The package ships buildTransitive/Saraff.Twain.Aux.targets, which injects the netstandard2.0 Saraff.IoC assembly for net48 consumers. A normal PackageReference Include="Saraff.Twain.Aux" works; the source projects use the same workaround.
Projects
| Project | Purpose |
|---|---|
src/Saraff.Twain.Aux.Contracts |
Wire DTOs, ITwainHost, ITwainClientCallbacks, protocol version, STJ defaults |
src/Saraff.Twain.Aux |
Client, host endpoint, transports, DI composition, STA dispatcher, transfers |
tests/Saraff.Twain.Aux.Tests |
Protocol, DI, transfer, conversion and file-policy tests |
samples/Saraff.Twain.Aux.Sample.Host |
Minimal net48 host executable |
samples/Saraff.Twain.Aux.Sample.Client |
Client handshake/info sample |
Host
using Saraff.Twain.Aux.Host;
[STAThread]
private static void Main()
{
TwainAuxHost.RunAsync(new HostOptions
{
TwainPackageVersion = "1.0.34"
}).GetAwaiter().GetResult();
}
TwainAuxHost.RunAsync creates the root ServiceContainer, the STA dispatcher, the real Twain32, registers IStreamProvider/IImageHandler, starts the JSON-RPC endpoint and sets Twain32.Site through AuxServiceSite.
Client
await using var client = await TwainAuxClient.ConnectAsync(new TwainAuxClientOptions
{
HostPath = @"C:\path\to\Saraff.Twain.Aux.Sample.Host.exe",
ConnectTimeout = TimeSpan.FromSeconds(15),
NativeFormat = NativeImageFormat.Bmp
});
client.TransferCompleted += (_, result) =>
{
// result.Image / result.Data / result.FilePath / result.Error
};
await client.OpenDsmAsync();
var sources = await client.GetSourcesAsync();
await client.Host.SetDefaultSourceAsync(new SetSourceRequest { Index = 0 }, default);
await client.OpenDataSourceAsync();
await client.AcquireAsync(new AcquireRequest
{
Mode = TransferMode.Native,
ShowUI = true,
Transfer = new TransferOptions { NativeFormat = NativeImageFormat.Bmp }
});
TwainAuxClient.LastTransfer contains the automatically assembled result. TwainAuxClient.Sync is a blocking compatibility facade ([Obsolete]).
Service / impersonation
TwainAuxClientOptions.LaunchMode controls host launch:
Auto(default): interactive session → current user; session 0/service → interactive desktop user viaCreateProcessAsUser(winsta0\default, WTS/explorer token).CurrentUser: always launch as the current process user.InteractiveUser: force the interactive user (useful for testing from a console).
FallbackToCurrentUser is false by default: a service should fail clearly rather than start a host in session 0 where TWAIN UI cannot appear. Set it to true only for non-UI scenarios.
The impersonation transport fixes the classic parent/child pipe-inheritance problem: parent pipe ends are non-inheritable and only child ends are passed to CreateProcessAsUser. The host is started on winsta0\default with STARTF_USESTDHANDLES.
Host bitness
TWAIN drivers are bitness-specific. Build both host variants:
powershell -ExecutionPolicy Bypass -File .\build-hosts.ps1
Then point TwainAuxClientOptions.HostPath to the artifacts\hosts directory; the client selects x64 or x86 by process bitness (or set an explicit executable path). HostExecutableName controls the executable name inside the architecture directory.
Transfer modes
- Native: client creates a
NamedPipeServerStreamduringXferDone; host writes BMP/TIFF throughIStreamProvider; client reads BMP bybfSize(or TIFF to EOF) and materializesImage. - Memory:
SetupMemXfer/MemXferchunks over JSON (byte[]as base64); client assembles BMP or concatenates compressed/MemFiledata; limits are configurable. - MemoryTiff: TWAIN uses
TwSX.Memory; the host collects uncompressed chunky chunks, assembles TIFF (Saraff.Tiff 2.1.0) and sends it through a named pipe negotiated inSetupMemXfer. The client finalizes the result atXferDone;AcquireCompletedis the end of the whole acquisition. One TIFF per image in the first version. - MemoryMultipageTiff: same as MemoryTiff, but the host keeps all pages and writes one multi-page TIFF at
AcquireCompleted.XferDonefinalizes only the current page;TransferResult.PageCountreports the number of pages. - MemFile: chunks are concatenated and saved to a file in the session transfer directory; the result also exposes the bytes/image.
- File: client proposes a path inside its session directory; host validates the path (
FileTransferPolicy), writes the file and reports it; client reads/deletes it.
TIFF compression
Host-side compression is available for MemoryTiff and MemoryMultipageTiff. The host reports supported codecs in HostInfo.TiffCompressions (built-in NONE, PACKBITS, LZW, ADOBE_DEFLATE, DEFLATE, plus external plugins).
await client.AcquireAsync(new AcquireRequest
{
Mode = TransferMode.MemoryTiff,
Transfer = new TransferOptions { TiffCompression = "LZW" }
});
null/empty compression → no compression (NONE).- Unknown/unsupported codec →
NotSupportedException. - The client can pre-validate against
client.Info.TiffCompressions. TransferResult.TiffCompressionreports the selected codec.
External codec plugins
Copy plugin assemblies implementing Saraff.Tiff.Core.ITiffCompressionCodec into a plugins directory next to the host executable (or set HostOptions.CodecPluginDirectory). The host scans the directory, registers codec types in Saraff.IoC and resolves them with constructor injection; no host rebuild is required.
HostOptions.EnableCodecPlugins(defaulttrue).HostOptions.AllowCodecOverrides(defaultfalse).HostOptions.ContinueOnCodecPluginError(defaultfalse).- Do not copy
Saraff.Tiff.dll/Saraff.Twain.Aux.dllinto the plugins directory; the host assemblies are used. - Custom codecs appear in
HostInfo.TiffCompressionswithIsBuiltIn=false.
MemoryTiff limitations
TWAIN source MemXfer chunks must still be uncompressed (TwCompression.None) and chunky; the host does not decode compressed TWAIN chunks. Compression is applied by the host when writing TIFF. Supported bpp: 8/16/24/32/48/64. TIFF is written to a seekable MemoryStream/temp file and then copied to the pipe. MemoryMultipageTiff keeps all pages until AcquireCompleted and sends one final TIFF.
Images, palette and extended info
Native transfer converts a packed DIB to BMP (BmpImageHandler) or TIFF (TiffImageHandler) before writing to the pipe. Memory transfer uses the palette from the Palette capability when available (8 bpp); otherwise it stores a grayscale palette. XferDone carries ExtImageInfo entries (values are base64 for byte arrays).
Cancellation
CancelAcquireAsync sets an engine flag and is delivered through the next transfer event (XferDone, MemXfer, SetupFileXfer, ...). Saraff.Twain 1.0.34 does not expose a thread-agnostic cancel API, so an already-open modal DSM UI may need to be closed by the user.
Threading
Saraff.Twain 1.0.34 enforces that every TWAIN operation runs on the thread that performed the first operation. The host routes all RPC methods through StaDispatcher; callbacks use RunNestedUntil so a client can call back into the host from an event handler. Do not call Twain32 from the JSON-RPC thread.
Build and test
dotnet build .\Saraff.Twain.Aux.sln
dotnet test .\tests\Saraff.Twain.Aux.Tests\Saraff.Twain.Aux.Tests.csproj
dotnet pack .\src\Saraff.Twain.Aux\Saraff.Twain.Aux.csproj -c Release
The local test project targets net10.0-windows because the development machine only has the .NET 10 runtime; the library itself builds for net48 and net8.0-windows.
Publishing
See docs/publishing.md for the NuGet.org Trusted Publishing policy, the NUGET_USER secret and the tag-based release flow.
Manual validation
See docs/testing.md for the scanner checklist and the elevated service/impersonation probe:
.\scripts\test-scanner.ps1 -Mode native -Output C:\temp\scan.bmp
.\scripts\test-scanner.ps1 -Mode memtiff -Compression LZW -Output C:\temp\scan-lzw.tif
.\scripts\test-x86-twain-modes.ps1
powershell -ExecutionPolicy Bypass -File .\scripts\test-service-impersonation.ps1
License
LGPL-3.0-or-later. See COPYING.txt and COPYING.LESSER.txt.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- System.Text.Json (>= 8.0.5)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Saraff.Twain.Aux.Contracts:
| Package | Downloads |
|---|---|
|
Saraff.Twain.Aux
Provides out-of-process interaction with Saraff.Twain.NET over JSON-RPC. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2.0.0 | 65 | 11/27/2026 |
| 2.0.0-alpha.1 | 62 | 11/27/2026 |