Code Snippets

Your snippets will appear here, organized by the selected section.

Basic Git Commands

Git

Common Git commands used when starting or working with a repository.

git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin URL
git push -u origin main

Basic Docker Commands

Docker

Useful Docker commands for containers and images.

docker build -t myapp .

docker run -p 8080:80 myapp

docker ps

docker stop container_id

Hash Password with BCrypt

.NET / Security

Generate a secure password hash before saving a user.

var passwordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);

Verify Password with BCrypt

.NET / Security

Compare the entered password with the stored password hash.

var validPassword = BCrypt.Net.BCrypt.Verify(dto.Password, user.PasswordHash);

Log Warning Example

.NET / Logging

Structured logging example for failed login attempts.

_logger.LogWarning("Login failed for {Username}", dto.Username);

Swagger JWT Configuration

.NET / Swagger

Add Bearer token authentication support inside Swagger UI.

builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
    {
        Description = "Enter the JWT token like this: Bearer {token}",
        Name = "Authorization",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
        Scheme = "bearer",
        BearerFormat = "JWT"
    });

    options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

appsettings.json with Connection String and JWT

.NET / Config

Basic application configuration with logging, SQL Server connection string, and JWT settings.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=PruebaProgramadaDB;Trusted_Connection=True;TrustServerCertificate=True;"
  },
  "Jwt": {
    "Key": "XXXXXXXXXXXXXXXXXXXXXXXX",
    "Issuer": "XXXXXXXXXXXXXXXXXXXXXX",
    "Audience": "XXXXXXXXXXXXXXXXXXUsers",
    "ExpireMinutes": 60
  }
}

SQL Server CREATE TABLE

SQL

Example of creating a table in SQL Server.

CREATE TABLE Users (
    Id INT PRIMARY KEY,
    Name VARCHAR(100),
    Email VARCHAR(200)
);

Register DbContext with SQL Server

.NET / EF Core

Entity Framework Core configuration using SQL Server and a connection string from configuration.

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Foreign Key Example

SQL

Creating a table with a foreign key relationship.

CREATE TABLE Orders (
    Id INT PRIMARY KEY,
    UserId INT,
    CONSTRAINT FK_User_Order
        FOREIGN KEY (UserId)
        REFERENCES Users(Id)
);

Composite Foreign Key

SQL

Example of a composite foreign key referencing two columns.

FOREIGN KEY (StudentId, CourseId)
REFERENCES StudentCourses(StudentId, CourseId);

EF Core Composite Key and Relationships

.NET / EF Core

Fluent API example with composite key, relationships, and restricted delete behavior.

CREATE PROCEDURE GetStudents
AS
BEGIN
    SELECT Id, FullName, Email
    FROM Students;
END
GO

-- Execute the procedure
EXEC GetStudents;

Basic Linux Commands

Linux

Common Linux commands for navigation and file management.

ls
cd folder
pwd
mkdir new_folder
rm file.txt

JWT Authentication Configuration

.NET / Security

JWT bearer authentication setup with token validation parameters.

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,

        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],

        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
    };
});

builder.Services.AddAuthorization();

app.UseAuthentication();

Generate JWT Token

.NET / Security

Claims, signing key, credentials, and JWT token generation for a logged-in user.

var claims = new[]
{
    new Claim(ClaimTypes.Name, user.Username),
    new Claim(ClaimTypes.Role, user.Role)
};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]!));

var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
    issuer: _config["Jwt:Issuer"],
    audience: _config["Jwt:Audience"],
    claims: claims,
    expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(_config["Jwt:ExpireMinutes"])),
    signingCredentials: credentials
);

return new JwtSecurityTokenHandler().WriteToken(token);

ASP.NET Core API Attributes

.NET / API
[ApiController]
[Route("api/[controller]")]

[HttpDelete("{id}")]
[Authorize(Roles = "Admin")]

JavaScript Class Example

JavaScript
class Client { 
    constructor(name, balance) {
        this.name = name;
        this.balance = balance;
    }

    printBalance() {
        return `Hi ${this.name}, your balance: ${this.balance}`;
    }

    withdrawBalance(withdrawal) {
        this.balance -= withdrawal;
    }

    static welcome(){
        return `Welcome to the cashier`;
    }
}

C# Lambda and Delegates

