Tildom.Libraries.Xero 9.0.0

Prefix Reserved
dotnet add package Tildom.Libraries.Xero --version 9.0.0
                    
NuGet\Install-Package Tildom.Libraries.Xero -Version 9.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tildom.Libraries.Xero" Version="9.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tildom.Libraries.Xero" Version="9.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Tildom.Libraries.Xero" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tildom.Libraries.Xero --version 9.0.0
                    
#r "nuget: Tildom.Libraries.Xero, 9.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tildom.Libraries.Xero@9.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tildom.Libraries.Xero&version=9.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Tildom.Libraries.Xero&version=9.0.0
                    
Install as a Cake Tool

Tildom.Libraries.Xero

A C# library that provides a simplified interface for interacting with Xero's Accounting APIs. This library wraps the official Xero.NetStandard.OAuth2 package to provide a more streamlined experience for reading data from Xero.

Features

  • Simple, consistent API for retrieving data from Xero
  • Automatic pagination handling for large result sets
  • Token caching and automatic refresh for improved performance
  • Retry logic for handling transient failures
  • Rate limiting to prevent API throttling
  • Proper error handling and meaningful error messages
  • Dependency injection support through Microsoft.Extensions.DependencyInjection

Installation

Install the package via NuGet:

Install-Package Tildom.Libraries.Xero

Or using the .NET CLI:

dotnet add package Tildom.Libraries.Xero

Getting Started

1. Register the services in your DI container

using Microsoft.Extensions.DependencyInjection;
using Tildom.Libraries.Xero.Configuration;
using Tildom.Libraries.Xero.Services;

public void ConfigureServices(IServiceCollection services)
{
    // With default settings
    services.AddXeroServices(options => {
        options.ClientId = "YOUR_CLIENT_ID";
        options.ClientSecret = "YOUR_CLIENT_SECRET";
    });

    // With custom settings
    services.AddXeroServices(
        // Configure Xero API credentials
        options => {
            options.ClientId = "YOUR_CLIENT_ID";
            options.ClientSecret = "YOUR_CLIENT_SECRET";
        },
        // Configure token caching (default is true)
        useTokenCaching: true,
        // Configure retry policy
        configureRetryPolicy: options => {
            options.MaxRetryAttempts = 5;                // Default: 3
            options.InitialDelayMilliseconds = 2000;     // Default: 1000
            options.DelayFactor = 1.5;                   // Default: 2.0
            options.MaxDelayMilliseconds = 60000;        // Default: 30000
            options.UseJitter = true;                    // Default: true
        });
}

2. Use the IXeroRepository in your code

using Tildom.Libraries.Xero.Interfaces;
using Tildom.Libraries.Xero.Queries;

public class YourService
{
    private readonly IXeroRepository _xeroRepository;

    public YourService(IXeroRepository xeroRepository)
    {
        _xeroRepository = xeroRepository;
    }

    public async Task<List<Invoice>> GetInvoicesAsync(string tenantId)
    {
        var query = new XeroApiQueryBuilder
        {
            XeroTenantId = tenantId,
            Where = "Status=='AUTHORISED'",
            Order = "Date DESC"
        };

        return await _xeroRepository.GetInvoicesAsync(query);
    }
}

Available Methods

The library provides access to the following Xero data entities:

Invoices

  • GetInvoicesAsync - Get a list of invoices
  • GetInvoiceAsync - Get a specific invoice by ID

Credit Notes

  • GetCreditNotesAsync - Get a list of credit notes
  • GetCreditNoteAsync - Get a specific credit note by ID

Accounts

  • GetAccountsAsync - Get a list of accounts
  • GetAccountAsync - Get a specific account by ID

Bank Transactions

  • GetBankTransactionsAsync - Get a list of bank transactions
  • GetBankTransactionAsync - Get a specific bank transaction by ID

Bank Transfers

  • GetBankTransfersAsync - Get a list of bank transfers
  • GetBankTransferAsync - Get a specific bank transfer by ID

Contacts

  • GetContactsAsync - Get a list of contacts
  • GetContactAsync - Get a specific contact by ID

Items

  • GetItemsAsync - Get a list of items
  • GetItemAsync - Get a specific item by ID

Manual Journals

  • GetManualJournalsAsync - Get a list of manual journals
  • GetManualJournalAsync - Get a specific manual journal by ID

Payments

  • GetPaymentsAsync - Get a list of payments
  • GetPaymentAsync - Get a specific payment by ID

Tracking Categories

  • GetTrackingCategoriesAsync - Get a list of tracking categories

Tax Rates

  • GetTaxRatesAsync - Get a list of tax rates

Organizations

  • GetOrganizationsAsync - Get a list of organizations

Currencies

  • GetCurrenciesAsync - Get a list of currencies

