Basic Git Commands
GitCommon 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
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
Useful Docker commands for containers and images.
docker build -t myapp .
docker run -p 8080:80 myapp
docker ps
docker stop container_id
Generate a secure password hash before saving a user.
var passwordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
Compare the entered password with the stored password hash.
var validPassword = BCrypt.Net.BCrypt.Verify(dto.Password, user.PasswordHash);
Structured logging example for failed login attempts.
_logger.LogWarning("Login failed for {Username}", dto.Username);
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[] {}
}
});
});
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
}
}
Example of creating a table in SQL Server.
CREATE TABLE Users (
Id INT PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(200)
);
Entity Framework Core configuration using SQL Server and a connection string from configuration.
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
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)
);
Example of a composite foreign key referencing two columns.
FOREIGN KEY (StudentId, CourseId)
REFERENCES StudentCourses(StudentId, CourseId);
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;
Common Linux commands for navigation and file management.
ls
cd folder
pwd
mkdir new_folder
rm file.txt
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();
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);
[ApiController]
[Route("api/[controller]")]
[HttpDelete("{id}")]
[Authorize(Roles = "Admin")]
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`;
}
}
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}");
}
}
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: {HttpHeaders.authorizationHeader: 'Basic your_api_token_here'},
);
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);
}
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'],
);
}
}
List<Photo> parsePhotos(String responseBody) {
final parsed = (jsonDecode(responseBody) as List)
.cast<Map<String, dynamic>>();
return parsed.map<Photo>(Photo.fromJson).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get(
Uri.parse('https://jsonplaceholder.typicode.com/photos'),
);
return parsePhotos(response.body);
}
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);
}
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());
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; }
}
}
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!");
}
}
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();
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;
}
}
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);
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();
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();
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());
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();
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');
});
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');
});
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);
});
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
git branch feature-login
git checkout feature-login
git checkout -b feature-api
git pull origin main
git add .
git commit -m "update feature"
git push origin main
git clone https://github.com/user/repository.git
cd repository
pwd
ls
ls -la
cd folder
cd ..
touch file.txt
cp file.txt backup.txt
mv file.txt newfile.txt
rm file.txt
chmod 755 script.sh
chmod +x script.sh
chown user:user file.txt
ps aux
top
kill -9 1234
htop
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);
}
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; }
}
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 }
};
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();
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);
}
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");
}
}
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
API
│
├── Controllers
│ └── StudentsController
│
├── Domain
│ └── Entities
│ ├── Student
│ ├── Course
│ ├── Career
│ └── Enrollment
│
├── Application
│ ├── Interfaces
│ │ ├── IStudentRepository
│ │ └── IStudentService
│ │
│ └── Services
│ └── StudentService
│
├── Infrastructure
│ ├── Data
│ │ └── ApplicationDbContext
│ │
│ └── Repositories
│ └── StudentRepository
│
└── Program.cs
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>();
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
});
}
Example of combining pagination with a search filter in an API endpoint.
[HttpGet("students-search")]
public async Task<IActionResult> GetStudents(string? search, int page = 1, int pageSize = 10)
{
var query = _context.Students.AsNoTracking();
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(s => s.FullName.Contains(search));
}
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
});
}
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>();
.container {
display: flex;
justify-content: center;
align-items: center;
gap: 20px;
}
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
.center-box {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
:root {
--primary-color: #4f46e5;
--border-radius: 8px;
}
.button {
background: var(--primary-color);
border-radius: var(--border-radius);
}
@media (max-width: 768px) {
.container {
flex-direction: column;
}
}
.button {
background: #6366f1;
transition: transform 0.2s ease;
}
.button:hover {
transform: scale(1.05);
}
.card {
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.fade-in {
animation: fadeIn 1s ease-in-out;
}
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);
}
}
Register repository and service implementations in the dependency injection container.
builder.Services.AddScoped<IStudentRepository, StudentRepository>();
builder.Services.AddScoped<IStudentService, StudentService>();
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);
}
}