vendredi 9 juin 2023

fonction FindHiggs (fixed bug)

 en C#, vous travaillez comme stagaire dans un centre de recherche effectuant des expériences avec un accelerateur de particules. Vous devez trouver les deux particules qui pourraient etre des bosons de Higgs, parmi toutes celles resultant d'une collision. Ces particules sont fournies sous la forme d'une liste de coordonnées [x,y]. Vos grandes connaissances scientifiques vous laissent supposer qu'un boson de Higgs est un particule amicale, qui essaie toujours d'etre aussi proche que possible d'un autre boson de Higgs. Vous devez donc trouver les deux particules ayant la plus petite distance euclidienne entre elles, et renvoyer leur deux index. 

Ecrit fonction public static List<int> FindHiggs(List<List<int>> particules). 

Contraints: 

les coordonnees des particules sont des entiers; 

il n'y aura jamais deux paires de particules differentes ayant la meme distance minimale; 

il y a au moins 2 particules et au plus 20000 particules; 

La paire de particules la plus proche sera toujours distante d'au plus 1000 unité; 

pour tout carre de taille 1000x1000 , il y a au plus 100 particules dans ce carre. compte tenu de ces contraintes, vous ne devriez pas calculer toues les distance entre toutes les particules, car cela prendrait trop de temps. Il pourrait etre judicieux de les indexer en utilisant un quadrillage.




public static List<int> FindHiggs(List<List<int>> particles) 

{

    var grid = new Dictionary<(int, int), List<(int index, int x, int y)>>();


    for (int i = 0; i < particles.Count; i++)

    {

        var particle = particles[i];

        int x = particle[0];

        int y = particle[1];            

        int cellX = x / 1000;

        int cellY = y / 1000;            


        if (!grid.ContainsKey((cellX, cellY)))

        {

            grid[(cellX, cellY)] = new List<(int, int, int)>();

        }

        grid[(cellX, cellY)].Add((i, x, y)); 

    }


    double minDistanceSquared = double.MaxValue; 

    int index1 = -1, index2 = -1;


    foreach (var cell in grid)

    {

        var (cellX, cellY) = cell.Key;

        var particlesInCell = cell.Value;


        for (int dx = -1; dx <= 1; dx++)

        {

            for (int dy = -1; dy <= 1; dy++)

            {

                var neighborCellKey = (cellX + dx, cellY + dy);

                if (grid.ContainsKey(neighborCellKey))

                {

                    var neighborParticles = grid[neighborCellKey];

                    foreach (var particle1 in particlesInCell)

                    {

                        foreach (var particle2 in neighborParticles)

                        {

                            if (particle1.index != particle2.index)

                            {

                                double distanceSquared = CalculateDistanceSquared(particle1.x, particle1.y, particle2.x, particle2.y);

                                if (distanceSquared < minDistanceSquared)

                                {

                                    minDistanceSquared = distanceSquared;

                                    index1 = particle1.index;

                                    index2 = particle2.index;

                                }

                            }

                        }

                    }

                }

            }

        }

    }


    return new List<int> { index1, index2 };

}


private static double CalculateDistanceSquared(int x1, int y1, int x2, int y2)

{

    return Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2);

}


mercredi 7 juin 2023

Docker

Docker est un outil permettant de créer, déployer et exécuter des applications dans des conteneurs.


🧱 C'est quoi un conteneur ?

Un conteneur Docker est une unité légère et portable qui contient tout ce qu’il faut pour exécuter une application :

  • Le code

  • Les dépendances (bibliothèques, runtime, etc.)

  • La configuration

  • Le système d'exploitation minimal

Contrairement aux machines virtuelles, les conteneurs partagent le noyau de l’OS et sont donc beaucoup plus légers et rapides.


🔄 À quoi sert Docker ?

  • 🧪 Faire tourner une app localement comme en production

  • 📦 Emballer votre application pour un déploiement automatisé (CI/CD)

  • 🧩 Isoler les composants d'une architecture (ex : app + base de données)

  • 🌍 Exécuter la même app sur n’importe quel système


🛠 Exemple avec une application C# (.NET)