Journals

  • GetJournalsAsync - Get a list of journals
  • GetJournalAsync - Get a specific journal by ID

Reports

  • GetReportProfitAndLossAsync - Get a profit and loss report
  • GetReportBalanceSheetAsync - Get a balance sheet report

Token Caching

By default, the library uses token caching to improve performance. This means that it will only request a new token from Xero when the current token expires. This reduces the number of API calls and improves performance.

How it works

  1. When a token is requested, the library first checks if there's a valid token in the cache
  2. If a valid token exists, it returns it immediately
  3. If no valid token exists or the token has expired, it requests a new token from Xero
  4. The new token is cached for future use

Controlling token caching

You can control token caching behavior when registering the services:

// Enable token caching (default)
services.AddXeroServices(options => {
    options.ClientId = "YOUR_CLIENT_ID";
    options.ClientSecret = "YOUR_CLIENT_SECRET";
}, useTokenCaching: true);

// Disable token caching
services.AddXeroServices(options => {
    options.ClientId = "YOUR_CLIENT_ID";
    options.ClientSecret = "YOUR_CLIENT_SECRET";
}, useTokenCaching: false);

Manually managing the token cache

You can also manually manage the token cache using the IXeroTokenProvider interface:

public class YourService
{
    private readonly IXeroTokenProvider _tokenProvider;

    public YourService(IXeroTokenProvider tokenProvider)
    {
        _tokenProvider = tokenProvider;
    }

    public async Task DoSomethingAsync()
    {
        // Force a token refresh
        var token = await _tokenProvider.RefreshTokenAsync();

        // Clear the token cache
        _tokenProvider.ClearTokenCache();
    }
}

Retry Logic

The library includes built-in retry logic to handle transient failures when communicating with the Xero API. This makes your application more resilient to temporary network issues, rate limiting, and other transient errors.

How it works

  1. When an API call fails with a retryable error (e.g., rate limiting, server error, network issue), the library will automatically retry the operation
  2. Retries use exponential backoff with jitter to prevent multiple clients from retrying simultaneously
  3. The number of retries, delay between retries, and other parameters are configurable

Retryable errors

The following types of errors will trigger a retry:

  • HTTP status codes: 408 (Request Timeout), 429 (Too Many Requests), 500, 502, 503, 504 (Server Errors)
  • Network-related exceptions: TimeoutException, SocketException, IOException
  • Xero-specific exceptions: XeroUnauthorizedException, XeroRateLimitException, XeroServerErrorException

Rate Limiting

The library includes built-in rate limiting to prevent hitting Xero API rate limits. This ensures that your application doesn't exceed the allowed number of requests per minute and handles rate limiting responses gracefully.

How it works

  1. The library tracks the number of requests made to each Xero tenant
  2. Before making a request, it checks if the request would exceed the rate limit
  3. If the rate limit would be exceeded, the request is delayed until it's safe to proceed
  4. If a rate limit response is received from the API, the library automatically adjusts its internal rate limits

Features

  • Per-tenant rate limiting to respect Xero's per-organization limits
  • Global concurrent request limiting to prevent overwhelming the API
  • Automatic rate limit adjustment based on API responses
  • Configurable buffer to stay safely under the actual rate limits

Configuring retry policy and rate limits

You can configure both the retry policy and rate limits when registering the services:

services.AddXeroServices(
    options => {
        options.ClientId = "YOUR_CLIENT_ID";
        options.ClientSecret = "YOUR_CLIENT_SECRET";
    },
    useTokenCaching: true,
    configureRetryPolicy: options => {
        options.MaxRetryAttempts = 5;                // Maximum number of retry attempts (default: 3)
        options.InitialDelayMilliseconds = 2000;     // Initial delay between retries in ms (default: 1000)
        options.DelayFactor = 1.5;                   // Factor by which delay increases (default: 2.0)
        options.MaxDelayMilliseconds = 60000;        // Maximum delay between retries in ms (default: 30000)
        options.UseJitter = true;                    // Add randomness to delay to prevent thundering herd (default: true)
        options.RetryableStatusCodes = new[] { 408, 429, 500, 502, 503, 504 }; // HTTP status codes that trigger retry
    },
    configureRateLimits: options => {
        options.RequestsPerMinute = 60;              // Maximum requests per minute (default: 60)
        options.MaxConcurrentRequests = 10;          // Maximum concurrent requests (default: 10)
        options.DefaultRetryAfterMs = 2000;          // Default wait time when rate limited (default: 2000)
        options.AutoAdjustRateLimits = true;         // Automatically adjust rate limits based on API responses (default: true)
        options.RateLimitBufferPercentage = 20;      // Buffer percentage to apply to rate limits (default: 20)
    });

License

This project is licensed under the MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
9.0.0 241 4/9/2025
8.0.2-alpha 143 3/29/2025