# LibTmux.Server.CaptureSnapshotAsync

- **Module:** LibTmux
- **Package:** LibTmux
- **Language:** C#
- **Kind:** method
- **Source:** https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/src/LibTmux/Server.Snapshots.cs#L87
- **Page:** https://libtmux.org/en/csharp/latest/reference/libtmux-server-capturesnapshotasync/

```
LibTmux.Server.CaptureSnapshotAsync(depth: SnapshotDepth, cancellationToken: CancellationToken) -> Task<Server>
```

Reads the server and answers a handle carrying what it found.

A handle that has not yet found a live server discovers one first,
because a scope hands back the unmaterialized endpoint it started.

Every depth performs a fresh guarded read. Separate reads are not an
atomic observation; detected topology contradictions fail the attempt
without retrying or publishing partial relations.

## Examples

Capture a new immutable hierarchy, check optional pane state, and distinguish an empty captured relation from one that has not been read. Use Linux or macOS with Git, tmux 3.2a or newer, .NET SDK 10.0.303, and the .NET 8 and 10 runtimes. In an empty directory, fetch the documented library revision:

```console
$ git clone https://github.com/libtmux/libtmux-dotnet.git libtmux-source && \
  git -C libtmux-source checkout --detach cf34b255c896d19a97e7d7fabea58609c916012d
```

Save this complete consumer setup as global.json:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/global.json).

```json
{
  "sdk": {
    "version": "10.0.303",
    "rollForward": "disable",
    "allowPrerelease": false
  },
  "test": {
    "runner": "Microsoft.Testing.Platform"
  }
}
```

Save this complete consumer setup as NuGet.config:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/api/NuGet.config).

```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="libtmux-source" value="libtmux-source/artifacts/api-example-packages" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
  <packageSourceMapping>
    <clear />
    <packageSource key="libtmux-source">
      <package pattern="LibTmux" />
      <package pattern="LibTmux.*" />
    </packageSource>
    <packageSource key="nuget.org">
      <package pattern="*" />
    </packageSource>
  </packageSourceMapping>
</configuration>
```

Save this complete consumer setup as Example.csproj:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/api/csharp/Example.csproj).

```xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>net8.0;net10.0</TargetFrameworks>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <AnalysisLevel>10-recommended</AnalysisLevel>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <PackageReference Include="LibTmux" Version="[0.0.0-alpha.20]" />
  </ItemGroup>
</Project>
```

Save this complete program as Program.cs. It creates a private server; await using disposes its owned scopes after success, cancellation or failure. The complete file contains explicit imports, a top-level async entry point and a cancellation deadline.

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/LibTmux.Examples/Programs/SnapshotAccess.cs).

```csharp
using System;
using System.Linq;
using System.Threading;
using LibTmux;

if (OperatingSystem.IsWindows())
{
    throw new PlatformNotSupportedException("This example requires tmux on Linux or macOS.");
}

using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10));
CancellationToken token = deadline.Token;
string binary = Environment.GetEnvironmentVariable("LIBTMUX_TMUX") ?? "tmux";
string socketName = "csharp-snapshotaccess-" + Guid.NewGuid().ToString("N");
ServerConnectionOptions options = new()
{
    SocketName = socketName,
    ConfigurationFile = "/dev/null",
    TmuxBinaryPath = binary,
};

await using OwnedServerScope owned = await Server.CreateOwnedAsync(options, token);
Server server;
await using (OwnedSessionScope session = await owned.Value.CreateOwnedSessionAsync(
    new NewSessionRequest { Name = "demo", Command = "/bin/cat" }, token))
{
    server = await Server.ConnectAsync(options, token);
    if (server.Sessions.IsCaptured)
    {
        throw new InvalidOperationException("Connecting must not capture the hierarchy.");
    }
    Console.WriteLine("Sessions have not been captured.");

    Server captured = await server.CaptureSnapshotAsync(SnapshotDepth.Panes, token);
    if (!captured.Sessions.IsCaptured)
    {
        throw new InvalidOperationException("The requested sessions were not captured.");
    }
    Session capturedSession = captured.Sessions.Single();
    if (!capturedSession.ActivePane.IsCaptured)
    {
        throw new InvalidOperationException("The active pane was not captured.");
    }
    Pane pane = capturedSession.ActivePane.Value;
    if (pane.CurrentPath is null || pane.CurrentCommand is null)
    {
        throw new InvalidOperationException("The running pane should report its path and command.");
    }
    Console.WriteLine("The captured active pane has a path and command.");
    if (server.Sessions.IsCaptured)
    {
        throw new InvalidOperationException("Capturing must return a new immutable handle.");
    }
    Console.WriteLine("The original handle is still uncaptured.");

    // Keep this private daemon alive after its only owned session is disposed.
    TmuxCommandResult result = await server.ExecuteCommandAsync(
        ["set-option", "-s", "exit-empty", "off"], token);
    if (result.ExitCode != 0)
    {
        throw new InvalidOperationException("Could not keep the empty server alive.");
    }
}
Server empty = await server.CaptureSnapshotAsync(SnapshotDepth.Sessions, token);
if (!empty.Sessions.IsCaptured || empty.Sessions.Count != 0)
{
    throw new InvalidOperationException("An empty captured relation differs from an uncaptured relation.");
}
Console.WriteLine("Captured sessions can be empty.");
```

Build the exact source package and the saved consumer, then run both supported frameworks. The local package feed prevents an unrelated published package from satisfying the restore. Each program checks its result and exits unsuccessfully after an unhandled error:

```console
$ export NUGET_PACKAGES="$PWD/packages" && \
  dotnet restore libtmux-source/src/LibTmux/LibTmux.csproj --locked-mode && \
  dotnet pack libtmux-source/src/LibTmux/LibTmux.csproj \
    --configuration Release --no-restore -p:ContinuousIntegrationBuild=true \
    --output "$PWD/libtmux-source/artifacts/api-example-packages" && \
  dotnet restore Example.csproj --configfile NuGet.config && \
  dotnet build Example.csproj --configuration Release --no-restore --warnaserror && \
  export LIBTMUX_TMUX="$(command -v tmux)" && \
  export TMUX_TMPDIR=/tmp/libtmux-dotnet-dev && \
  mkdir -p "$TMUX_TMPDIR" && \
  unset TMUX TMUX_PANE && \
  dotnet bin/Release/net8.0/Example.dll && \
  dotnet bin/Release/net10.0/Example.dll
```

Expected program output from each framework:

```text
Sessions have not been captured.
The captured active pane has a path and command.
The original handle is still uncaptured.
Captured sessions can be empty.
```

## Parameters

- `depth` (`SnapshotDepth`): How far down the hierarchy to read.
- `cancellationToken` (`CancellationToken`): Cancels the tmux commands.

## Returns

A handle whose relations are the ones this reading found.

## Raises

- [`InvalidOperationException`](https://learn.microsoft.com/dotnet/api/system.invalidoperationexception): The handle has no connection.
- [`ArgumentOutOfRangeException`](https://learn.microsoft.com/dotnet/api/system.argumentoutofrangeexception): The depth is undefined.
- [`InconsistentSnapshotException`](/en/csharp/latest/reference/libtmux-inconsistentsnapshotexception/): The acquired parent, placement, or child-count rows contradict each other.
- [`StaleServerGenerationException`](/en/csharp/latest/reference/libtmux-staleservergenerationexception/): The endpoint now names a different daemon generation.
- [`OperationCanceledException`](https://learn.microsoft.com/dotnet/api/system.operationcanceledexception): Acquisition was cancelled before publication.