🎯 Objectif :

Conteneuriser une application console ou Web API C# avec Docker.


📁 Structure du projet :

/MonProjet
├── Program.cs
├── MonProjet.csproj
└── Dockerfile

🧪 Exemple simple : Web API .NET 8 (C#)

Program.cs

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello depuis Docker !");
app.Run();

🐳 Dockerfile

# Étape 1 : build
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app
COPY . ./
RUN dotnet publish -c Release -o out

# Étape 2 : runtime
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
WORKDIR /app
COPY --from=build /app/out ./
ENTRYPOINT ["dotnet", "MonProjet.dll"]

📦 Commandes Docker :

  1. Construire l’image :

docker build -t mon-projet-dotnet .
  1. Lancer le conteneur :

docker run -p 8080:80 mon-projet-dotnet
  1. Tester dans le navigateur :
    http://localhost:8080


⚠️ Remarques :

  • docker-compose.yml peut être utilisé pour gérer plusieurs services (ex : app + SQL Server).

  • Docker est idéal pour les microservices .NET.


📌 Résumé

Terme Description
Docker Outil de gestion de conteneurs
Image Docker Modèle d'un conteneur (comme une recette)
Conteneur Docker Instance d'une image en cours d'exécution
Dockerfile Script qui décrit comment construire l’image
docker build/run Commandes pour compiler et exécuter


mardi 6 juin 2023

Lợi ích bất ngờ của đậu bắp - “nhân sâm xanh” Hàn Quốc

Đậu bắp là một loại thực vật có hoa được trồng rất nhiều ở nước ta. Quả đậu bắp được dùng để chế biến thành nhiều món ăn ngon, bổ dưỡng. Nhiều người không thích ăn quả đậu bắp vì tính nhớt của nó. Tuy nhiên, chất nhớt của loại quả này lại được coi là “thần dược” đối với người bị tiểu đường và có tác dụng làm sạch mỡ máu tuyệt vời.


 

Một nghiên cứu được đăng tải trên tạp chí Physiology and Molecular Biology of Plants vào năm 2015 cho hay đậu bắp được người Hàn Quốc gọi là “nhân sâm xanh”.

Vì sao đậu bắp lại được ví như “nhân sâm xanh”?

Đậu bắp là loại quả có chứa nguồn dinh dưỡng cực ấn tượng. Theo Trung tâm Dữ liệu Thực phẩm, Bộ Nông nghiệp Hoa Kỳ, trong 100g đậu bắp tươi có chứa:

 


Đậu bắp là một nguồn cung cấp dồi dào vitamin C và K1. Vitamin C là loại vitamin tan trong nước có tác dụng tăng cường chức năng miễn dịch tổng thể. Trong khi đó, vitamin K1 tan trong chất béo và có vai trò quan trọng trong việc tổng hợp các yếu tố đông máu.

Thêm vào đó, đậu bắp rất ít calo và carb nhưng lại chứa nhiều chất xơ và chất đạm. Bổ sung đủ chất đạm có lợi cho việc kiểm soát cân nặng, đường huyết, giúp xương chắc khỏe và hình thành khối cơ. Có rất ít rau củ, trái cây có chứa chất đạm.

Quả đậu bắp xào ăn như các loại đậu khác hoặc nướng ăn sống như dưa chuột. Quả non cũng có thể phơi khô để dùng dần là món ăn khá ngon. Lá non cũng dùng luộc, xào, nấu ăn.

Trong đậu bắp có chứa nhiều protein, glucid, hydrat carbon (tinh bột, đường, palmitin và stearin). Hạt chứa chất dầu lỏng màu vàng xanh, có mùi dễ chịu, tính hoạt nhuận, có thể ăn được.

Đậu bắp là loại thực phẩm chứa đa dạng các vitamin và khoáng chất như chất xơ, vitamin C, vitamin A, vitamin B1, B3, B6, canxi, vitamin K, magie, folate, mangan... Do đó, chỉ cần bạn bổ sung đậu bắp vào thực đơn thường xuyên sẽ mang đến nhiều lợi ích cho sức khỏe như sau:

Ngăn ngừa táo bón

Lượng chất xơ vô cùng dồi dào trong đậu bắp giúp ngăn ngừa cũng như hỗ trợ điều trị táo bón vô cùng hiệu quả. Chính thành phần chất xơ này có tác dụng thúc đẩy quá trình tiêu hóa diễn ra thuận lợi hơn. Ngoài ra, chất nhầy có trong đậu bắp còn giúp kích thích nhu động ruột, làm mềm phân, nhuận tràng nên cũng rất tốt cho những người có nguy cơ bị táo bón cao.

Làm đẹp da

Hàm lượng vitamin C và K trong đậu bắp giúp bảo vệ làn da sáng màu và tươi trẻ hơn. Ăn đậu bắp nhiều sẽ giúp thúc đẩy quá trình hình thành collagen đồng thời phục hồi các vùng da bị hư hại nên cũng mang lại cho bạn làn da mịn màng, trẻ trung và khỏe mạnh hơn.


 

Hỗ trợ giảm cân

Đậu bắp nhiều chất xơ nên sẽ giúp bạn nhanh no và no lâu. Từ đó bạn sẽ hạn chế ăn các loại thực phẩm khác đặc biệt là ít ăn vặt hơn nên hỗ trợ giảm cân hiệu quả. Đặc biệt, đậu bắp chứa rất ít calo nên cho dù bạn ăn nhiều cũng không lo vấn đề tăng cân.

Do đó, thêm đậu bắp vào thực đơn thường xuyên đồng thời hạn chế các loại thực phẩm nhiều chất béo khác cũng là cách giúp giảm cân như ý muốn.

Hỗ trợ tiêu hóa

Chất nhầy và chất xơ trong đậu bắp khi vào hệ tiêu hóa sẽ trở thành môi trường vô cùng lý tưởng cho các vi sinh vật có lợi trong đường ruột sinh sôi nhiều hơn. Khả năng hỗ trợ tiêu hóa của đậu bắp có thể sánh ngang bằng với sữa chua. Do đó, ăn đậu bắp thường xuyên cũng là cách giúp cho hệ tiêu hóa khỏe mạnh, chống rối loạn tiêu hóa cũng như hạn chế kích ứng đường ruột...

Tốt cho xương khớp

Nhờ có chứa canxi, vitamin K và axit folic nên đậu bắp sẽ giúp cải thiện quá trình trao đổi chất ở các khớp xương từ đó giúp xương chắc khỏe, giảm tình trạng mất xương hoặc loãng xương nghiêm trọng.

Ngoài ra, chất nhầy có trong đậu bắp cũng giúp bổ sung độ nhờn cho các khớp xương giúp các khớp xương hoạt động linh hoạt và giảm đau nhức khớp hiệu quả.


 

Hạn chế bệnh tim mạch

Chất nhầy trong đậu bắp có tác dụng làm giảm hàm lượng cholesterol xấu trong máu nên rất tốt cho những người bị huyết áp cao. Nhờ có khả năng ổn định huyết áp nên đậu bắp cũng có hiệu quả trong việc ngăn ngừa và hạn chế các biến chứng nguy hiểm của bệnh tim mạch. Do đó, ăn đậu bắp thường xuyên cũng là cách tăng cường sức khỏe tim mạch vô cùng hiệu quả bạn nhé.

Ổn định lượng đường trong máu

Chính hàm lượng chất xơ cao có trong đậu bắp có tác dụng làm chậm quá trình hấp thu đường trong máu, từ đó giúp ổn định đường huyết hiệu quả. Do đó, mặc dù không phải là bài thuốc trị dứt điểm tiểu đường nhưng việc ăn đậu bắp thường xuyên cũng có hiệu quả cao trong việc ngăn ngừa tiểu đường và hạn chế biến chứng nguy hiểm do tiểu đường gây ra.


 

 

 

 

lundi 5 juin 2023

Share cách chơi 18+ cho Youtube

 

Share cách chơi 18+ mà e từng chơi: kiểu 18+ của em nó không theo key để các cụ spam hàng loạt nên yên tâm không bị die khi up lên , mà em chơi theo kiểu tên phim.

Nguồn (vi du):

+ Koreanz.com.au vào phần 19+ trên thanh menu
+ cat3movie.us

– Về đặt tittle: ở đây là tên phim nên có cả tiếng anh và tiếng hàn. nhưng em thường bỏ phần tiếng anh đi, chơi mình tiếng Hàn cho nó đỡ die. vì nhiều phim có tieu đề tiếng anh up phát chết luôn
+ ví dụ phim Naughty Girlfriend 2017 – 야한 여친 2017 (ya-han yeo-chin) thì e vứt toàn bộ tittle tiếng Anh, để lại mình tiếng hàn và thêm tên diễn viên vào sau nó sẽ thành thế này : 야한 여친 2017 (ya-han yeo-chin) – Park Bum-soo (박범수) Cast Ji Oh (지오), Ye Da (예다), Jae Hoon (재훈) . 

đấy các bác cứ bê nguyên vào là đc

– về video thì các bác tốt nhất nên cắt hết cảnh nóng đi. đừng để làm gì cả. có để hay k thì cũng thế. để thì die nhanh hơn

– Mô tả: các bác copy tittle 1 cái ném xuống và nhét thêm cái link video vào nữa là được

– Tag thì cứ tiêu đề tách ra rồi cho vào là xong

– Thumbnail cái này làm không cẩn thận là tắt kiếm tiền video. Các bác lấy luôn thumbnail của nó rồi cho vào Photoshop kéo làm 3 phần như dưới ảnh là xanh lè mọi thể loại.

– Còn làm sao tránh tối đa khi up video chết luôn, thì em toàn chơi kênh dính 1 gậy cộng đồng sẵn rồi. Up video lên để riêng tư, xóa kênh đi 2 ngày sau khôi phục lại sau đó thêm Tittle. Mô Tả, tag và thumbnail vào , và các bác nên đặt lịch. Lịch pub đẹp nhất là 8h sáng và 5-6h chiều.

– Khi mới pub ra nó ăn view tìm kiếm khá nhiều sau 1 time thì ăn đề xuất, mà 1 kênh các bác nên up 2 – 3 video thôi đừng spam nhiều. 8h sáng 1 cái 5h chiều 1 cái là đẹp. khi view lên tương tối thì các bác vào ẩn like với dislike và chăn cmt đi là okie.

– Về tiền bạc và RPM thì cái này rpm cũng rơi vào khoảng 0.5 – 0.6 nên kiếm cũng ok chứ không hề ít

– Đấy ngày trước em làm là thế và kiếm đều đều. giờ em cũng quẩy lại, share cho mọi người làm để đẩy view nhanh hơn. vì giờ mấy cái này ít người làm quá không móc đâu ra đề xuất cả :v :v :v

samedi 3 juin 2023

Mega Link 157 2024

=== Scroll down & Wait &  Click on CONTINUE x/x for Mega link in 2 minutes ===

=== Cuộn xuống & Chờ & Click vào CONTINUE x/x để lấy link  chỉ 2 phút ===

All Mega Links 

#ydepdeploihayhay

#ydepdeploihayhay

Only 2 minutes

===============

Chỉ 2 phút thôi

===============

========

Tổng cộng chi mất khoảng 2 phút là sẽ có link tới Mega.

Chờ một chút để trang web load xong, sau đó kéo xuống dưới, tìm nút Continue/Enjoy, dẫn đến bước tiếp theo. 



In total, it only takes about 2 minutes to have the link to Mega.

Wait a moment for the website to load, then scroll down to find the Continue/Enjoy button, leading to the next step.


Au total, il ne faut que 2 minutes environ pour avoir le lien vers Mega.

Attendez un moment que le site Web se charge, puis faites défiler vers le bas pour trouver le bouton Continuer/Profiter, menant à l'étape suivante.


===============

=======================

=======================

All Mega Links

vendredi 2 juin 2023

Try youtube embeded

HTML : Youtube Videos embed

 Need to know Youtube Video ID (pyYgqK-do7g)

Using an <iframe> element in your web page html.

Use src attribute point to the youtube video link.

Use the width and height attributes to specify the dimension of the player.

We can make the video autoplay when vister visite webpage with more attributes in video link.

Use mute=1 after autoplay=1 to let your video start playing automatically and muted.

Exemple:

<iframe width="420" height="315"
src="https://www.youtube.com/embed/
pyYgqK-do7g?autoplay=1&mute=1">
</iframe>
 
 
With Playlist, we can add loop=1 for the video loop forever. 
Exemple:
 
<iframe width="420" height="315"
src="https://www.youtube.com/embed/pyYgqK-do7g&list=PLLcbeR0n_YwRI0Y_tR-FxbIleZW2r8oc9
&loop=1">
</iframe>
 


jeudi 1 juin 2023

Exemple Docker

Docker et de comment l’utiliser avec C# / .NET dans un projet concret.  

Concepts, création d’image, utilisation de Docker avec un projet C#, déploiement local, et outils.


🐳 1. Qu’est-ce que Docker ? (détaillé)

Docker est une plateforme de virtualisation légère qui permet de :

  • Emballer une application + son environnement dans un conteneur.

  • Exécuter ce conteneur partout où Docker est installé (Windows, Linux, macOS, Cloud).

  • Éviter le classique problème : “Ça marche chez moi mais pas sur le serveur”.

⚠️ Contrairement à une machine virtuelle, un conteneur partage le noyau de l'OS, ce qui le rend rapide et léger.


📦 2. Composants Docker

Élément Rôle
Image Une image Docker est une photographie immuable de l’environnement
Conteneur Une instance exécutable d’une image
Dockerfile Fichier qui décrit comment construire une image
Docker Hub Registre public d’images Docker
Volumes Permettent de stocker les données en dehors du conteneur

🧪 3. Exemple : Créer et exécuter une API C# .NET dans Docker

🧰 Prérequis


🧱 Étape 1 : Créer un projet Web API C#

dotnet new webapi -n MonApiDocker
cd MonApiDocker

Vous avez maintenant un projet avec un contrôleur de test.


🐳 Étape 2 : Ajouter un fichier Dockerfile

À la racine du projet, créez un fichier nommé Dockerfile (sans extension) :

# Étape 1 : build
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app

# Étape 2 : runtime
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "MonApiDocker.dll"]

