### Install Idoklad SDK Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/README.md Install the Idoklad SDK package using the .NET CLI. ```bash dotnet add package IdokladSdk ``` -------------------------------- ### Install iDoklad SDK via NuGet Source: https://github.com/solitea/idokladsdk/blob/master/README.md Use the .NET CLI to add the IdokladSdk package to your project. ```cmd > dotnet add package IdokladSdk ``` -------------------------------- ### Basic API Setup Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/README.md Set up and authenticate the DokladApi instance using client credentials. This is the initial step before making any API calls. ```csharp // Create HttpClient var httpClient = new HttpClient(); // Build API instance var api = new DokladApiBuilder("MyApp", "1.0.0") .AddHttpClient(httpClient) .AddClientCredentialsAuthentication("client-id", "client-secret", "app-id") .Build(); // Use it! var contacts = await api.ContactClient.List().GetAsync(); ``` -------------------------------- ### DokladApiBuilder Usage Example Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Demonstrates how to use the DokladApiBuilder to create a configured DokladApi instance with client credentials authentication and specific API context options. ```csharp var httpClient = new HttpClient(); var api = new DokladApiBuilder("MyApp", "1.0.0") .AddHttpClient(httpClient) .AddClientCredentialsAuthentication("client-id", "client-secret", "app-id") .AddApiContextOptions(o => o.Language = Language.Cz) .Build(); ``` -------------------------------- ### Log Levels Example Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/errors.md Demonstrates the usage of different log levels for various scenarios, from detailed debugging information to critical service failures. ```csharp // Debug — detailed request/response _logger.LogDebug($"API request: {method} {resource}"); _logger.LogDebug($"Response: {statusCode} {responseSize} bytes"); // Warning — partial failures, rate limits _logger.LogWarning($"Batch partial success: {failureCount}/{totalCount}"); _logger.LogWarning("Rate limited — implementing backoff"); // Error — API failures, authentication issues _logger.LogError($"API Error: {result.StatusCode} {result.Message}"); _logger.LogError($"Auth failed: {ex.AuthenticationError?.Error}"); // Critical — service unavailable, cascading failures _logger.LogCritical("iDoklad API is unavailable"); ``` -------------------------------- ### Error Handling Example Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Demonstrates how to use try-catch blocks to handle the different Idoklad SDK exceptions gracefully. ```APIDOC ## Error Handling Example ### Description This example shows how to catch and process `IdokladSdkException`, `IdokladValidationException`, and `IdokladAuthenticationException`. ### Code Example ```csharp try { var contact = (await api.ContactClient.Detail(999).GetAsync()).CheckResult(); } catch (IdokladSdkException ex) { // Handle API error logger.LogError($"API failed: {ex.ApiResult?.Message}"); logger.LogError($"Status: {ex.ApiResult?.StatusCode}"); } catch (IdokladValidationException ex) { // Handle validation error foreach (var prop in ex.InvalidProperties) { logger.LogError($"Invalid {prop.Key}: {prop.Value.Name}"); } } catch (IdokladAuthenticationException ex) { // Handle authentication failure logger.LogError($"Auth failed: {ex.AuthenticationError?.Error}"); } ``` ``` -------------------------------- ### Configure and Add HttpClient using IHttpClientFactory Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Provides an example of configuring an HttpClient using IHttpClientFactory and then adding it to the DokladApiBuilder. Ensure the HttpClient is configured with appropriate timeouts and does not have BaseAddress set. ```csharp // In Startup/Program.cs: services.AddHttpClient("IdokladApi", client => { client.Timeout = TimeSpan.FromSeconds(30); client.DefaultRequestHeaders.ConnectionClose = false; }); // In your code: var httpClient = httpClientFactory.CreateClient("IdokladApi"); var builder = new DokladApiBuilder("MyApp", "1.0.0") .AddHttpClient(httpClient); ``` -------------------------------- ### Build DokladApi with Validation Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Examples demonstrating how `DokladApiBuilder.Build()` enforces validation rules. Incorrect configurations for AppName or HttpClient will throw exceptions. ```csharp var api = new DokladApiBuilder("", "1.0") // Invalid .AddHttpClient(httpClient) .Build(); // Throws ArgumentNullException ``` ```csharp var api = new DokladApiBuilder("App", "1.0") .AddHttpClient(null) // Invalid .Build(); // Throws IdokladSdkException ``` -------------------------------- ### Create a New Contact Entity Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Example of creating a new contact by providing a `ContactPostModel` and sending it via the `PostAsync` method. ```csharp var newContact = new ContactPostModel { CompanyName = "Tech Corp", Email = "info@techcorp.com", CountryId = 1, // ... other properties }; var result = await api.ContactClient.PostAsync(newContact); var created = result.CheckResult(); Console.WriteLine($"Created: ID {created.Id}"); ``` -------------------------------- ### Idoklad SDK Error Handling Example Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Demonstrates how to catch and handle IdokladSdkException, IdokladValidationException, and IdokladAuthenticationException in a try-catch block. ```csharp try { var contact = (await api.ContactClient.Detail(999).GetAsync()).CheckResult(); } catch (IdokladSdkException ex) { // Handle API error logger.LogError($"API failed: {ex.ApiResult?.Message}"); logger.LogError($"Status: {ex.ApiResult?.StatusCode}"); } catch (IdokladValidationException ex) { // Handle validation error foreach (var prop in ex.InvalidProperties) { logger.LogError($"Invalid {prop.Key}: {prop.Value.Name}"); } } catch (IdokladAuthenticationException ex) { // Handle authentication failure logger.LogError($"Auth failed: {ex.AuthenticationError?.Error}"); } ``` -------------------------------- ### Retrieve Default Model for New Entity Creation Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Example of fetching a default `ContactPostModel` template to pre-fill properties before creating a new contact. ```csharp // Get template for new contact var result = await api.ContactClient.DefaultAsync(); var template = result.CheckResult(); // Use as starting point var newContact = new ContactPostModel { CountryId = template.CountryId, // Pre-filled Email = "newcustomer@example.com" }; ``` -------------------------------- ### Development/Staging Environment Configuration Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Configure the iDoklad API client for development or staging environments. This example shows how to use custom API and identity server URLs for non-production environments. ```csharp public static DokladApi CreateStagingApi( IHttpClientFactory httpClientFactory, IConfiguration config) { var isDevelopment = config["Environment"] == "Development"; var httpClient = httpClientFactory.CreateClient("IdokladApi"); var builder = new DokladApiBuilder("TestApp", "0.0.1") .AddHttpClient(httpClient); // Use staging/development endpoints if (isDevelopment) { builder.AddCustomApiUrls( apiUrl: "https://api-staging.idoklad.cz/", identityServerUrl: "https://identity-staging.idoklad.cz/" ); } return builder .AddClientCredentialsAuthentication( clientId: config["Staging:ClientId"], clientSecret: config["Staging:ClientSecret"], applicationId: "StagingTest" ) .AddApiContextOptions(opts => { opts.ApiResultHandler = (result) => { Console.WriteLine($"[STAGING] {result.StatusCode} - {result.Message}"); }; }) .Build(); } ``` -------------------------------- ### ASP.NET Core Dependency Injection Setup Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/README.md Configure the HttpClient and DokladApi client for dependency injection in ASP.NET Core applications. Ensure required configuration values like App:Name, App:Version, IdokladApi:ClientId, and IdokladApi:ClientSecret are set. ```csharp // Program.cs / Startup.cs services.AddHttpClient("IdokladApi", client => { client.Timeout = TimeSpan.FromSeconds(30); }); services.AddSingleton(provider => { var factory = provider.GetRequiredService(); var config = provider.GetRequiredService(); var httpClient = factory.CreateClient("IdokladApi"); return new DokladApiBuilder(config["App:Name"], config["App:Version"]) .AddHttpClient(httpClient) .AddClientCredentialsAuthentication( config["IdokladApi:ClientId"], config["IdokladApi:ClientSecret"], "MyApp" ) .Build(); }); // Inject in services public class InvoiceService { public InvoiceService(DokladApi api) { _api = api; } } ``` -------------------------------- ### Server Application with Client Credentials Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Configure the iDoklad API client for a server application using client credentials. This example shows how to set up the API client with authentication and custom result handling. ```csharp public class DokladApiService { private readonly DokladApi _api; public DokladApiService(IHttpClientFactory httpClientFactory, IConfiguration config) { var httpClient = httpClientFactory.CreateClient("IdokladApi"); _api = new DokladApiBuilder( config["App:Name"], config["App:Version"] ) .AddHttpClient(httpClient) .AddClientCredentialsAuthentication( clientId: config["IdokladApi:ClientId"], clientSecret: config["IdokladApi:ClientSecret"], applicationId: "MyServerApp" ) .AddApiContextOptions(opts => { opts.Language = Language.Cz; opts.ApiResultHandler = (result) => { if (!result.IsSuccess) { // Custom logging or alerting Telemetry.LogApiError(result); } }; }) .Build(); } public async Task> GetAllContactsAsync() { var result = await _api.ContactClient.List().GetAsync(); return result.CheckResult().Items; } } // Startup configuration: services.AddHttpClient("IdokladApi", client => { client.Timeout = TimeSpan.FromSeconds(30); }); services.AddSingleton(); ``` -------------------------------- ### Reuse DokladApi Instance Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Illustrates the correct approach of reusing a single DokladApi instance throughout the application's lifetime to avoid performance overhead. The 'Bad' example shows a wasteful pattern of creating new instances per call. ```csharp // Good — single instance for application lifetime public class InvoiceService { private readonly DokladApi _api; public InvoiceService(DokladApi api) { _api = api; // Injected, reused } } // Bad — creates new instance per call public async Task GetInvoice(int id) { var api = new DokladApiBuilder(...).Build(); // Wasteful return await api.IssuedInvoiceClient.Detail(id).GetAsync(); } ``` -------------------------------- ### Chain Filters Efficiently on Server Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Shows how to apply multiple filters to a list request, ensuring that filtering is performed on the server-side for better performance. The 'Bad' example demonstrates inefficient in-memory filtering after fetching all data. ```csharp // Good — filters applied on server var contacts = api.ContactClient .List() .Filter(c => c.CompanyName.Contains("Tech")) .Filter(c => c.Country.Id == 1) .PageSize(100) .GetAsync(); // Bad — fetches all, filters in memory var allContacts = api.ContactClient.List().GetAsync(); var filtered = allContacts.Items .Where(c => c.CompanyName.Contains("Tech")) .ToList(); ``` -------------------------------- ### ApiBatchResult Usage Examples Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Illustrates how to process batch operation results by checking the Status property and using CheckResult() with or without the acceptPartialSuccess flag. ```csharp var models = new List { /* ... */ }; var batchResult = await api.BatchClient.UpdateAsync(models); // Check status before processing if (batchResult.Status == BatchResultType.Success) { var results = batchResult.CheckResult(); } else if (batchResult.Status == BatchResultType.PartialSuccess) { var results = batchResult.CheckResult(acceptPartialSuccess: true); } ``` -------------------------------- ### ApiResult Usage Examples Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Demonstrates two common approaches for handling API responses: checking the IsSuccess property or using the CheckResult() method to retrieve data or throw an exception. ```csharp var result = await api.ContactClient.Detail(123).GetAsync(); // Approach 1: Check IsSuccess if (result.IsSuccess) { var contact = result.Data; } // Approach 2: Use CheckResult() var contact = result.CheckResult(); ``` -------------------------------- ### Web Application with Authorization Code Flow Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Configure the iDoklad API client for a web application using the authorization code flow. This example includes logic for refreshing tokens and handling unauthorized responses. ```csharp public class IdokladUserService { private readonly IHttpClientFactory _httpClientFactory; private readonly IUserRepository _userRepository; public async Task GetUserApiAsync(int userId) { var user = await _userRepository.GetAsync(userId); // Get or refresh stored refresh token var refreshToken = user.IdokladRefreshToken; if (DateTime.UtcNow.AddDays(7) > user.IdokladTokenExpiresAt) { refreshToken = await RefreshTokenAsync(user); } var httpClient = _httpClientFactory.CreateClient("IdokladApi"); var api = new DokladApiBuilder("MyWebApp", "3.0.0") .AddHttpClient(httpClient) .AddAuthorizationCodeAuthentication( clientId: "web-app-client-id", clientSecret: "web-app-client-secret", refreshToken: refreshToken ) .AddApiContextOptions(opts => { opts.Language = user.PreferredLanguage; opts.ApiResultHandler = (result) => { if (result.StatusCode == System.Net.HttpStatusCode.Unauthorized) { // Token invalid — trigger re-authentication Events.Publish(new UserAuthExpired(userId)); } }; }) .Build(); return api; } private async Task RefreshTokenAsync(User user) { // Token refresh logic var newToken = await _api.GetTokenAsync(); user.IdokladRefreshToken = newToken; user.IdokladTokenExpiresAt = DateTime.UtcNow.AddHours(1); await _userRepository.UpdateAsync(user); return newToken.AccessToken; } } // Startup: services.AddHttpClient("IdokladApi"); services.AddScoped(); ``` -------------------------------- ### Define Default Operation Interface Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Defines the interface for retrieving a default or template model, typically used as a starting point for creating new entities. ```csharp public interface IDefaultRequest { Task> DefaultAsync(CancellationToken cancellationToken = default); } ``` -------------------------------- ### Initialize DokladApi with Chained Configuration Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Demonstrates the fluent builder pattern for initializing a DokladApi instance with essential configurations including application identity, HTTP client, and authentication. ```csharp var api = new DokladApiBuilder("AppName", "1.0.0") .AddHttpClient(httpClient) .AddClientCredentialsAuthentication("id", "secret", "app-id") .AddApiContextOptions(opts => opts.Language = Language.En) .Build(); ``` -------------------------------- ### Create DokladApiBuilder with Application Identity Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Shows how to instantiate the DokladApiBuilder, providing the application name and version, which are sent in the User-Agent and X-App headers. ```csharp var builder = new DokladApiBuilder(string appName, string appVersion); ``` ```csharp var builder = new DokladApiBuilder("MyInvoiceApp", "2.1.0"); ``` -------------------------------- ### Initialize DokladConfiguration Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Instantiate DokladConfiguration using default production endpoints or provide custom URLs for staging or development environments. ```csharp // Production (default) var config = new DokladConfiguration(); // Custom endpoint var config = new DokladConfiguration( "https://api-staging.idoklad.cz/", "https://identity-staging.idoklad.cz/" ); ``` -------------------------------- ### Authenticate and Initialize API Source: https://github.com/solitea/idokladsdk/blob/master/README.md Configure the DokladApi using client credentials and an HttpClient instance. ```csharp // Create HttpClient instance var httpClient = httpClientFactory.CreateClient("IdokladApi"); // Use DokladApiBuilder to create DokladApi. var api = new DokladApiBuilder("your application name", "your application version") .AddClientCredentialsAuthentication("ClientId", "ClientSecret") .AddHttpClient(httpClient) .Build(); ``` -------------------------------- ### HttpClient Configuration with Direct Instantiation Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Configures HttpClient by directly instantiating it and setting a timeout. Default headers like User-Agent can also be set. This HttpClient is then passed to the DokladApiBuilder. ```csharp var httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) }; // Set default headers if needed httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0"); var api = new DokladApiBuilder("MyApp", "1.0.0") .AddHttpClient(httpClient) // ... .Build(); ``` -------------------------------- ### Configure DokladApi Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/INDEX.md Demonstrates the fluent builder pattern for configuring the DokladApi instance with application details, HTTP client, and authentication. This is required before using the API. ```csharp var api = new DokladApiBuilder("MyApp", "1.0.0") .AddHttpClient(httpClient) .AddClientCredentialsAuthentication("id", "secret", "app-id") .Build(); ``` -------------------------------- ### DokladConfiguration Constructors Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Details on how to instantiate and configure the DokladConfiguration, including default production and custom endpoints. ```APIDOC ## DokladConfiguration() ### Description Initializes DokladConfiguration with default production endpoints. ### Method `DokladConfiguration()` ### Parameters None ### Response #### Success Response - **DokladConfiguration** ### Example ```csharp var config = new DokladConfiguration(); ``` ## DokladConfiguration(string apiUrl, string identityServerUrl) ### Description Initializes DokladConfiguration with custom API and Identity Server URLs. ### Method `DokladConfiguration(string apiUrl, string identityServerUrl)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **apiUrl** (string) - Required - Base URL of iDoklad API (must be absolute URI) - **identityServerUrl** (string) - Required - Base URL of Identity server (must be absolute URI) ### Response #### Success Response - **DokladConfiguration** ### Example ```csharp var config = new DokladConfiguration("https://api-staging.idoklad.cz/", "https://identity-staging.idoklad.cz/"); ``` ``` -------------------------------- ### Instantiate and Use DokladApi Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Demonstrates how to instantiate the DokladApi class with an ApiContext and access an API client, such as IssuedInvoiceClient, to retrieve data. ```csharp var api = new DokladApi(apiContext); var issuedInvoiceResult = await api.IssuedInvoiceClient.Detail(123456).GetAsync(); var issuedInvoice = issuedInvoiceResult.Data; ``` -------------------------------- ### Default Operations Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Retrieve a default or template object for creating new entities. The `IDefaultRequest` interface is useful for pre-populating forms or providing a starting point for new records. ```APIDOC ## Default Operations ### Description Retrieve default/template for creating new entities. ### Interface `IDefaultRequest` ### Supported Methods - `DefaultAsync(CancellationToken cancellationToken = default)` — Execute retrieval ### Usage Example ```csharp // Get template for new contact var result = await api.ContactClient.DefaultAsync(); var template = result.CheckResult(); // Use as starting point var newContact = new ContactPostModel { CountryId = template.CountryId, // Pre-filled Email = "newcustomer@example.com" }; ``` ``` -------------------------------- ### Build API Instance Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Constructs and returns a fully configured DokladApi instance, ready for use. ```APIDOC ## Build API Instance ### Description Builds the `DokladApi` instance using the configured builder. ### Method Signature ```csharp var api = builder.Build(); ``` ### Returns - **DokladApi** - A fully configured API instance ready for use. ### Example ```csharp var api = new DokladApiBuilder("MyApp", "1.0.0") .AddHttpClient(httpClient) .AddClientCredentialsAuthentication("id", "secret", "app-id") .Build(); var contacts = await api.ContactClient.List().GetAsync(); ``` ``` -------------------------------- ### DokladApiBuilder.Build Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Constructs and returns the configured DokladApi instance. ```APIDOC ## Build ### Description Constructs and returns the configured `DokladApi` instance. ### Method POST ### Endpoint N/A ### Parameters None ### Request Example ```csharp var api = new DokladApiBuilder("MyApp", "1.0.0").Build(); ``` ### Response #### Success Response (200) Returns a configured `DokladApi` instance. #### Response Example ```json { "apiInstance": "DokladApi" } ``` ``` -------------------------------- ### Get Single Contact with Includes Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/README.md Retrieve a single contact's details along with related data like bank information or country details. Use the Include method to specify related entities. ```csharp var contact = await api.ContactClient .Detail(123) .Include(c => c.Bank) .Include(c => c.Country.Currency) .GetAsync(); var data = contact.CheckResult(); Console.WriteLine($"{data.CompanyName} ({data.Country?.Name})"); ``` -------------------------------- ### Minimal Idoklad API Configuration Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md This snippet shows the absolute minimum configuration required to initialize the DokladApi. It uses default settings for endpoints, language, error handling, and timeouts. ```csharp var httpClient = new HttpClient(); var api = new DokladApiBuilder("MinimalApp", "1.0.0") .AddHttpClient(httpClient) .AddClientCredentialsAuthentication("id", "secret", "app-id") .Build(); ``` -------------------------------- ### Get Contact Detail with Selector and Includes Source: https://github.com/solitea/idokladsdk/blob/master/README.md Fetch detailed contact information, including related entities like Bank and Country. The selector function transforms the returned data, reducing transferred data by specifying only required properties. Nested objects used in the selector must be included using the Include method. ```csharp var detail = api.ContactClient .Detail(contactId) .Include(c => c.Bank, c => c.Country.Currency) .Get(c => new { CompanyName = c.CompanyName.ToUpper(CultureInfo.InvariantCulture), Currency = c.Country != null && c.Country.Currency != null ? c.Country.Currency.Name : string.Empty, Bank = c.Bank != null ? c.Bank.Name : string.Empty, Name = c.Firstname + " " + c.Surname, Address = $"{c.Street} {c.City} {c.PostalCode}", Discount = c.CompanyName.Length > 10 ? 10.0m : c.DiscountPercentage }); ``` -------------------------------- ### DokladApiBuilder Constructor Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Initializes a new instance of the DokladApiBuilder class with application name and version. ```APIDOC ## DokladApiBuilder Constructor ### Description Initializes a new instance of the DokladApiBuilder class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Constructor ### Endpoint N/A ### Request Example ```csharp var builder = new DokladApiBuilder("MyAppName", "1.0.0"); ``` ### Response #### Success Response (Constructor) Returns an initialized DokladApiBuilder instance. #### Response Example N/A ``` -------------------------------- ### Build API Instance Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Build the fully configured API instance using DokladApiBuilder. This instance is ready for use in making API calls. ```csharp var api = new DokladApiBuilder("MyApp", "1.0.0") .AddHttpClient(httpClient) .AddClientCredentialsAuthentication("id", "secret", "app-id") .Build(); var contacts = await api.ContactClient.List().GetAsync(); ``` -------------------------------- ### Perform Batch Update Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/INDEX.md Shows how to perform batch updates and handle potential partial successes. Use for updating multiple records efficiently. ```csharp var result = await api.BatchClient.UpdateAsync(models); var data = result.CheckResult(acceptPartialSuccess: true); ``` -------------------------------- ### Create a Contact with Idoklad SDK Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/README.md Use this snippet to create a new contact in the system. Ensure the ContactPostModel is populated with necessary details like CompanyName, Email, and CountryId. ```csharp var newContact = new ContactPostModel { CompanyName = "Acme Corp", Email = "contact@acme.com", CountryId = 1 }; var result = await api.ContactClient.PostAsync(newContact); var created = result.CheckResult(); Console.WriteLine($"Created contact ID: {created.Id}"); ``` -------------------------------- ### Handle Batch Partial Success Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Illustrates how to process the results of a batch operation, specifically handling cases where some items in the batch may have failed. It shows how to check the status and log individual failures. ```csharp var result = await api.BatchClient.UpdateAsync(models); var updated = result.CheckResult(acceptPartialSuccess: true); // Log partial failures if (result.Status == BatchResultType.PartialSuccess) { var failures = result.Results.Where(r => !r.IsSuccess); foreach (var failure in failures) { _logger.LogWarning($"Batch item failed: {failure.Message}"); } } ``` -------------------------------- ### List Countries Using CountryClient Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Demonstrates how to retrieve a list of countries using the CountryClient and iterate through the results. Ensure the API instance is properly configured. ```csharp var countries = (await api.CountryClient.List().GetAsync()).CheckResult(); foreach (var country in countries.Items) { Console.WriteLine($"{country.Code}: {country.Name}"); } ``` -------------------------------- ### DokladApiBuilder.AddCustomApiUrls Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Overrides the default API and Identity Server URLs. ```APIDOC ## AddCustomApiUrls ### Description Overrides the default API and Identity Server URLs. ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var builder = new DokladApiBuilder("MyApp", "1.0.0").AddCustomApiUrls("https://custom.api.url/", "https://custom.identity.url/"); ``` ### Response #### Success Response (200) Returns the `DokladApiBuilder` instance for chaining. #### Response Example ```json { "message": "Custom API URLs set successfully" } ``` ``` -------------------------------- ### Lazy-Loaded Clients Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/README.md Demonstrates how DokladApi clients are lazily loaded and cached upon first access, ensuring efficient resource utilization. ```csharp var api = new DokladApi(context); var client = api.ContactClient; // Created here var client2 = api.ContactClient; // Same instance reused ``` -------------------------------- ### HttpClient Configuration with Dependency Injection Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Recommended approach for configuring HttpClient using dependency injection. Sets a timeout, disables connection pooling per-request, and adds tracing headers. The HttpClient is then injected into your service. ```csharp // Program.cs / Startup.cs services.AddHttpClient("IdokladApi", client => { // Set reasonable timeout client.Timeout = TimeSpan.FromSeconds(30); // Disable connection pooling per-request client.DefaultRequestHeaders.ConnectionClose = false; // Add tracing headers client.DefaultRequestHeaders.Add("X-Request-ID", Guid.NewGuid().ToString()); }); // In your service public MyService(IHttpClientFactory factory) { var httpClient = factory.CreateClient("IdokladApi"); var api = new DokladApiBuilder("App", "1.0") .AddHttpClient(httpClient) // ... .Build(); } ``` -------------------------------- ### Handle SDK Exceptions Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/INDEX.md Illustrates how to catch and handle specific exceptions thrown by the SDK during API operations. Wrap potentially failing calls in a try-catch block. ```csharp try { var contact = (await api.ContactClient.Detail(id).GetAsync()).CheckResult(); } catch (IdokladSdkException ex) { // Handle error } ``` -------------------------------- ### Use Specific Models for Projection Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Demonstrates fetching only specific properties of an entity using projection for optimized data retrieval. Contrasts this with fetching the full entity or an unnecessarily large list. ```csharp // Good — get only needed properties via projection var result = await api.ContactClient .Detail(123) .Get(c => new { c.CompanyName, c.Email }); // Reasonable — get full entity var result = await api.ContactClient .Detail(123) .GetAsync(); // Avoid — unnecessary network traffic var result = await api.ContactClient .List() .PageSize(10000) .GetAsync(); // Too much data ``` -------------------------------- ### Define API Context Options Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/types.md Configure API behavior and result handling, including custom handlers for single and batch results, and setting the response language. ```csharp public class ApiContextOptions { public Action ApiResultHandler { get; set; } public Action ApiBatchResultHandler { get; set; } public Language? Language { get; set; } } ``` -------------------------------- ### Add HttpClient to DokladApiBuilder Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Illustrates adding a pre-configured HttpClient instance to the DokladApiBuilder. The HttpClient must not have its BaseAddress set. ```csharp builder.AddHttpClient(HttpClient httpClient); ``` -------------------------------- ### List Contacts Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/INDEX.md Demonstrates how to retrieve a list of all contacts. Use this for basic data retrieval. ```csharp var contacts = await api.ContactClient.List().GetAsync(); ``` -------------------------------- ### DokladApiBuilder.AddClientCredentialsAuthentication Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Configures authentication using OAuth 2.0 client credentials. ```APIDOC ## AddClientCredentialsAuthentication ### Description Authenticates with OAuth 2.0 client credentials. ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **clientId** (string) - Required - OAuth 2.0 Client ID. - **clientSecret** (string) - Required - OAuth 2.0 Client Secret. - **applicationId** (string) - Required - Application ID for audit trail. ### Request Example ```csharp var builder = new DokladApiBuilder("MyApp", "1.0.0").AddClientCredentialsAuthentication("client-id", "client-secret", "app-id"); ``` ### Response #### Success Response (200) Returns the `DokladApiBuilder` instance for chaining. #### Response Example ```json { "message": "Client credentials authentication configured" } ``` ``` -------------------------------- ### Configure Global API Result Handler Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/errors.md Set up a global handler for API results during application startup. This approach centralizes error handling logic for common HTTP status codes, allowing you to throw specific SDK exceptions or log warnings. ```csharp // Configure global error handling in builder builder.AddApiContextOptions(options => { options.ApiResultHandler = (result) => { switch (result.StatusCode) { case HttpStatusCode.Unauthorized: throw new IdokladAuthenticationException(result.Message); case HttpStatusCode.Forbidden: throw new IdokladAuthorizationException(result.Message); case HttpStatusCode.ServiceUnavailable: throw new IdokladUnavailableException(result.Message); case HttpStatusCode.BadRequest: // Log and continue — let caller decide _logger.LogWarning($"Bad request: {result.Message}"); break; } }; }); // Then use without try-catch for expected conditions var contact = (await api.ContactClient.Detail(id).GetAsync()).CheckResult(); ``` -------------------------------- ### DokladApiBuilder.AddApiContextOptions Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Configures API result handlers and language settings using a provided action. ```APIDOC ## AddApiContextOptions ### Description Configures API result handlers and language settings. ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (Action) - Required - Configuration action for ApiContextOptions. ### Request Example ```csharp var builder = new DokladApiBuilder("MyApp", "1.0.0").AddApiContextOptions(o => o.Language = Language.Cz); ``` ### Response #### Success Response (200) Returns the `DokladApiBuilder` instance for chaining. #### Response Example ```json { "message": "ApiContextOptions configured successfully" } ``` ``` -------------------------------- ### Perform List Operation with Filters and Sorting Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Demonstrates how to use the List operation to retrieve a paginated collection of contacts, applying filters, sorting, and pagination. ```csharp var listRequest = api.ContactClient.List() .Filter(c => c.CompanyName.Contains("Tech")) .Filter(c => c.DateLastChange.IsGreaterThan(DateTime.Now.AddDays(-30))) .Sort(c => c.CompanyName.Asc()) .PageSize(50) .Page(1); var result = await listRequest.GetAsync(); var page = result.CheckResult(); foreach (var contact in page.Items) { // Process contact } ``` -------------------------------- ### Structured Logging for API Errors Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/errors.md Shows how to use structured logging to capture detailed information about API operation failures, including exception details and contextual data. ```csharp try { var contact = (await api.ContactClient.Detail(id).GetAsync()).CheckResult(); } catch (IdokladSdkException ex) { _logger.LogError(ex, "API operation failed. " + "StatusCode={StatusCode} " + "ErrorCode={ErrorCode} " + "EntityId={EntityId} " + "Operation={Operation}", ex.ApiResult?.StatusCode, ex.ApiResult?.ErrorCode, id, "GetContact" ); } ``` -------------------------------- ### Create Operations Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Create new entities within the system. The `IPostRequest` interface handles the creation process, including client-side validation and returning the newly created entity. ```APIDOC ## Create Operations ### Description Create new entities. ### Interface `IPostRequest` ### Supported Methods - `PostAsync(TPostModel model, CancellationToken cancellationToken = default)` — Execute creation ### Usage Example ```csharp var newContact = new ContactPostModel { CompanyName = "Tech Corp", Email = "info@techcorp.com", CountryId = 1, // ... other properties }; var result = await api.ContactClient.PostAsync(newContact); var created = result.CheckResult(); Console.WriteLine($"Created: ID {created.Id}"); ``` ### Notes - Model is validated client-side before sending - Server performs additional validation - Returns full entity after creation ``` -------------------------------- ### DokladApiBuilder.AddPinAuthentication Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Configures authentication using a PIN, optionally with a refresh token. ```APIDOC ## AddPinAuthentication ### Description Authenticates using a PIN, optionally with a refresh token. ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **clientId** (string) - Required - OAuth 2.0 Client ID. - **clientSecret** (string) - Required - OAuth 2.0 Client Secret. - **pin** (string) - Optional - PIN for authentication. - **refreshToken** (string) - Optional - Refresh token for obtaining new access token. ### Request Example ```csharp var builder = new DokladApiBuilder("MyApp", "1.0.0").AddPinAuthentication("client-id", "client-secret", "1234", "refresh-token"); ``` ### Response #### Success Response (200) Returns the `DokladApiBuilder` instance for chaining. #### Response Example ```json { "message": "PIN authentication configured" } ``` ``` -------------------------------- ### Define Create Operation Interface Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Defines the interface for creating new entities, specifying the model for the request and the expected response. ```csharp public interface IPostRequest { Task> PostAsync(TPostModel model, CancellationToken cancellationToken = default); } ``` -------------------------------- ### Handle Authentication Failures Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/errors.md Demonstrates how to catch IdokladAuthenticationException during API calls, access detailed error information, and handle token-related issues. ```csharp try { var api = new DokladApiBuilder("MyApp", "1.0.0") .AddHttpClient(httpClient) .AddClientCredentialsAuthentication("bad-id", "bad-secret", "app-id") .Build(); var token = await api.ApiContext.GetTokenAsync(); } catch (IdokladAuthenticationException ex) { Console.WriteLine($"Authentication failed: {ex.Message}"); if (ex.AuthenticationError != null) { Console.WriteLine($"Error code: {ex.AuthenticationError.Error}"); Console.WriteLine($"Description: {ex.AuthenticationError.ErrorDescription}"); } } ``` ```csharp // Distinguish from other exceptions try { var result = await api.ContactClient.List().GetAsync(); } catch (IdokladAuthenticationException) { // Token invalid/expired — trigger re-authentication _authService.InvalidateSession(); } catch (IdokladSdkException ex) { // Other API error logger.LogError($"API error: {ex.Message}"); } ``` -------------------------------- ### DokladApiBuilder Class Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/COMPLETION_REPORT.txt The DokladApiBuilder class is used for configuring and building instances of the DokladApi. It offers 7 configuration methods. ```APIDOC ## DokladApiBuilder ### Description The `DokladApiBuilder` facilitates the construction and configuration of `DokladApi` instances. It allows for customization of API settings through a fluent interface. ### Methods - **7 configuration methods**: These methods allow users to set up API endpoints, authentication, context, and other essential configurations. ``` -------------------------------- ### ApiContext Methods Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Provides methods for managing API context, including token retrieval and language settings. ```APIDOC ## GetTokenAsync ### Description Obtain or refresh access token as needed. ### Method `GetTokenAsync` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response - **Task** (Task) - current valid access token ### Example ```csharp var token = await context.GetTokenAsync(); ``` ## SetLanguage ### Description Set the Accept-Language header for API responses. ### Method `SetLanguage` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **language** (Language) - Required - Language enum: Cz, Sk, En, or De ### Response #### Success Response - **void** ### Example ```csharp context.SetLanguage(Language.Cz); ``` ``` -------------------------------- ### Configure Custom HTTP Logging Handler Source: https://github.com/solitea/idokladsdk/blob/master/README.md Set up a custom logging handler for HTTP requests within the iDoklad SDK using .NET's Service Collection. This allows for custom logging logic to be integrated into the SDK's request pipeline. Refer to Microsoft's official documentation for more details on HttpLogger and Service Collection configuration. ```csharp _serviceCollection .AddHttpClient("IdokladApi") .AddLogger(wrapHandlersPipeline: true); ``` -------------------------------- ### List Entities with Filtering, Sorting, and Pagination Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Retrieve collections of entities. Supports chaining methods for filtering, sorting, and pagination. Use when you need to fetch multiple records with specific criteria. ```csharp public interface IEntityList { TList List(); } ``` ```csharp var list = api.ContactClient.List() .Filter(c => c.CompanyName.Contains("company")) .Sort(c => c.Id.Asc()) .PageSize(100) .Page(1) .GetAsync(); ``` -------------------------------- ### Configure Custom API URLs in Builder Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/types.md Set custom API and Identity Server URLs using the DokladApiBuilder. This allows directing requests to alternative endpoints, such as staging environments. ```csharp var builder = new DokladApiBuilder("MyApp", "1.0.0") .AddCustomApiUrls( "https://api-staging.idoklad.cz/", "https://identity-staging.idoklad.cz/" ); ``` -------------------------------- ### Reference Data Clients Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Clients for retrieving static and reference data such as countries, currencies, VAT rates, and payment options. ```APIDOC ## Reference Data Clients Clients for retrieving static/reference data: - **CountryClient**: Retrieves country master data. Resource: `/Countries` - **CurrencyClient**: Retrieves currency information. Resource: `/Currencies` - **BankClient**: Retrieves bank information. Resource: `/Banks` - **VatRateClient**: Retrieves VAT rate definitions. Resource: `/VatRates` - **VatCodeClient**: Retrieves VAT code mappings. Resource: `/VatCodes` - **PaymentOptionClient**: Retrieves payment method options. Resource: `/PaymentOptions` - **ConstantSymbolClient**: Retrieves constant symbols. Resource: `/ConstantSymbols` - **NumericSequenceClient**: Retrieves document numbering sequences. Resource: `/NumericSequences` - **PriceListItemClient**: Retrieves price list entries. Resource: `/PriceListItems` ``` -------------------------------- ### DokladConfiguration Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/COMPLETION_REPORT.txt DokladConfiguration is used for configuring API URLs. ```APIDOC ## DokladConfiguration ### Description The `DokladConfiguration` class holds the configuration for API endpoints, allowing users to specify custom URLs if needed. ### Properties - **API URLs**: Configuration for base API endpoints. ``` -------------------------------- ### Add Custom API URLs Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/configuration.md Override default production endpoints for development or alternative deployments. URLs must be valid, absolute URIs with trailing slashes. ```csharp builder.AddCustomApiUrls(string apiUrl, string identityServerUrl); ``` ```csharp builder.AddCustomApiUrls( apiUrl: "https://api-staging.idoklad.cz/", identityServerUrl: "https://identity-staging.idoklad.cz/" ); ``` -------------------------------- ### Retrieve Default Model with Reference ID Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/clients.md Demonstrates fetching a default model based on a specific reference ID, useful for creating entities related to existing ones, like an invoice based on a template. ```csharp var result = await api.IssuedInvoiceClient.DefaultAsync(templateId: 5); var template = result.CheckResult(); ``` -------------------------------- ### Handle Specific Exceptions with Try-Catch Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/errors.md Use a try-catch block to catch and handle specific Idoklad SDK exceptions. This pattern allows for granular control over different error types like authentication, authorization, validation, and general API errors. ```csharp try { var contact = (await api.ContactClient.Detail(id).GetAsync()).CheckResult(); } catch (IdokladAuthenticationException ex) { // Handle auth failure _authService.ResetSession(); } catch (IdokladAuthorizationException) { // Handle permission error _uiService.ShowFeatureLockedDialog(); } catch (IdokladValidationException ex) { // Handle validation error _uiService.ShowValidationErrors(ex.InvalidProperties); } catch (IdokladUnavailableException) { // Handle maintenance/unavailability _uiService.ShowMaintenanceMessage(); } catch (IdokladSdkException ex) { // Handle general API error _errorService.LogError(ex); _uiService.ShowErrorMessage(ex.Message); } ``` -------------------------------- ### DokladApiBuilder.AddAuthorizationCodeAuthentication (with refresh token) Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Configures authentication using a refresh token to obtain a new access token. ```APIDOC ## AddAuthorizationCodeAuthentication (with refresh token) ### Description Authenticates using a refresh token to obtain a new access token. ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **clientId** (string) - Required - OAuth 2.0 Client ID. - **clientSecret** (string) - Required - OAuth 2.0 Client Secret. - **refreshToken** (string) - Required - Refresh token for obtaining new access token. ### Request Example ```csharp var builder = new DokladApiBuilder("MyApp", "1.0.0").AddAuthorizationCodeAuthentication("client-id", "client-secret", "refresh-token"); ``` ### Response #### Success Response (200) Returns the `DokladApiBuilder` instance for chaining. #### Response Example ```json { "message": "Refresh token authentication configured" } ``` ``` -------------------------------- ### List Contacts with Filter Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/INDEX.md Shows how to filter contacts based on a condition, such as company name. Use when you need to retrieve a subset of contacts. ```csharp var contacts = await api.ContactClient .List() .Filter(c => c.CompanyName.Contains("Tech")) .GetAsync(); ``` -------------------------------- ### DokladApiBuilder.AddHttpClient Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/api-reference.md Adds a pre-configured HttpClient instance to the builder for making API requests. ```APIDOC ## AddHttpClient ### Description Adds a pre-configured HttpClient instance to the builder for making API requests. ### Method POST ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var httpClient = new HttpClient(); var builder = new DokladApiBuilder("MyApp", "1.0.0").AddHttpClient(httpClient); ``` ### Response #### Success Response (200) Returns the `DokladApiBuilder` instance for chaining. #### Response Example ```json { "message": "HttpClient added successfully" } ``` ``` -------------------------------- ### Handle IdokladAuthorizationException Source: https://github.com/solitea/idokladsdk/blob/master/_autodocs/errors.md Catch this exception when a user lacks the necessary permissions for an operation. Consider redirecting to an upgrade page or displaying a feature lock. ```csharp try { var issuedInvoice = (await api.IssuedInvoiceClient.Detail(123).GetAsync()).CheckResult(); } catch (IdokladAuthorizationException) { Console.WriteLine("You lack permission to view this invoice"); // Redirect to upgrade page, show feature lock, etc. } ```