### Install HostTracker SDK Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/llms.txt Add the HostTracker package to your .NET project using the dotnet CLI. ```bash dotnet add package HostTracker.Sdk ``` -------------------------------- ### SDK Operations Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Examples of invoking operations via the SDK client. ```APIDOC ## SDK Operations ### Description Operations are grouped by API family. Methods are named after their operationId. Paged GET operations have a corresponding POST body-query twin for complex filters. ### Request Example ```csharp // List monitors with specific state and expansion await client.Monitors.ListMonitorAsync(state: new[] { MonitorStates.Down }, expand: new[] { "lastIncident" }); // Create a new contact await client.Contacts.CreateContactAsync(new ContactWriteRequest { Type = ContactTypes.Email, Address = "ops@example.com" }); // Test a webhook await client.Webhooks.TestWebhookAsync(webhookId); ``` ``` -------------------------------- ### Build and test the solution Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Standard commands for building and testing the SDK solution in Release configuration. ```bash dotnet build HostTracker.Sdk.sln -c Release dotnet test HostTracker.Sdk.sln -c Release ``` -------------------------------- ### Initialize and Use HostTracker Client Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/llms.txt Demonstrates client initialization, listing monitors, creating a new monitor, running an on-demand check, and verifying webhook signatures. ```csharp using HostTracker.Sdk; using HostTracker.Sdk.Generated; using var client = new HostTrackerClient(Environment.GetEnvironmentVariable("HT_TOKEN")); // 1. List monitors. var page = await client.Monitors.ListMonitorAsync(limit: 50); foreach (var m in page.Data) Console.WriteLine($"{m.Name,-30} {m.State} since {UnixTime.ToDateTimeOffset(m.Since):u}"); // 2. Create one. var created = await client.Monitors.CreateMonitorAsync(new MonitorWriteRequest { Type = MonitorTypes.Http, Url = "https://example.com", Name = "Marketing site", Interval = 5, Locations = new MonitorLocations { Pools = new[] { "allworld" } }, }); // 3. Run an on-demand check and wait for the verdict. var result = await client.RunCheckAsync(new IcCreateRequest { Url = "https://example.com", Type = "http" }); // 4. Verify a webhook delivery, in your endpoint, on the RAW bytes. var verdict = WebhookSignature.Verify(request.Headers, rawBody, secrets: new[] { webhookSecret }); verdict.EnsureValid(); var evt = WebhookEvent.Parse(rawBody); ``` -------------------------------- ### HostTrackerClient Configuration Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md How to initialize the HostTrackerClient with custom options. ```APIDOC ## Configuration ### Description Initialize the HostTrackerClient using the HostTrackerOptions class. The client is thread-safe and should be registered as a singleton. ### Request Example ```csharp using var client = new HostTrackerClient(new HostTrackerOptions { Token = "…", BaseUrl = "https://api2.host-tracker.com", Timeout = TimeSpan.FromSeconds(30), MaxRetries = 2, MaxRetryDelay = TimeSpan.FromSeconds(60), Idempotency = IdempotencyMode.Auto, UserAgentSuffix = "acme-deploy/2.1", Handler = new HttpClientHandler { Proxy = myProxy }, }); ``` ``` -------------------------------- ### Initialize HostTrackerClient Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Configure the client with options such as authentication tokens, base URLs, and retry policies. The client is thread-safe and should be registered as a singleton. ```csharp using var client = new HostTrackerClient(new HostTrackerOptions { Token = "…", // omit for the anonymous reference tier BaseUrl = "https://api2.host-tracker.com", // default Timeout = TimeSpan.FromSeconds(30), // PER ATTEMPT, not per call MaxRetries = 2, MaxRetryDelay = TimeSpan.FromSeconds(60), Idempotency = IdempotencyMode.Auto, UserAgentSuffix = "acme-deploy/2.1", Handler = new HttpClientHandler { Proxy = myProxy }, }); ``` -------------------------------- ### Run live smoke tests Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Execute live smoke tests by providing the base URL and token file path. ```bash HT_BASE_URL=https://api2.host-tracker.com HT_TOKEN_FILE=/path/to/token \ dotnet test -c Release --filter "Category=Live" ``` -------------------------------- ### Regenerate the SDK client Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Use these commands to regenerate the client code from the OpenAPI specification. ```bash ./scripts/regen.sh # from the public openapi repo HT_SPEC=/path/to/openapi-3.0.json ./scripts/regen.sh # from a local document ``` -------------------------------- ### CreateMonitorAsync Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/llms.txt Creates a new monitor for tracking uptime or other metrics. ```APIDOC ## CreateMonitorAsync ### Description Creates a new monitor instance. ### Method POST ### Request Body - **Type** (MonitorTypes) - Required - The type of monitor (e.g., Http). - **Url** (string) - Required - The URL to monitor. - **Name** (string) - Required - A descriptive name for the monitor. - **Interval** (int) - Required - The check interval in minutes. - **Locations** (MonitorLocations) - Required - Configuration for monitoring locations. ``` -------------------------------- ### Handle HostTrackerException Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Use the IsCode method to branch logic based on specific problem codes rather than relying solely on HTTP status codes. ```csharp try { await client.Monitors.CreateMonitorAsync(request); } catch (HostTrackerException ex) when (ex.IsCode(ProblemCodes.DuplicateMonitor)) { var existing = ex.Errors.FirstOrDefault()?.Extensions["existingId"].GetString(); } catch (HostTrackerException ex) when (ex.IsCode(ProblemCodes.QuotaExceeded)) { // The allowance is spent - wait for the reset or upgrade. Retrying changes nothing. } catch (HostTrackerException ex) { Console.Error.WriteLine($"{ex.StatusCode} {ex.Code}: {ex.Detail} (request {ex.RequestId})"); foreach (var e in ex.Errors) Console.Error.WriteLine($" {e.Pointer}: {e.Reason}"); } ``` -------------------------------- ### Run an Instant Check Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Executes an instant check and polls the result until completion. The SDK automatically handles the polling logic based on the server's response. ```csharp var result = await client.RunCheckAsync( new IcCreateRequest { Url = "https://example.com", Type = "http", Pools = new[] { "allworld" } }, new RunCheckOptions { OnPoll = r => Console.WriteLine($"{r.Events?.Count ?? 0} reports so far") }); ``` -------------------------------- ### ListMonitorsAsync Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/llms.txt Retrieves a paginated list of monitors configured in the account. ```APIDOC ## ListMonitorsAsync ### Description Retrieves a list of monitors with optional pagination. ### Method GET ### Parameters #### Query Parameters - **limit** (int) - Optional - The number of items to return per page. ``` -------------------------------- ### Manage Bulk Jobs Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Handle bulk mutations by waiting for job completion and processing results. Check for partial success states to identify failed items. ```csharp var accepted = await client.BulkCreateMonitorAsync(request); var job = await client.WaitForJobAsync(accepted.JobId); if (JobStateInfo.IsPartial(job.State)) // partial is a SUCCESS with some failed items { await foreach (var item in client.JobResultsAsync(accepted.JobId)) if (item.Status == JobItemStatuses.Failed) Console.WriteLine($"row {item.Index}: {item.Error}"); } ``` -------------------------------- ### RunCheckAsync Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/llms.txt Executes an on-demand instant check for a specific URL. ```APIDOC ## RunCheckAsync ### Description Performs an immediate check on the provided URL. ### Method POST ### Request Body - **Url** (string) - Required - The URL to check. - **Type** (string) - Required - The type of check to perform. ``` -------------------------------- ### client.WaitForJobAsync Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Polls for the completion of an asynchronous bulk mutation job. ```APIDOC ## client.WaitForJobAsync(jobId) ### Description Polls the status of a bulk mutation job until it reaches a terminal state (succeeded, partial, failed, or cancelled). ### Method SDK Method ### Parameters - **jobId** (string) - Required - The unique identifier of the job to track. ### Response - **JobStateInfo** - The final state of the job. ``` -------------------------------- ### Execute API Operations Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Perform operations grouped by API family, such as listing monitors, creating contacts, or testing webhooks. ```csharp await client.Monitors.ListMonitorAsync(state: new[] { MonitorStates.Down }, expand: new[] { "lastIncident" }); await client.Contacts.CreateContactAsync(new ContactWriteRequest { Type = ContactTypes.Email, Address = "ops@example.com" }); await client.Webhooks.TestWebhookAsync(webhookId); ``` -------------------------------- ### Pagination.PaginateAsync Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Helper method to iterate through cursor-paginated list endpoints automatically. ```APIDOC ## Pagination.PaginateAsync(func) ### Description Handles cursor-based pagination for list endpoints, yielding items until no more data is available. ### Method SDK Method ### Parameters - **func** (Func>) - Required - A delegate that calls the API method with a cursor and cancellation token. ### Response - **IAsyncEnumerable** - An asynchronous stream of items retrieved across all pages. ``` -------------------------------- ### Paginate API Results Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Iterate through cursor-paginated lists using the Pagination helper. Do not modify or parse the opaque cursor strings. ```csharp await foreach (var monitor in Pagination.PaginateAsync( (cursor, ct) => client.Monitors.ListMonitorAsync(limit: 200, cursor: cursor, cancellationToken: ct))) { Console.WriteLine(monitor.Url); } ``` -------------------------------- ### Convert Unix Timestamps Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Use the UnixTime utility to convert between Unix seconds and DateTimeOffset objects. ```csharp DateTimeOffset since = UnixTime.ToDateTimeOffset(monitor.Since); long from = UnixTime.FromDateTimeOffset(DateTimeOffset.UtcNow.AddDays(-7)); ``` -------------------------------- ### Send Raw JSON Requests Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Use SendJsonAsync as an escape hatch to send arbitrary JSON payloads, such as explicit null values, when the typed SDK surface is insufficient. ```csharp await client.SendJsonAsync(HttpMethod.Patch, "/account", new Dictionary { ["defaultAgentPools"] = null }); ``` -------------------------------- ### Provide Explicit Idempotency Key Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Override the default auto-generated idempotency key by passing a custom key to write operations. ```csharp await client.Monitors.BulkCreateMonitorAsync(request, idempotency_Key: myOwnKey); ``` -------------------------------- ### Verify Webhook Signatures Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Verifies incoming webhook requests using raw request bytes to ensure signature integrity. Supports secret rotation by accepting multiple secrets. ```csharp app.MapPost("/hooks/hosttracker", async (HttpRequest req) => { using var buffer = new MemoryStream(); await req.Body.CopyToAsync(buffer); var rawBody = buffer.ToArray(); var verdict = WebhookSignature.Verify( req.Headers.Select(h => new KeyValuePair>(h.Key, h.Value!)), rawBody, secrets: new[] { currentSecret, previousSecret }); // both, while a rotation is in flight if (!verdict.IsValid) return Results.Unauthorized(); var evt = WebhookEvent.Parse(rawBody); if (!seen.Add(evt.Id)) return Results.Ok(); // HT-Delivery is stable across retries … return Results.Ok(); }); ``` -------------------------------- ### Capture Response Metadata Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Use a capture scope to access request metadata and rate limit information from API responses. ```csharp using var capture = client.CaptureResponses(); var page = await client.Monitors.ListMonitorAsync(limit: 50); var meta = capture.Last!; Console.WriteLine($"{meta.RequestId} attempts={meta.Attempts} replayed={meta.IdempotencyReplayed}"); Console.WriteLine(meta.RateLimit); // policy=account;q=1000;w=60 limit=1000 remaining=997 reset=42 ``` -------------------------------- ### Webhook Verification Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Verifies the authenticity of incoming webhooks using HT-Signature or Standard Webhooks. ```APIDOC ## WebhookSignature.Verify ### Description Verifies the signature of a raw webhook request body using provided secrets. ### Method Static Method ### Parameters - **Headers** (IEnumerable>>) - Required - The request headers. - **RawBody** (byte[]) - Required - The raw request bytes. - **Secrets** (string[]) - Required - Array of secrets for verification. ### Request Example var verdict = WebhookSignature.Verify( req.Headers.Select(h => new KeyValuePair>(h.Key, h.Value!)), rawBody, secrets: new[] { currentSecret, previousSecret }); ``` -------------------------------- ### CaptureResponses Source: https://github.com/hosttracker/hosttracker-sdk-dotnet/blob/main/README.md Captures metadata associated with the last API response, such as RequestId, attempt counts, and rate limit information. ```APIDOC ## client.CaptureResponses() ### Description Opens a capture scope to retrieve metadata from the subsequent API call, including request IDs and rate limit headers. ### Method SDK Method ### Parameters - None ### Response - **meta** (ResponseMetadata) - Object containing RequestId, Attempts, IdempotencyReplayed, and RateLimit information. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.