// Onbrix CRM C# SDK // Version: 1.0.0 // License: MIT // // Copyright (c) 2026 Onbrix // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Usage: // // var client = new OnbrixClient("crm_your_api_key", "https://your-instance.onbrix.com"); // var modules = await client.Modules.ListAsync(); // foreach (var m in modules) // Console.WriteLine(m.Name); using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using System.Web; namespace Onbrix { // ----------------------------------------------------------------------- // Exceptions // ----------------------------------------------------------------------- /// /// Base exception for all Onbrix API errors. /// Contains the HTTP status code and machine-readable error code returned by the API. /// public class OnbrixException : Exception { /// The HTTP status code from the API response. public int StatusCode { get; } /// A machine-readable error code (e.g., "UNAUTHORIZED", "NOT_FOUND"). public string? ErrorCode { get; } /// /// Creates a new OnbrixException. /// /// A human-readable description of the error. /// The HTTP status code. /// The machine-readable error code. public OnbrixException(string message, int statusCode, string? errorCode = null) : base(message) { StatusCode = statusCode; ErrorCode = errorCode; } } /// /// Thrown when the API key is missing, invalid, or expired (HTTP 401). /// public class AuthenticationException : OnbrixException { /// Creates a new AuthenticationException. public AuthenticationException(string message, string? errorCode = null) : base(message, 401, errorCode) { } } /// /// Thrown when the authenticated user lacks permission for the requested operation (HTTP 403). /// public class ForbiddenException : OnbrixException { /// Creates a new ForbiddenException. public ForbiddenException(string message, string? errorCode = null) : base(message, 403, errorCode) { } } /// /// Thrown when the requested resource does not exist (HTTP 404). /// public class NotFoundException : OnbrixException { /// Creates a new NotFoundException. public NotFoundException(string message, string? errorCode = null) : base(message, 404, errorCode) { } } /// /// Thrown when the request data fails validation (HTTP 400 or 422). /// public class ValidationException : OnbrixException { /// Creates a new ValidationException. public ValidationException(string message, int statusCode, string? errorCode = null) : base(message, statusCode, errorCode) { } } /// /// Thrown when the API rate limit has been exceeded and all retry attempts are exhausted (HTTP 429). /// public class RateLimitException : OnbrixException { /// Creates a new RateLimitException. public RateLimitException(string message, string? errorCode = null) : base(message, 429, errorCode) { } } // ----------------------------------------------------------------------- // Data models // ----------------------------------------------------------------------- /// /// Represents a CRM module (e.g., Contacts, Leads, Deals). /// public class Module { /// The unique identifier of the module. [JsonPropertyName("id")] public string Id { get; set; } = string.Empty; /// The display name of the module. [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; /// The URL-friendly identifier used in API paths. [JsonPropertyName("slug")] public string Slug { get; set; } = string.Empty; /// An optional description of the module. [JsonPropertyName("description")] public string? Description { get; set; } /// The field definitions for this module. [JsonPropertyName("fields")] public List>? Fields { get; set; } /// The timestamp when the module was created. [JsonPropertyName("created_at")] public string? CreatedAt { get; set; } /// The timestamp when the module was last updated. [JsonPropertyName("updated_at")] public string? UpdatedAt { get; set; } } /// /// Represents a single record within a module. /// public class Record { /// The unique identifier of the record. [JsonPropertyName("id")] public string Id { get; set; } = string.Empty; /// The field values of the record as key-value pairs. [JsonPropertyName("data")] public Dictionary? Data { get; set; } /// The user ID of the record creator. [JsonPropertyName("created_by")] public string? CreatedBy { get; set; } /// The user ID of the last person to update the record. [JsonPropertyName("updated_by")] public string? UpdatedBy { get; set; } /// The timestamp when the record was created. [JsonPropertyName("created_at")] public string? CreatedAt { get; set; } /// The timestamp when the record was last updated. [JsonPropertyName("updated_at")] public string? UpdatedAt { get; set; } } /// /// Pagination metadata for list responses. /// public class Meta { /// The total number of records matching the query. [JsonPropertyName("total")] public int Total { get; set; } /// The current page number (1-based). [JsonPropertyName("page")] public int Page { get; set; } /// The number of records per page. [JsonPropertyName("page_size")] public int PageSize { get; set; } /// The total number of pages available. [JsonPropertyName("total_pages")] public int TotalPages { get; set; } } /// /// A paginated list of records with metadata. /// public class ListResponse { /// The list of records on the current page. [JsonPropertyName("data")] public List Data { get; set; } = new(); /// The pagination information. [JsonPropertyName("meta")] public Meta Meta { get; set; } = new(); } /// /// The result of a delete operation. /// public class DeleteResponse { /// The identifier of the deleted record. [JsonPropertyName("id")] public string Id { get; set; } = string.Empty; /// True if the record was successfully deleted. [JsonPropertyName("deleted")] public bool Deleted { get; set; } } /// /// Configures filtering, sorting, and pagination for list requests. /// public class ListOptions { /// The page number to retrieve (1-based). Defaults to 1 if not set. public int? Page { get; set; } /// The number of records per page. Defaults to the API default if not set. public int? PageSize { get; set; } /// The field name to sort by. public string? SortBy { get; set; } /// The sort direction: "asc" or "desc". public string? SortDir { get; set; } /// A full-text search query applied across searchable fields. public string? Search { get; set; } /// A dictionary of field names to filter values. Each entry produces a filter[field]=value query parameter. public Dictionary? Filters { get; set; } } // ----------------------------------------------------------------------- // Internal JSON helpers // ----------------------------------------------------------------------- internal class ApiErrorResponse { [JsonPropertyName("error")] public string Error { get; set; } = string.Empty; [JsonPropertyName("code")] public string? Code { get; set; } } internal class SingleDataWrapper { [JsonPropertyName("data")] public T Data { get; set; } = default!; } // ----------------------------------------------------------------------- // Module resource // ----------------------------------------------------------------------- /// /// Provides methods for managing CRM modules. /// Access via . /// public class ModuleResource { private readonly OnbrixClient _client; internal ModuleResource(OnbrixClient client) => _client = client; /// /// Lists all modules available to the authenticated user. /// /// Optional cancellation token. /// A list of available modules. /// Thrown when the API key is invalid. /// Thrown when the API returns an error. public async Task> ListAsync(CancellationToken cancellationToken = default) { var json = await _client.SendRequestAsync(HttpMethod.Get, "/modules", null, cancellationToken); var wrapper = JsonSerializer.Deserialize>>(json, _client.JsonOptions) ?? throw new OnbrixException("Failed to parse modules response", 0); return wrapper.Data; } } // ----------------------------------------------------------------------- // Record resource // ----------------------------------------------------------------------- /// /// Provides methods for managing records within CRM modules. /// Access via . /// public class RecordResource { private readonly OnbrixClient _client; internal RecordResource(OnbrixClient client) => _client = client; /// /// Lists records from the specified module with optional filtering, sorting, and pagination. /// /// The module slug (e.g., "contacts", "leads"). /// Optional list options for pagination, sorting, and filtering. /// Optional cancellation token. /// A paginated list of records with metadata. public async Task ListAsync(string moduleSlug, ListOptions? options = null, CancellationToken cancellationToken = default) { var queryString = BuildQueryString(options); var path = "/" + Uri.EscapeDataString(moduleSlug) + queryString; var json = await _client.SendRequestAsync(HttpMethod.Get, path, null, cancellationToken); return JsonSerializer.Deserialize(json, _client.JsonOptions) ?? throw new OnbrixException("Failed to parse list response", 0); } /// /// Retrieves a single record by its ID from the specified module. /// /// The module slug (e.g., "contacts", "leads"). /// The unique identifier of the record. /// Optional cancellation token. /// The requested record. /// Thrown when the record does not exist. public async Task GetAsync(string moduleSlug, string recordId, CancellationToken cancellationToken = default) { var path = "/" + Uri.EscapeDataString(moduleSlug) + "/" + Uri.EscapeDataString(recordId); var json = await _client.SendRequestAsync(HttpMethod.Get, path, null, cancellationToken); var wrapper = JsonSerializer.Deserialize>(json, _client.JsonOptions) ?? throw new OnbrixException("Failed to parse record response", 0); return wrapper.Data; } /// /// Creates a new record in the specified module. /// /// The module slug (e.g., "contacts", "leads"). /// A dictionary of field names and their values. /// Optional cancellation token. /// The newly created record. /// Thrown when the data fails validation. public async Task CreateAsync(string moduleSlug, Dictionary data, CancellationToken cancellationToken = default) { var path = "/" + Uri.EscapeDataString(moduleSlug); var body = new Dictionary { { "data", data } }; var json = await _client.SendRequestAsync(HttpMethod.Post, path, body, cancellationToken); var wrapper = JsonSerializer.Deserialize>(json, _client.JsonOptions) ?? throw new OnbrixException("Failed to parse create response", 0); return wrapper.Data; } /// /// Updates an existing record in the specified module. /// Only the fields included in the data dictionary will be updated. /// /// The module slug (e.g., "contacts", "leads"). /// The unique identifier of the record to update. /// A dictionary of field names and their new values. /// Optional cancellation token. /// The updated record. /// Thrown when the record does not exist. /// Thrown when the data fails validation. public async Task UpdateAsync(string moduleSlug, string recordId, Dictionary data, CancellationToken cancellationToken = default) { var path = "/" + Uri.EscapeDataString(moduleSlug) + "/" + Uri.EscapeDataString(recordId); var body = new Dictionary { { "data", data } }; var json = await _client.SendRequestAsync(HttpMethod.Put, path, body, cancellationToken); var wrapper = JsonSerializer.Deserialize>(json, _client.JsonOptions) ?? throw new OnbrixException("Failed to parse update response", 0); return wrapper.Data; } /// /// Deletes a record by its ID from the specified module. /// /// The module slug (e.g., "contacts", "leads"). /// The unique identifier of the record to delete. /// Optional cancellation token. /// A response indicating whether the record was deleted. /// Thrown when the record does not exist. public async Task DeleteAsync(string moduleSlug, string recordId, CancellationToken cancellationToken = default) { var path = "/" + Uri.EscapeDataString(moduleSlug) + "/" + Uri.EscapeDataString(recordId); var json = await _client.SendRequestAsync(HttpMethod.Delete, path, null, cancellationToken); var wrapper = JsonSerializer.Deserialize>(json, _client.JsonOptions) ?? throw new OnbrixException("Failed to parse delete response", 0); return wrapper.Data; } /// /// Iterates over all records in the specified module, automatically paginating through results. /// Yields records one at a time using IAsyncEnumerable for memory-efficient iteration. /// /// The module slug (e.g., "contacts", "leads"). /// Optional list options. Page will be auto-incremented; do not set it manually. /// Optional cancellation token. /// An async enumerable of all records in the module. /// /// /// await foreach (var record in client.Records.ListAllAsync("contacts")) /// { /// Console.WriteLine(record.Id); /// } /// /// public async IAsyncEnumerable ListAllAsync(string moduleSlug, ListOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { var currentPage = options?.Page ?? 1; int totalPages; do { var pageOptions = new ListOptions { Page = currentPage, PageSize = options?.PageSize, SortBy = options?.SortBy, SortDir = options?.SortDir, Search = options?.Search, Filters = options?.Filters }; var response = await ListAsync(moduleSlug, pageOptions, cancellationToken); totalPages = response.Meta.TotalPages; foreach (var record in response.Data) { yield return record; } currentPage++; } while (currentPage <= totalPages); } /// /// Builds a query string from ListOptions. /// private static string BuildQueryString(ListOptions? options) { if (options == null) return string.Empty; var parts = new List(); if (options.Page.HasValue) parts.Add("page=" + options.Page.Value); if (options.PageSize.HasValue) parts.Add("page_size=" + options.PageSize.Value); if (!string.IsNullOrEmpty(options.SortBy)) parts.Add("sort_by=" + Uri.EscapeDataString(options.SortBy)); if (!string.IsNullOrEmpty(options.SortDir)) parts.Add("sort_dir=" + Uri.EscapeDataString(options.SortDir)); if (!string.IsNullOrEmpty(options.Search)) parts.Add("search=" + Uri.EscapeDataString(options.Search)); if (options.Filters != null) { foreach (var kvp in options.Filters) { parts.Add("filter[" + Uri.EscapeDataString(kvp.Key) + "]=" + Uri.EscapeDataString(kvp.Value)); } } return parts.Count > 0 ? "?" + string.Join("&", parts) : string.Empty; } } // ----------------------------------------------------------------------- // Main client // ----------------------------------------------------------------------- /// /// The Onbrix CRM API client. Provides access to modules and records through /// the and properties. /// /// /// /// var client = new OnbrixClient("crm_your_api_key", "https://your-instance.onbrix.com"); /// /// // List modules /// var modules = await client.Modules.ListAsync(); /// /// // Create a contact /// var contact = await client.Records.CreateAsync("contacts", new Dictionary<string, object> /// { /// { "first_name", "John" }, /// { "last_name", "Doe" } /// }); /// /// // Iterate all records /// await foreach (var record in client.Records.ListAllAsync("contacts")) /// { /// Console.WriteLine(record.Id); /// } /// /// /// public class OnbrixClient : IDisposable { /// The current version of the Onbrix C# SDK. public const string SdkVersion = "1.0.0"; private const string UserAgent = "onbrix-dotnet/" + SdkVersion; private const int MaxRetries = 3; private readonly string _apiKey; private readonly string _baseUrl; private readonly HttpClient _httpClient; private bool _disposed; internal JsonSerializerOptions JsonOptions { get; } = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; /// /// Provides methods for managing CRM modules. /// public ModuleResource Modules { get; } /// /// Provides methods for managing records within CRM modules. /// public RecordResource Records { get; } /// /// Creates a new Onbrix API client. /// /// The API key for authentication (must start with "crm_"). /// The base URL of the Onbrix instance (e.g., "https://your-instance.onbrix.com"). /// Thrown when apiKey or baseUrl is null or empty. public OnbrixClient(string apiKey, string baseUrl) { if (string.IsNullOrWhiteSpace(apiKey)) throw new ArgumentNullException(nameof(apiKey), "API key is required"); if (string.IsNullOrWhiteSpace(baseUrl)) throw new ArgumentNullException(nameof(baseUrl), "Base URL is required"); _apiKey = apiKey; _baseUrl = baseUrl.TrimEnd('/'); _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; _httpClient.DefaultRequestHeaders.Add("X-API-Key", _apiKey); _httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Modules = new ModuleResource(this); Records = new RecordResource(this); } /// /// Sends an HTTP request to the Onbrix API with automatic retry on rate limiting. /// internal async Task SendRequestAsync(HttpMethod method, string path, object? body, CancellationToken cancellationToken) { var url = _baseUrl + "/api/v1" + path; var attempt = 0; while (true) { using var request = new HttpRequestMessage(method, url); if (body != null) { var jsonContent = JsonSerializer.Serialize(body, JsonOptions); request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); } var response = await _httpClient.SendAsync(request, cancellationToken); var responseBody = await response.Content.ReadAsStringAsync(cancellationToken); // Handle rate limiting with automatic retry if (response.StatusCode == HttpStatusCode.TooManyRequests && attempt < MaxRetries) { attempt++; var delay = CalculateBackoff(response, attempt); await Task.Delay(delay, cancellationToken); continue; } if (!response.IsSuccessStatusCode) { ThrowApiException(response.StatusCode, responseBody); } return responseBody; } } /// /// Calculates the backoff duration for rate-limited request retries. /// Uses the X-RateLimit-Reset header if available; otherwise uses exponential backoff. /// private static TimeSpan CalculateBackoff(HttpResponseMessage response, int attempt) { if (response.Headers.TryGetValues("X-RateLimit-Reset", out var values)) { var resetStr = values.FirstOrDefault(); if (resetStr != null && long.TryParse(resetStr, out var resetUnix)) { var resetTime = DateTimeOffset.FromUnixTimeSeconds(resetUnix); var wait = resetTime - DateTimeOffset.UtcNow; if (wait > TimeSpan.Zero) return wait; } } // Exponential backoff: 1s, 2s, 4s return TimeSpan.FromSeconds(Math.Pow(2, attempt - 1)); } /// /// Parses an error response body and throws the appropriate typed exception. /// private static void ThrowApiException(HttpStatusCode statusCode, string responseBody) { string message; string? errorCode = null; try { var errorResponse = JsonSerializer.Deserialize(responseBody); message = errorResponse?.Error ?? $"HTTP {(int)statusCode}: {statusCode}"; errorCode = errorResponse?.Code; } catch { message = $"HTTP {(int)statusCode}: {statusCode}"; } throw statusCode switch { HttpStatusCode.Unauthorized => new AuthenticationException(message, errorCode), HttpStatusCode.Forbidden => new ForbiddenException(message, errorCode), HttpStatusCode.NotFound => new NotFoundException(message, errorCode), HttpStatusCode.TooManyRequests => new RateLimitException(message, errorCode), HttpStatusCode.BadRequest => new ValidationException(message, (int)statusCode, errorCode), HttpStatusCode.UnprocessableEntity => new ValidationException(message, (int)statusCode, errorCode), _ => new OnbrixException(message, (int)statusCode, errorCode) }; } /// /// Verifies the HMAC-SHA256 signature of an incoming webhook payload. /// The signature should be in the format "sha256={hex_digest}" as received /// in the X-Webhook-Signature header. /// /// The raw JSON request body as a string. /// The signature from the X-Webhook-Signature header (e.g., "sha256=abc123..."). /// The webhook endpoint's signing secret. /// True if the signature is valid, false otherwise. /// /// /// var body = await new StreamReader(Request.Body).ReadToEndAsync(); /// var signature = Request.Headers["X-Webhook-Signature"].ToString(); /// if (!OnbrixClient.VerifyWebhookSignature(body, signature, "your_webhook_secret")) /// { /// return Unauthorized(); /// } /// /// public static bool VerifyWebhookSignature(string payload, string signature, string secret) { if (string.IsNullOrEmpty(payload) || string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(secret)) return false; if (!signature.StartsWith("sha256=")) return false; var receivedHex = signature.Substring("sha256=".Length); using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); var computedHex = BitConverter.ToString(computedHash).Replace("-", "").ToLowerInvariant(); // Constant-time comparison to prevent timing attacks if (receivedHex.Length != computedHex.Length) return false; var result = 0; for (var i = 0; i < computedHex.Length; i++) { result |= receivedHex[i] ^ computedHex[i]; } return result == 0; } /// /// Disposes the underlying HttpClient. /// public void Dispose() { if (!_disposed) { _httpClient.Dispose(); _disposed = true; } GC.SuppressFinalize(this); } } }