jeudi 1 juin 2023

exemple concret en C# .NET d’un flux d’intégration

exemple concret en C# .NET d’un flux d’intégration qui extrait des données d’une base de données (SQL Server) et les envoie vers une API REST.


🎯 Objectif du flux :

Lire les nouveaux clients depuis une base SQL Server, les convertir en JSON, et les envoyer en HTTP POST à une API REST externe.


🧱 Technologies utilisées :

  • .NET 8 / .NET 6

  • Dapper (ou SqlClient) pour l’accès base de données

  • HttpClient pour l’appel REST

  • JSON (System.Text.Json) pour la sérialisation


✅ Exemple complet

using System.Data.SqlClient;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Dapper;

public class Client
{
    public int Id { get; set; }
    public string Nom { get; set; }
    public string Email { get; set; }
    public bool Synced { get; set; }
}

public class IntegrationService
{
    private readonly string _connectionString = "Server=localhost;Database=MaBase;Trusted_Connection=True;";
    private readonly string _apiUrl = "https://api.externe.com/clients";

    public async Task RunAsync()
    {
        using var connection = new SqlConnection(_connectionString);
        var clients = await connection.QueryAsync<Client>("SELECT * FROM Clients WHERE Synced = 0");

        using var httpClient = new HttpClient();

        foreach (var client in clients)
        {
            var json = JsonSerializer.Serialize(client);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await httpClient.PostAsync(_apiUrl, content);

            if (response.IsSuccessStatusCode)
            {
                await connection.ExecuteAsync("UPDATE Clients SET Synced = 1 WHERE Id = @Id", new { client.Id });
            }
            else
            {
                Console.WriteLine($"Erreur pour le client {client.Id} : {response.StatusCode}");
            }
        }
    }
}

🛠️ Utilisation dans une application console .NET :

static async Task Main(string[] args)
{
    var service = new IntegrationService();
    await service.RunAsync();
}

⏰ Pour l’exécuter régulièrement :

  • Option 1 : Créer une tâche Windows (Task Scheduler)

  • Option 2 : Lancer le flux toutes les minutes via un Timer C#

  • Option 3 : Héberger dans un service Windows ou une app worker (Worker Service)


🧠 Bonus : Ajouter la gestion des erreurs

Avec try/catch, log, ou outils comme Serilog ou NLog.


Aucun commentaire:

Enregistrer un commentaire