.NET / C#
public class LambdaExample
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    // Lambda equivalent
    // (a, b) => a + b

    public delegate int Operation(int a, int b);

    public static int Sum(int a, int b)
    {
        return a + b;
    }

    public static void ExecuteFunction(int a, int b, Func operation)
    {
        int result = operation(a,b);
        Console.WriteLine($"Result: {result}");
    }
}

Flutter HTTP GET with Authorization Header

Flutter / HTTP
final response = await http.get(
  Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
  headers: {HttpHeaders.authorizationHeader: 'Basic your_api_token_here'},
);

Flutter Fetch Album Example

Flutter / HTTP
Future<Album> fetchAlbum() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: {HttpHeaders.authorizationHeader: 'Basic your_api_token_here'},
  );

  final responseJson = jsonDecode(response.body) as Map<String, dynamic>;
  return Album.fromJson(responseJson);
}

Flutter Model from JSON

Flutter / Model
class Album {
  final int userId;
  final int id;
  final String title;

  const Album({required this.userId, required this.id, required this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

Flutter Parse JSON List

Flutter / JSON
List<Photo> parsePhotos(String responseBody) {
  final parsed = (jsonDecode(responseBody) as List)
      .cast<Map<String, dynamic>>();

  return parsed.map<Photo>(Photo.fromJson).toList();
}

Flutter Fetch Photos

Flutter / HTTP
Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response = await client.get(
    Uri.parse('https://jsonplaceholder.typicode.com/photos'),
  );

  return parsePhotos(response.body);
}

Flutter Compute Isolate Example

Flutter / Performance
Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response = await client.get(
    Uri.parse('https://jsonplaceholder.typicode.com/photos'),
  );

  return compute(parsePhotos, response.body);
}

C# Class and Object

.NET / OOP

Basic example of a class, constructor, method, and object creation in C#.

public class Car
{
    public string Brand { get; set; }
    public string Model { get; set; }

    public Car(string brand, string model)
    {
        Brand = brand;
        Model = model;
    }

    public string GetInfo()
    {
        return $"{Brand} {Model}";
    }
}

var car = new Car("Toyota", "Corolla");
Console.WriteLine(car.GetInfo());

C# Properties

.NET / OOP

Auto-properties and encapsulation with validation logic in C#.

public class Product
{
    public string Name { get; set; } = string.Empty;

    private decimal _price;
    public decimal Price
    {
        get { return _price; }
        set { _price = value >= 0 ? value : 0; }
    }
}

C# Inheritance

.NET / OOP

A derived class inherits behavior from a base class.

public class Animal
{
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Woof!");
    }
}

C# Polymorphism

.NET / OOP

Method overriding allows different classes to provide different behavior.

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Generic sound");
    }
}

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow");
    }
}

Animal animal = new Cat();
animal.MakeSound();

C# Abstract Class

.NET / OOP

An abstract class defines members that derived classes must implement.

public abstract class Shape
{
    public abstract double CalculateArea();
}

public class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public override double CalculateArea()
    {
        return Width * Height;
    }
}

JavaScript Class Expression

JavaScript

Example of assigning a class to a variable.

class Client {
    constructor(name, balance) {
        this.name = name;
        this.balance = balance;
    }
}

const ClientTwo = class {
    constructor(name, balance) {
        this.name = name;
        this.balance = balance;
    }
}

const person = new ClientTwo('John', 400);
console.log(person);

PHP Class and Object

PHP / OOP

Basic example of a class, properties, methods, and object creation in PHP.

<?php
class Car
{
    public string $brand;
    public string $model;

    public function __construct(string $brand, string $model)
    {
        $this->brand = $brand;
        $this->model = $model;
    }

    public function getInfo(): string
    {
        return "{$this->brand} {$this->model}";
    }
}

$car = new Car("Toyota", "Corolla");
echo $car->getInfo();

PHP Inheritance

PHP / Inheritance

A child class inherits properties and methods from a parent class.

<?php
class Animal
{
    public function speak(): string
    {
        return "Generic animal sound";
    }
}

class Dog extends Animal
{
    public function bark(): string
    {
        return "Woof!";
    }
}

$dog = new Dog();
echo $dog->speak();
echo $dog->bark();

PHP Polymorphism

PHP / Polymorphism

Different classes can implement the same method in different ways.

<?php
class Cat
{
    public function makeSound(): string
    {
        return "Meow";
    }
}

class Bird
{
    public function makeSound(): string
    {
        return "Tweet";
    }
}

