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

# Ejemplos en C\#

Ejemplos ejecutables en C# para la API gRPC de KiloCenter — crea un proyecto de consola, añade Grpc.Net.Client y llama a métodos.

Esta página proporciona ejemplos ejecutables en C# para la API gRPC de KiloCenter. Para la referencia completa de la API, consulte la Referencia de la API.

Para la documentación general de gRPC en C#, consulte [grpc.io/docs/languages/csharp](https://grpc.io/docs/languages/csharp/).

### Prerrequisitos

> Todos los comandos de esta guía asumen que su directorio de trabajo es `kilocenter-modules/`.

Cree un nuevo proyecto de consola y agregue los paquetes NuGet necesarios:

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

Agregue los archivos proto a su `.csproj` para la generación 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>
```

Reemplace `path/to/` con la ruta real al repositorio de KiloCenter. Compilar el proyecto genera automáticamente stubs de C#.

### Obtener estado del sistema

Recupera el estado actual del sistema, incluida la versión, el tiempo de actividad y la salud de los servicios.

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

// Punto de conexión gRPC de 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($"Versión:             {resp.Version}");
Console.WriteLine($"Estado:              {resp.Status}");
Console.WriteLine($"Tiempo de actividad: {resp.Uptime}");
Console.WriteLine($"Puntos finales activos:    {resp.ActiveEndpoints}");
Console.WriteLine($"Estaciones base activas: {resp.ActiveBasestations}");
Console.WriteLine($"Mensajes procesados:  {resp.MessagesProcessed}");

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

### Listar endpoints

Lista los endpoints registrados con compatibilidad para paginación. Perfil de alto volumen: tamaño de página predeterminado 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 puntos finales: {resp.TotalCount}");

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

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

### Autenticación

#### Community Edition

Community Edition se ejecuta en modo de inquilino único con la autenticación y la aplicación de la organización deshabilitadas (`auth.enabled: false`, `org_enforcement_enabled: false`). Los ejemplos anteriores funcionan sin ningún encabezado.

#### Enterprise: principal de usuario JWT

Requiere tres encabezados: `authorization`, `x-organization-id`, y `x-user-id`. El `x-user-id` el valor debe coincidir con el usuario autenticado en el JWT. La ausencia de `x-user-id` devuelve `ErrTokenUserIDHeaderRequired`; una discrepancia devuelve `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: clave API de cuenta de servicio

Requiere dos encabezados: `authorization` y `x-organization-id`. No **no** envíe `x-user-id` — incluirlo devuelve `ErrTokenIdentityMismatch` para evitar la inyección de usuario.

```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-es/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.