Ce Dockerfile crée une image multi-étape (build + runtime) pour optimiser la taille finale.


🧪 Étape 3 : Construire l’image Docker

Depuis le dossier du projet (où se trouve le Dockerfile) :

docker build -t monapi-docker .

🚀 Étape 4 : Lancer le conteneur localement

docker run -d -p 5000:80 --name monapi monapi-docker

Cela mappe :

  • Le port interne 80 du conteneur

  • Au port 5000 de votre machine locale

Test dans le navigateur :

http://localhost:5000/weatherforecast

🧪 4. Ajouter SQL Server à votre conteneur (via Docker Compose)

Si vous voulez connecter votre API .NET à une base de données SQL Server dans Docker, vous pouvez utiliser Docker Compose :

🔧 docker-compose.yml

version: '3.4'

services:
  api:
    build: .
    ports:
      - "5000:80"
    depends_on:
      - db
    environment:
      - ConnectionStrings__Default=Server=db;Database=MaDb;User=sa;Password=Pa$$w0rd;

  db:
    image: mcr.microsoft.com/mssql/server:2022-latest
    environment:
      SA_PASSWORD: "Pa$$w0rd"
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"

Puis lancez :

docker-compose up --build

🔍 5. Inspecter et déboguer

Action Commande
Voir les conteneurs actifs docker ps
Voir les logs docker logs monapi
Entrer dans le conteneur docker exec -it monapi /bin/bash
Supprimer un conteneur docker rm monapi
Supprimer une image docker rmi monapi-docker

