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

# Exemples C\#

Exemples C# exécutables pour l’API gRPC de KiloCenter — créez un projet console, ajoutez Grpc.Net.Client, appelez les méthodes.

Cette page fournit des exemples C# exécutables pour l’API gRPC KiloCenter. Pour la référence complète de l’API, consultez la Référence de l’API.

Pour la documentation générale sur gRPC en C#, voir [grpc.io/docs/languages/csharp](https://grpc.io/docs/languages/csharp/).

### Prérequis

> Toutes les commandes de ce guide supposent que votre répertoire de travail est `kilocenter-modules/`.

Créez un nouveau projet console et ajoutez les packages NuGet requis :

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

Ajoutez les fichiers proto à votre `.csproj` pour la génération de code :

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

Remplacez `path/to/` en remplaçant par le chemin réel vers le dépôt KiloCenter. La compilation du projet génère automatiquement les stubs C#.

### Obtenir l’état du système

Récupère l’état actuel du système, y compris la version, le temps de fonctionnement et l’état des services.

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

// Point de terminaison 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($"Version :             {resp.Version}");
Console.WriteLine($"État :              {resp.Status}");
Console.WriteLine($"Temps de fonctionnement :              {resp.Uptime}");
Console.WriteLine($"Points de terminaison actifs :    {resp.ActiveEndpoints}");
Console.WriteLine($"Stations de base actives : {resp.ActiveBasestations}");
Console.WriteLine($"Messages traités :  {resp.MessagesProcessed}");

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

### Lister les points de terminaison

Liste les points de terminaison enregistrés avec prise en charge de la pagination. Profil à volume élevé : taille de page par défaut 100, maximum 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;

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

    Console.WriteLine($"Nombre total de points de terminaison : {resp.TotalCount}");

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

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

### Authentification

#### Édition communautaire

L’Édition communautaire fonctionne en mode mono-locataire avec l’authentification et l’application des organisations désactivées (`auth.enabled: false`, `org_enforcement_enabled: false`). Les exemples ci-dessus fonctionnent sans aucun en-tête.

#### Entreprise : principal utilisateur JWT

Nécessite trois en-têtes : `authorization`, `x-organization-id`, et `x-user-id`. Le `x-user-id` La valeur doit correspondre à l’utilisateur authentifié dans le JWT. L’absence de `x-user-id` renvoie `ErrTokenUserIDHeaderRequired`; une incompatibilité renvoie `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
);
```

#### Entreprise : clé API de compte de service

Nécessite deux en-têtes : `authorization` et `x-organization-id`. Ne **pas** envoyez `x-user-id` — l’inclure renvoie `ErrTokenIdentityMismatch` pour empêcher l’injection d’utilisateur.

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