> For the complete documentation index, see [llms.txt](https://docs.kiloiot.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kiloiot.io/kilo-mioty-service-center/integrations/api-reference/c-examples.md).

# C# Examples

Runnable C# examples for the KiloCenter gRPC API — create console project, add Grpc.Net.Client, call methods.

This page provides runnable C# examples for the KiloCenter gRPC API. For the full API reference, see API Reference.

For general C# gRPC documentation, see [grpc.io/docs/languages/csharp](https://grpc.io/docs/languages/csharp/).

### Prerequisites

> All commands in this guide assume your working directory is `kilocenter-modules/`.

Create a new console project and add the required NuGet packages:

```bash
dotnet new console -n KiloCenterClient
cd KiloCenterClient
dotnet add package Grpc.Net.Client
dotnet add package Google.Protobuf
dotnet add package Grpc.Tools
```

Add the proto files to your `.csproj` for code generation:

```xml
<ItemGroup>
  <Protobuf Include="path/to/KC-Core/api/proto/kilocenter.proto"
            GrpcServices="Client"
            AdditionalImportDirs="path/to/KC-Core/api/proto" />
  <Protobuf Include="path/to/KC-Core/api/proto/core.proto"
            GrpcServices="None"
            AdditionalImportDirs="path/to/KC-Core/api/proto" />
  <Protobuf Include="path/to/KC-Core/api/proto/identity.proto"
            GrpcServices="None"
            AdditionalImportDirs="path/to/KC-Core/api/proto" />
</ItemGroup>
```

Replace `path/to/` with the actual path to the KiloCenter repository. Building the project auto-generates C# stubs.

### Get System Status

Retrieves the current system status including version, uptime, and service health.

```csharp
using Grpc.Net.Client;
using Google.Protobuf.WellKnownTypes;
using Kilocenter.Api.V1;

// KiloCenter KC-Gateway gRPC endpoint
var server = "http://localhost:9090";

using var channel = GrpcChannel.ForAddress(server);
var client = new KiloCenterService.KiloCenterServiceClient(channel);

var resp = await client.GetSystemStatusAsync(new Empty());

Console.WriteLine($"Version:             {resp.Version}");
Console.WriteLine($"Status:              {resp.Status}");
Console.WriteLine($"Uptime:              {resp.Uptime}");
Console.WriteLine($"Active Endpoints:    {resp.ActiveEndpoints}");
Console.WriteLine($"Active Base Stations: {resp.ActiveBasestations}");
Console.WriteLine($"Messages Processed:  {resp.MessagesProcessed}");

foreach (var svc in resp.Services)
{
    Console.WriteLine($"  Service: {svc.Name}  healthy={svc.Healthy}  latency={svc.LatencyMs}ms");
}
```

### List Endpoints

Lists registered endpoints with pagination support. High-volume profile: default page size 100, max 1000.

```csharp
using Grpc.Net.Client;
using Kilocenter.Api.V1;

var server = "http://localhost:9090";

using var channel = GrpcChannel.ForAddress(server);
var client = new KiloCenterService.KiloCenterServiceClient(channel);

var pageToken = "";
var pageSize = 100;

do
{
    var resp = await client.ListEndPointsAsync(new ListEndPointsRequest
    {
        PageSize = pageSize,
        PageToken = pageToken,
    });

    Console.WriteLine($"Total endpoints: {resp.TotalCount}");

    foreach (var ep in resp.Endpoints)
    {
        Console.WriteLine($"  EUI: {ep.EpEui}  Name: {ep.Name}  Status: {ep.Status}  Class: {ep.EpClass}");
    }

    pageToken = resp.NextPageToken;
}
while (!string.IsNullOrEmpty(pageToken));
```

### Authentication

#### Community Edition

Community Edition runs single-tenant with organization enforcement off, so the examples above need only the `authorization` header: sign in with `Login` and send `Bearer <access_token>`. Each call also needs a role: `GetSystemStatus` is open to every role, `ListEndPoints` to Endpoint Managers and administrators. See [User Roles and Permissions](/kilo-mioty-service-center/security/users-and-roles.md).

#### Enterprise: JWT User Principal

Requires three headers: `authorization`, `x-organization-id`, and `x-user-id`. The `x-user-id` value must match the authenticated user in the JWT. Missing `x-user-id` returns `ErrTokenUserIDHeaderRequired`; a mismatch returns `ErrTokenIdentityMismatch`.

```csharp
using Grpc.Core;

var token = "your-jwt-token";
var orgId = "your-organization-uuid";
var userId = "your-user-uuid";

var headers = new Metadata
{
    { "authorization", "Bearer " + token },
    { "x-organization-id", orgId },
    { "x-user-id", userId },
};

var resp = await client.ListEndPointsAsync(
    new ListEndPointsRequest { PageSize = 100 },
    headers
);
```

#### Enterprise: Service-Account API Key

Requires two headers: `authorization` and `x-organization-id`. Do **not** send `x-user-id` — including it returns `ErrTokenIdentityMismatch` to prevent user injection.

A service-account key acts as a Base Station Manager and Endpoint Manager in the organization it was created for, so the call below succeeds for that organization. Calls that need the Admin or Tenant Manager role, and any call for another organization, return `PERMISSION_DENIED`.

```csharp
var apiKey = "your-api-key";
var orgId = "your-organization-uuid";

var headers = new Metadata
{
    { "authorization", "Bearer " + apiKey },
    { "x-organization-id", orgId },
};

var resp = await client.ListEndPointsAsync(
    new ListEndPointsRequest { PageSize = 100 },
    headers
);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.kiloiot.io/kilo-mioty-service-center/integrations/api-reference/c-examples.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
