> 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-docs-pt/kilo-center/kilo-mioty-service-center/integrations/api-reference/c-examples.md).

# Exemplos em C\#

Exemplos executáveis em C# para a API gRPC do KiloCenter — crie um projeto de consola, adicione Grpc.Net.Client e chame métodos.

Esta página fornece exemplos em C# executáveis para a API gRPC do KiloCenter. Para a referência completa da API, veja Referência da API.

Para documentação geral de gRPC em C#, veja [grpc.io/docs/languages/csharp](https://grpc.io/docs/languages/csharp/).

### Pré-requisitos

> Todos os comandos neste guia pressupõem que o seu diretório de trabalho é `kilocenter-modules/`.

Crie um novo projeto de consola e adicione os pacotes NuGet necessários:

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

Adicione os ficheiros proto ao seu `.csproj` para geração de código:

```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>
```

Substitua `path/to/` com o caminho real para o repositório KiloCenter. A compilação do projeto gera automaticamente stubs em C#.

### Obter estado do sistema

Recupera o estado atual do sistema, incluindo versão, tempo de atividade e saúde do serviço.

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

// Endpoint gRPC KiloCenter KC-Gateway
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($"Versão:             {resp.Version}");
Console.WriteLine($"Estado:              {resp.Status}");
Console.WriteLine($"Tempo de atividade: {resp.Uptime}");
Console.WriteLine($"Endpoints ativos:    {resp.ActiveEndpoints}");
Console.WriteLine($"Estações base ativas: {resp.ActiveBasestations}");
Console.WriteLine($"Mensagens processadas:  {resp.MessagesProcessed}");

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

### Listar pontos de extremidade

Lista os pontos de extremidade registados com suporte a paginação. Perfil de alto volume: tamanho padrão da página 100, máximo 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 de endpoints: {resp.TotalCount}");

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

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

### Autenticação

#### Edição Comunitária

A Edição Comunitária é executada em modo de inquilino único com autenticação e imposição de organização desativadas (`auth.enabled: false`, `org_enforcement_enabled: false`). Os exemplos acima funcionam sem quaisquer cabeçalhos.

#### Enterprise: Principal do utilizador JWT

Requer três cabeçalhos: `authorization`, `x-organization-id` e `x-user-id`. O `x-user-id` o valor deve corresponder ao utilizador autenticado no JWT. Em falta `x-user-id` retorna `ErrTokenUserIDHeaderRequired`; uma incompatibilidade retorna `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: Chave de API da conta de serviço

Requer dois cabeçalhos: `authorization` e `x-organization-id`. Não **não** enviar `x-user-id` — incluindo-o retorna `ErrTokenIdentityMismatch` para impedir injeção de utilizador.

```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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