📌 6. Avantages de Docker avec C#/.NET

  • ✔️ Déploiement reproductible

  • ✔️ Facilité de test et CI/CD

  • ✔️ Environnement isolé (lib versions, config…)

  • ✔️ Compatible avec Azure, AWS, Kubernetes


🔚 Résumé

Étapes Action
1 Créer projet C# .NET
2 Ajouter Dockerfile
3 Construire avec docker build
4 Lancer avec docker run
5 (Optionnel) Ajouter une base SQL avec docker-compose

=========================================================

==========================================================

Un projet complet .NET Web API avec Docker + SQL Server, prêt à être exécuté avec Docker Compose.


🧱 Objectif :

Créer une Web API C# .NET 8, connectée à une base SQL Server, le tout conteneurisé avec Docker et orchestré avec Docker Compose.


📁 Structure du projet final :

/MonApiDocker/
├── Controllers/
│   └── ClientsController.cs
├── Models/
│   └── Client.cs
├── Data/
│   └── AppDbContext.cs
├── Program.cs
├── MonApiDocker.csproj
├── Dockerfile
├── docker-compose.yml
└── appsettings.json

✅ Étape 1 : Créer le projet API

dotnet new webapi -n MonApiDocker
cd MonApiDocker

✏️ Étape 2 : Ajouter les modèles et DbContext