function playSound($animal): void
{
    echo $animal->makeSound();
}

playSound(new Cat());
playSound(new Bird());

PHP Abstract Class

PHP / Abstract

An abstract class defines a base structure that child classes must complete.

<?php
abstract class Shape
{
    abstract public function calculateArea(): float;
}

class Rectangle extends Shape
{
    public function __construct(
        private float $width,
        private float $height
    ) {}

    public function calculateArea(): float
    {
        return $this->width * $this->height;
    }
}

$rectangle = new Rectangle(10, 5);
echo $rectangle->calculateArea();

Node.js Basic HTTP Server

Node.js / HTTP

Simple HTTP server using the built-in Node.js http module.

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Node.js');
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

Basic Express Server

Node.js / Express

Minimal Express application with one route.

const express = require('express');

const app = express();

app.get('/', (req, res) => {
  res.json({ message: 'Welcome to the API' });
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

Read File with Node.js

Node.js / FileSystem

Reading a file using the built-in fs module.

const fs = require('fs');

fs.readFile('data.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }

  console.log(data);
});

Async/Await Example

Node.js / Async

Example of using async and await with a promise.

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function run() {
  console.log('Start');
  await delay(2000);
  console.log('Finished after 2 seconds');
}

run();

Git Branch Commands

Git
git branch

git branch feature-login

git checkout feature-login

git checkout -b feature-api

Git Pull and Push

Git
git pull origin main

git add .

git commit -m "update feature"

git push origin main

Git Clone Repository

Git
git clone https://github.com/user/repository.git

cd repository

Linux Navigation

Linux
pwd

ls

ls -la

cd folder

cd ..

Linux File Commands

Linux
touch file.txt

cp file.txt backup.txt

mv file.txt newfile.txt

rm file.txt

Linux Permissions

Linux
chmod 755 script.sh

chmod +x script.sh

chown user:user file.txt

Linux Process Commands

Linux
ps aux

top

kill -9 1234

htop

EF Core ModelBuilder (Fluent API Relationships)

.NET / EF Core

Example of configuring composite keys and relationships using Entity Framework Core Fluent API.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Enrollment>(entity =>
    {
        entity.HasKey(e => new { e.StudentId, e.CourseId });

        entity.HasOne(e => e.Student)
              .WithMany(s => s.Enrollments)
              .HasForeignKey(s => s.StudentId)
              .OnDelete(DeleteBehavior.Restrict);

        entity.HasOne(e => e.Course)
              .WithMany(c => c.Enrollments)
              .HasForeignKey(c => c.CourseId)
              .OnDelete(DeleteBehavior.Restrict);
    });

    modelBuilder.Entity<Course>(entity =>
    {
        entity.HasOne(c => c.Career)
              .WithMany(ca => ca.Courses)
              .HasForeignKey(c => c.CareerId)
              .OnDelete(DeleteBehavior.Restrict);
    });

    modelBuilder.Entity<Student>()
        .HasOne(s => s.Career)
        .WithMany(c => c.Students)
        .HasForeignKey(s => s.CareerId)
        .OnDelete(DeleteBehavior.Restrict);
}

EF Core Example Models

.NET / EF Core

Basic models used for the LINQ query examples (Student, Career, Course, Enrollment).

public class Student
{
    public int Id { get; set; }
    public string FullName { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;

    public int CareerId { get; set; }
    public Career? Career { get; set; }

    public List<Enrollment> Enrollments { get; set; } = new();
}

public class Career
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;

    public List<Student> Students { get; set; } = new();
    public List<Course> Courses { get; set; } = new();
}

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;

    public int CareerId { get; set; }
    public Career? Career { get; set; }

    public List<Enrollment> Enrollments { get; set; } = new();
}

public class Enrollment
{
    public int StudentId { get; set; }
    public Student? Student { get; set; }

    public int CourseId { get; set; }
    public Course? Course { get; set; }
}

In-Memory Sample Data

.NET / Collections
var careers = new List<Career>
{
    new Career { Id = 1, Name = "Software Engineering" },
    new Career { Id = 2, Name = "Cyber Security" }
};

var courses = new List<Course>
{
    new Course { Id = 1, Name = "Algorithms", CareerId = 1 },
    new Course { Id = 2, Name = "Databases", CareerId = 1 },
    new Course { Id = 3, Name = "Network Security", CareerId = 2 }
};

