# C# and .NET
Source: https://www.desktopaccountingapi.com/docs/sdks/dotnet/

> Install and use the Desktop Accounting API .NET SDK, with async methods, decimal money, IAsyncEnumerable pagination and typed exceptions.

```sh
dotnet add package DesktopAccountingAPI.QuickBooksDesktop --version 0.12.1
```

Targets `net8.0` and `netstandard2.0`, so it runs on .NET 8 and newer and on .NET Framework 4.6.2 and newer. All methods are asynchronous and accept a `CancellationToken`. Models and inputs are in the `DesktopAccountingApi.QuickBooksDesktop.Models` namespace.

## Create a client

```csharp
using DesktopAccountingApi.QuickBooksDesktop;
using DesktopAccountingApi.QuickBooksDesktop.Models;

var client = new DesktopAccountingApiClient(new ClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("DAAPI_SECRET_KEY"), // the default
    Timeout = TimeSpan.FromSeconds(100),
    MaxRetries = 2,
});

var qb = client.ForEndUser("eu_01j9x4m6v4c8k2t7q0r5s3w1zb");
```

Register one `DesktopAccountingApiClient` as a singleton and call `ForEndUser` per customer.

## Make calls

```csharp
var customer = await qb.Qbd.Customers.CreateAsync(new CustomerCreateInput
{
    Name = "Northwind Traders",
    Email = "ap@northwind.example",
});

var invoice = await qb.Qbd.Invoices.CreateAsync(new InvoiceCreateInput
{
    CustomerId = customer.Id,
    TransactionDate = new DateOnly(2026, 10, 5),
    Lines = new[] { new InvoiceLineCreateInput { ItemId = "80000003-1730311000", Quantity = 2, Rate = 125.00m } },
});

await qb.Qbd.Invoices.UpdateAsync(invoice.Id, new InvoiceUpdateInput
{
    RevisionNumber = invoice.RevisionNumber,
    Memo = "Thanks for your order",
});
```

Money is `decimal`, dates are `DateOnly` and timestamps are `DateTimeOffset`. Input objects track which properties you set: unset properties are omitted, and setting a clearable property to `null` sends `null`.

Per-call options use `RequestOptions`:

```csharp
await qb.Qbd.Invoices.CreateAsync(input, new RequestOptions { IdempotencyKey = "order-5541-invoice" });
```

## Pagination

List methods return a `Pager<T>`, which is `IAsyncEnumerable<T>`:

```csharp
await foreach (var invoice in qb.Qbd.Invoices.ListAsync(new InvoiceListParams { UpdatedAfter = "2026-10-01" }))
{
    Console.WriteLine($"{invoice.RefNumber} {invoice.Subtotal}");
}
```