📄 Models/Client.cs

namespace MonApiDocker.Models;

public class Client
{
    public int Id { get; set; }
    public string Nom { get; set; } = "";
    public string Email { get; set; } = "";
}

📄 Data/AppDbContext.cs

using Microsoft.EntityFrameworkCore;
using MonApiDocker.Models;

namespace MonApiDocker.Data;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<Client> Clients => Set<Client>();
}

🎮 Étape 3 : Ajouter un contrôleur simple

📄 Controllers/ClientsController.cs

using Microsoft.AspNetCore.Mvc;
using MonApiDocker.Data;
using MonApiDocker.Models;

namespace MonApiDocker.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ClientsController : ControllerBase
{
    private readonly AppDbContext _db;

    public ClientsController(AppDbContext db) => _db = db;

    [HttpGet]
    public IActionResult Get() => Ok(_db.Clients.ToList());

    [HttpPost]
    public IActionResult Post(Client client)
    {
        _db.Clients.Add(client);
        _db.SaveChanges();
        return CreatedAtAction(nameof(Get), new { id = client.Id }, client);
    }
}

🧠 Étape 4 : Modifier Program.cs

using Microsoft.EntityFrameworkCore;
using MonApiDocker.Data;

var builder = WebApplication.CreateBuilder(args);