var students = new List<Student>
{
    new Student { Id = 1, FullName = "Alice Johnson", Email = "alice@gmail.com", CareerId = 1 },
    new Student { Id = 2, FullName = "Bob Smith", Email = "bob@gmail.com", CareerId = 1 },
    new Student { Id = 3, FullName = "Carol White", Email = "carol@gmail.com", CareerId = 2 }
};

LINQ Queries with EF Core

.NET / LINQ

Examples of projections, grouping, counts, and joins with Entity Framework.

// Students with their career
var studentsCareers = await _context.Students
    .Select(s => new
    {
        StudentId = s.Id,
        StudentName = s.FullName,
        CareerName = s.Career!.Name
    })
    .ToListAsync();

// Quantity of courses per student
var quantityStudentCourses = await _context.Students
    .Select(s => new
    {
        StudentName = s.FullName,
        CoursesCount = s.Enrollments.Count()
    })
    .ToListAsync();

// Courses by career
var coursesByCareer = await _context.Courses
    .GroupBy(c => c.Career!.Name)
    .Select(g => new
    {
        CareerName = g.Key,
        CoursesCount = g.Count()
    })
    .ToListAsync();

// Top courses with most students
var topCourseStudents = await _context.Enrollments
    .GroupBy(e => e.Course!.Name)
    .Select(g => new
    {
        CourseName = g.Key,
        StudentCount = g.Count()
    })
    .OrderByDescending(c => c.StudentCount)
    .ToListAsync();

Call Stored Procedure with EF Core

.NET / LINQ / SQL

Example of executing a SQL Server stored procedure from Entity Framework Core using FromSqlRaw.

[HttpGet("studentsCareer")]
public async Task<IActionResult> GetStudentsCareer(int careerId)
{
    var studentsCareer = await _context.Students
        .FromSqlRaw("EXEC GetStudentsByCareer {0}", careerId)
        .ToListAsync();

    return Ok(studentsCareer);
}

EF Core Transaction Example

.NET / Transactions

Example of using a database transaction in Entity Framework Core to ensure multiple operations succeed or fail together.

[HttpPost("createStudentEnrollment")]
public async Task<IActionResult> CreateStudentEnrollment()
{
    using var transaction = await _context.Database.BeginTransactionAsync();

    try
    {
        var student = new Student
        {
            FullName = "User Test",
            Email = "user@test.com",
            CareerId = 1
        };

        _context.Students.Add(student);
        await _context.SaveChangesAsync();

        var enrollment = new Enrollment
        {
            StudentId = student.Id,
            CourseId = 1
        };

        _context.Enrollments.Add(enrollment);
        await _context.SaveChangesAsync();

        await transaction.CommitAsync();

        return Ok("Student and Enrollment created");
    }
    catch
    {
        await transaction.RollbackAsync();
        return BadRequest("Transaction failed");
    }
}

.NET Dependency Injection Lifetimes

.NET / DI
Scoped
One instance per HTTP request.

Request 1 -> new instance
Request 2 -> new instance

Common usage:
- DbContext
- Repositories
- Services

----------------------------

Singleton
One instance for the entire application lifetime.

App starts
↓
One instance forever

Common usage:
- Configuration
- Cache
- Stateless services

----------------------------

Transient
A new instance every time it is requested.

Used for:
- Very lightweight services
- Helpers
- Formatters

Typical .NET API Project Structure (Clean Architecture Style)

.NET / Architecture
API
│
├── Controllers
│   └── StudentsController
│
├── Domain
│   └── Entities
│       ├── Student
│       ├── Course
│       ├── Career
│       └── Enrollment
│
├── Application
│   ├── Interfaces
│   │   ├── IStudentRepository
│   │   └── IStudentService
│   │
│   └── Services
│       └── StudentService
│
├── Infrastructure
│   ├── Data
│   │   └── ApplicationDbContext
│   │
│   └── Repositories
│       └── StudentRepository
│
└── Program.cs

Register Services in Program.cs

.NET / Dependency Injection

Example of registering DbContext, repositories, services, cache, and helpers using different lifetimes.

builder.Services.AddDbContext<ApplicationDbContext>();

builder.Services.AddScoped<IStudentRepository, StudentRepository>();
builder.Services.AddScoped<IStudentService, StudentService>();

builder.Services.AddSingleton<ICacheService, CacheService>();

builder.Services.AddTransient<IEmailFormatter, EmailFormatter>();