Fast item loops request the next page when they reach it. If you keep requesting items after holding a page for more than two seconds, the iterator can fetch the next page early to reduce cursor expiry. A later `break` can leave that page unused. Page-by-page iteration fetches a page only when requested, so fetch the next page promptly. Read-ahead cannot keep a cursor alive while your code pauses indefinitely. `GetFirstPageAsync()`, `PagesAsync()` and `ListAllAsync()` give you one page, page by page, or everything in a list. If the cursor expires, iteration throws `CursorExpiredException` with `ItemsYielded`, `PagesServed`, `LastId`, `LastUpdatedAt` and `Reason`, and does not restart the list. See [Pagination](https://www.desktopaccountingapi.com/docs/guides/pagination/).

## Exceptions

All API errors derive from `ApiException`: `InvalidRequestException`, `AuthenticationException`, `PermissionException`, `BillingException`, `RateLimitException`, `IntegrationConnectionException`, `IntegrationException`, `OutcomeUnknownException`, `InternalException`, `CursorExpiredException` and `ResultUnavailableException` (the result is no longer available: never send an applied write again, read the object instead; a read is safe to send again). `ApiConnectionException` means no response arrived. `RequestPendingException` means the SDK stopped waiting for a request that reached QuickBooks: the client timeout ended, or checking on it failed (the failed check says nothing about the write). It carries `RequestId`, `TimeoutError` and `IdempotencyKey`; resend a write only with that key. Every exception of a write carries `IdempotencyKey`.

```csharp
try
{
    await qb.Qbd.HealthCheckAsync();
}
catch (IntegrationConnectionException ex)
{
    Console.WriteLine(ex.UserFacingMessage);
}
catch (ApiException ex)
{
    Console.WriteLine($"{ex.Code} {ex.RequestId} {ex.Message}");
}
```

Each exception exposes `Code`, `Type`, `UserFacingMessage`, `HttpStatusCode`, `IntegrationCode`, `RequestId`, `Retryable`, `Outcome`, `Param` and `Details`. See [Error handling](https://www.desktopaccountingapi.com/docs/guides/error-handling/).

## Idempotency and retries

Writes get an idempotency key automatically, reused across retries; set `RequestOptions.IdempotencyKey` to use your own. Retries follow `Daapi-Should-Retry` and never repeat a write with an unknown or pending outcome. See [Idempotency](https://www.desktopaccountingapi.com/docs/guides/idempotency/).

## Async requests

Each resource with operations QuickBooks runs has an `Enqueue` accessor with the same methods. They queue the request without waiting and return a `RequestHandle<T>`:

```csharp
var handle = await qb.Qbd.Invoices.Enqueue.CreateAsync(input, new RequestOptions { QueueTtl = TimeSpan.FromHours(1) });
Console.WriteLine(handle.Id); // req_...

Invoice created = await handle.WaitAsync(TimeSpan.FromMinutes(2)); // long-polls until QuickBooks answers
```

`StatusAsync()` reads the request once, and `ResultAsync()` returns the result if the request has finished or throws `RequestPendingException` if it has not. A write the API [recovered](https://www.desktopaccountingapi.com/docs/guides/request-lifecycle/#recovered-writes) without its result throws `ResultUnavailableException` from `WaitAsync()` and `ResultAsync()`: do not send it again; retrieve the object by `ex.RecoveredObjectId`.

## Raw responses

Every method that does not page has a `...WithResponseAsync` variant that returns `ApiResponse<T>` with `Data`, `StatusCode`, `Headers`, `RequestId` and `Warnings`:

```csharp
var response = await qb.Qbd.Customers.RetrieveWithResponseAsync("80000001-1730311000");
Console.WriteLine($"{response.StatusCode} {response.RequestId} {response.Data.Name}");
```

## Logging

Set `ClientOptions.Logger` to an `Action<DaapiLogLevel, string>` to get one line per HTTP attempt, retry and long poll. The SDK never logs the API key, the `Authorization` header or bodies.

## Webhooks

```csharp
var ev = WebhookVerifier.Verify(rawBody, name => request.Headers[name].ToString(), secret);
if (ev.Type == WebhookEventTypes.RequestSucceeded)
{
    // ev.Data, ev.DataAs<Request>()
}
```

`Verify` checks the signature and timestamp against the raw body and returns the event, or throws `WebhookVerificationException`. `client.Webhooks.Verify(...)` does the same. See [Webhooks](https://www.desktopaccountingapi.com/docs/guides/webhooks/).

## Porting from Conductor

Conductor has no .NET SDK, so .NET code that used Conductor calls its REST API. The paths, parameters and JSON fields are the same here; move the settings to `ClientOptions`:

```csharp
// Before: HttpClient calls to https://api.conductor.is/v1 with a Conductor-End-User-Id header.
using var client = new DesktopAccountingApiClient(new ClientOptions
{
    BaseUrl = "https://api.desktopaccountingapi.com/v1", // a trailing /v1 is accepted
    Timeout = TimeSpan.FromSeconds(120), // per attempt
    TotalTimeout = TimeSpan.FromMinutes(5), // the whole call, retries included
    DefaultHeaders = new Dictionary<string, string> { ["X-Trace-Id"] = "billing-sync" },
});
var qb = client.ForEndUser("eu_01j9..."); // replaces Conductor-End-User-Id
try
{
    await qb.Qbd.Invoices.RetrieveAsync("1A4F-1730312567");
}
catch (ApiException ex) when (ex.Status == 404)
{
    Console.WriteLine($"{ex.Code} {ex.UserFacingMessage} {ex.RequestId}");
}
```

Conductor's error fields (`code`, `type`, `userFacingMessage`, `httpStatusCode`, `integrationCode`, `requestId`) are properties of `ApiException`, next to `Cause`, `Fixes`, `DocsUrl` and `Outcome`.