// Ajouter EF Core SQL Server
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

builder.Services.AddControllers();
var app = builder.Build();

app.MapControllers();

// Créer la base automatiquement (migration auto)
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.Migrate();

app.Run();

🧾 Étape 5 : appsettings.json

{
  "ConnectionStrings": {
    "Default": "Server=db;Database=ClientsDb;User=sa;Password=Pa$$w0rd;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

🐳 Étape 6 : Dockerfile

# Build .NET app
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app
COPY . .
RUN dotnet restore
RUN dotnet publish -c Release -o out

# Runtime image
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/out .
ENTRYPOINT ["dotnet", "MonApiDocker.dll"]

🐋 Étape 7 : docker-compose.yml

version: '3.4'

services:
  api:
    build: .
    ports:
      - "5000:80"
    depends_on:
      - db
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    networks:
      - monreseau

  db:
    image: mcr.microsoft.com/mssql/server:2022-latest
    environment:
      SA_PASSWORD: "Pa$$w0rd"
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"
    networks:
      - monreseau

networks:
  monreseau:

📦 Étape 8 : Ajouter les packages NuGet

Dans le terminal :

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design

▶️ Étape 9 : Lancer le tout

docker-compose up --build

Accédez à :
📫 http://localhost:5000/api/clients


🧪 Tester avec Postman / Curl

Ajouter un client :

curl -X POST http://localhost:5000/api/clients \
  -H "Content-Type: application/json" \
  -d '{"nom": "Alice", "email": "alice@example.com"}'

🔚 Résultat :

  • Une API C# .NET dans Docker

  • Une base SQL Server aussi dans Docker

  • L’ensemble connecté automatiquement avec Docker Compose

  • Base de données créée automatiquement via EF Core



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.