Pagination with LINQ (Skip / Take)

.NET / LINQ

Basic pagination pattern for APIs using page number and page size.

[HttpGet("students")]
public async Task<IActionResult> GetStudents(int page = 1, int pageSize = 10)
{
    var query = _context.Students.AsNoTracking();

    var totalRecords = await query.CountAsync();

    var students = await query
        .OrderBy(s => s.Id)
        .Skip((page - 1) * pageSize)
        .Take(pageSize)
        .Select(s => new
        {
            s.Id,
            s.FullName,
            s.Email
        })
        .ToListAsync();

    return Ok(new
    {
        page,
        pageSize,
        totalRecords,
        totalPages = (int)Math.Ceiling(totalRecords / (double)pageSize),
        data = students
    });
}

Global Exception Middleware

.NET / Middleware

Centralized error handling middleware for ASP.NET Core APIs.

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionMiddleware> _logger;

    public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Unhandled exception");

            context.Response.StatusCode = 500;
            context.Response.ContentType = "application/json";

            var response = new
            {
                message = "An unexpected error occurred",
                detail = ex.Message
            };

            await context.Response.WriteAsJsonAsync(response);
        }
    }
}
// Register in Program.cs
app.UseMiddleware<ExceptionMiddleware>();

CSS Flexbox Layout

CSS3 / Layout
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

CSS Grid Layout

CSS3 / Grid
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

Center Element Horizontally and Vertically

CSS3 / Layout
.center-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

CSS Variables

CSS3 / Variables
:root {
  --primary-color: #4f46e5;
  --border-radius: 8px;
}

.button {
  background: var(--primary-color);
  border-radius: var(--border-radius);
}

Responsive Media Query

CSS3 / Responsive
@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }
}

Hover Effect

CSS3 / Interaction
.button {
  background: #6366f1;
  transition: transform 0.2s ease;
}

.button:hover {
  transform: scale(1.05);
}

Card Shadow

CSS3 / UI
.card {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}

Simple CSS Animation

CSS3 / Animation
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.fade-in {
  animation: fadeIn 1s ease-in-out;
}
$1 $1 $1 $1

Clean Architecture - Controller using Service

.NET / Clean Architecture

ASP.NET Core controller that interacts with the service layer instead of directly accessing the repository.

[ApiController]
[Route("api/students")]
public class StudentsController : ControllerBase
{
    private readonly IStudentService _service;

    public StudentsController(IStudentService service)
    {
        _service = service;
    }

    [HttpGet]
    public async Task<IActionResult> GetStudents()
    {
        var students = await _service.GetStudents();
        return Ok(students);
    }
}

Clean Architecture - Dependency Injection

.NET / Clean Architecture

Register repository and service implementations in the dependency injection container.

builder.Services.AddScoped<IStudentRepository, StudentRepository>();
builder.Services.AddScoped<IStudentService, StudentService>();

Clean Architecture - Full Example

.NET / Clean Architecture

Complete simplified example showing Repository, Service, Repository Implementation and Controller in a Clean Architecture style.

public interface IStudentRepository
{
    Task<List<Student>> GetAllAsync();
    Task<Student?> GetByIdAsync(int id);
    Task AddAsync(Student student);
}

public class StudentService : IStudentService
{
    private readonly IStudentRepository _repository;

    public StudentService(IStudentRepository repository)
    {
        _repository = repository;
    }

    public async Task<List<Student>> GetStudents()
    {
        return await _repository.GetAllAsync();
    }

    public async Task CreateStudent(Student student)
    {
        await _repository.AddAsync(student);
    }
}

public class StudentRepository : IStudentRepository
{
    private readonly ApplicationDbContext _context;

    public StudentRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<List<Student>> GetAllAsync()
    {
        return await _context.Students.ToListAsync();
    }

    public async Task<Student?> GetByIdAsync(int id)
    {
        return await _context.Students.FindAsync(id);
    }

    public async Task AddAsync(Student student)
    {
        _context.Students.Add(student);
        await _context.SaveChangesAsync();
    }
}

[ApiController]
[Route("api/students")]
public class StudentsController : ControllerBase
{
    private readonly IStudentService _service;

    public StudentsController(IStudentService service)
    {
        _service = service;
    }

    [HttpGet]
    public async Task<IActionResult> GetStudents()
    {
        var students = await _service.GetStudents();
        return Ok(students);
    }
}