Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Day: February 15, 2026

C#

C#: Use Collection Expressions for Cleaner Collection Initialization

- 15.02.26 - ErcanOPAK comment on C#: Use Collection Expressions for Cleaner Collection Initialization

Creating collections with new List { } is verbose. C# 12 collection expressions simplify it. Old Way: List numbers = new List { 1, 2, 3 }; int[] array = new int[] { 1, 2, 3 }; var combined = numbers.Concat(array).ToList(); Collection Expressions: // Simpler syntax List numbers = [1, 2, 3]; int[] array = […]

Read More
C#

C#: Use Primary Constructors to Reduce Boilerplate in Classes

- 15.02.26 - ErcanOPAK comment on C#: Use Primary Constructors to Reduce Boilerplate in Classes

Writing constructors with property assignment is repetitive. C# 12 primary constructors simplify it. Old Way: public class ProductService { private readonly ILogger _logger; private readonly IProductRepository _repo; public ProductService(ILogger logger, IProductRepository repo) { _logger = logger; _repo = repo; } public void DoWork() { _logger.LogInfo(“Working”); _repo.Save(); } } Primary Constructor (C# 12): public class ProductService(ILogger […]

Read More
C#

C#: Use Raw String Literals for Multiline Strings Without Escaping

- 15.02.26 | 15.02.26 - ErcanOPAK comment on C#: Use Raw String Literals for Multiline Strings Without Escaping

Escaping quotes and newlines in strings is annoying. C# 11 raw string literals handle everything. Old Way (Escape Hell): var json = “{\”name\”: \”John\”, \”age\”: 30}”; var path = “C:\\Users\\John\\Documents”; var html = ” <div class=\”container\”>Content</div>”; Raw String Literals: // Use at least 3 quotes var json = “”” { “name”: “John”, “age”: 30 } […]

Read More
C#

C#: Use List Patterns to Match List Elements in Pattern Matching

- 15.02.26 - ErcanOPAK comment on C#: Use List Patterns to Match List Elements in Pattern Matching

Checking list contents with if statements is verbose. C# 11 list patterns make it clean. Traditional Way: if (numbers.Count >= 3 && numbers[0] == 1 && numbers[2] == 3) { // Do something } List Pattern: if (numbers is [1, _, 3, ..]) { // Matches list starting with 1, any value, then 3, then […]

Read More
SQL

SQL: Use EXPLAIN to See Query Execution Plan and Find Bottlenecks

- 15.02.26 - ErcanOPAK comment on SQL: Use EXPLAIN to See Query Execution Plan and Find Bottlenecks

Query slow but don’t know why? EXPLAIN shows exactly how database executes it. Basic Usage: EXPLAIN SELECT * FROM Orders WHERE CustomerId = 123; — Output shows: — – Table scan or index usage — – Number of rows examined — – Join order — – Estimated cost PostgreSQL Analyze: EXPLAIN ANALYZE SELECT * FROM […]

Read More
SQL

SQL: Use CTEs to Make Complex Queries Readable

- 15.02.26 - ErcanOPAK comment on SQL: Use CTEs to Make Complex Queries Readable

Nested subqueries are impossible to read. CTEs (Common Table Expressions) break them into named, readable chunks. Messy Nested Query: SELECT * FROM Orders o WHERE o.CustomerId IN ( SELECT CustomerId FROM Customers WHERE Country IN ( SELECT Country FROM TopCountries WHERE Revenue > 1000000 ) ); Clean CTE Version: WITH TopCountries AS ( SELECT Country […]

Read More
Asp.Net Core

.NET Core: Use Rate Limiting to Prevent API Abuse

- 15.02.26 - ErcanOPAK comment on .NET Core: Use Rate Limiting to Prevent API Abuse

APIs getting hammered with requests? .NET 7+ has built-in rate limiting middleware. Setup: // Program.cs builder.Services.AddRateLimiter(options => { options.AddFixedWindowLimiter(“fixed”, opt => { opt.Window = TimeSpan.FromMinutes(1); opt.PermitLimit = 100; // 100 requests per minute opt.QueueLimit = 0; }); }); var app = builder.Build(); app.UseRateLimiter(); Apply to Endpoints: app.MapGet(“/api/data”, () => “Data”) .RequireRateLimiting(“fixed”); // If user exceeds […]

Read More
Asp.Net Core

.NET Core: Use Health Checks to Monitor Application Status

- 15.02.26 - ErcanOPAK comment on .NET Core: Use Health Checks to Monitor Application Status

Need to know if your app is healthy? Health checks provide monitoring endpoints automatically. Setup: // Program.cs builder.Services.AddHealthChecks() .AddDbContextCheck() // Check database .AddUrlGroup(new Uri(“https://api.example.com”), “External API”); // Check external dependency var app = builder.Build(); app.MapHealthChecks(“/health”); Test: curl http://localhost:5000/health # Healthy response: 200 OK # Unhealthy: 503 Service Unavailable Custom Health Check: public class MemoryHealthCheck : […]

Read More
Git

Git: Use git log –graph to Visualize Branch History

- 15.02.26 - ErcanOPAK comment on Git: Use git log –graph to Visualize Branch History

Understanding branch history in text is hard. –graph flag shows visual tree. Pretty Graph: git log –graph –oneline –all # Output: # * abc1234 (HEAD -> main) Merge feature # |\ # | * def5678 (feature) Add feature # | * ghi9012 Feature progress # * | jkl3456 Fix bug # |/ # * mno7890 […]

Read More
Git

Git: Use git reflog to Recover Lost Commits After Reset

- 15.02.26 - ErcanOPAK comment on Git: Use git reflog to Recover Lost Commits After Reset

Accidentally did git reset –hard and lost commits? Reflog keeps history of all HEAD movements. View Reflog: git reflog # Output: # abc1234 HEAD@{0}: reset: moving to HEAD~3 # def5678 HEAD@{1}: commit: Important feature ← Lost commit! # ghi9012 HEAD@{2}: commit: Bug fix Recover Lost Commit: # Option 1: Checkout specific commit git checkout def5678 […]

Read More
Ajax

AJAX: Use Server-Sent Events for Real-Time Updates Without WebSocket

- 15.02.26 - ErcanOPAK comment on AJAX: Use Server-Sent Events for Real-Time Updates Without WebSocket

WebSocket is overkill for one-way real-time updates. SSE is simpler and built-in. Server (Node.js Example): app.get(‘/events’, (req, res) => { res.setHeader(‘Content-Type’, ‘text/event-stream’); res.setHeader(‘Cache-Control’, ‘no-cache’); res.setHeader(‘Connection’, ‘keep-alive’); // Send update every 5 seconds const interval = setInterval(() => { res.write(`data: ${JSON.stringify({ time: Date.now() })}\n\n`); }, 5000); req.on(‘close’, () => clearInterval(interval)); }); Client: const eventSource = new […]

Read More
JavaScript

JavaScript: Use AbortController to Cancel Multiple Requests at Once

- 15.02.26 - ErcanOPAK comment on JavaScript: Use AbortController to Cancel Multiple Requests at Once

Canceling multiple fetch requests individually is messy. One AbortController can cancel them all. Single Controller for Multiple Requests: const controller = new AbortController(); const signal = controller.signal; // Multiple requests with same signal const userRequest = fetch(‘/api/user’, { signal }); const ordersRequest = fetch(‘/api/orders’, { signal }); const settingsRequest = fetch(‘/api/settings’, { signal }); // […]

Read More
HTML

HTML5: Use input type=’date’ for Native Date Picker

- 15.02.26 - ErcanOPAK comment on HTML5: Use input type=’date’ for Native Date Picker

JavaScript date picker libraries add 100KB+ overhead. HTML5 date input is native and lightweight. Basic Usage: <input type=”date” name=”birthday” min=”1900-01-01″ max=”2024-12-31″> Features: – Native calendar popup on all browsers – Automatic validation – Mobile-optimized keyboard – Supports min/max constraints – Returns YYYY-MM-DD format Other Useful Types: <input type=”time”> <!– HH:MM picker –> <input type=”datetime-local”> <!– […]

Read More
CSS

CSS: Use Grid auto-fit and minmax for Responsive Layouts Without Media Queries

- 15.02.26 - ErcanOPAK comment on CSS: Use Grid auto-fit and minmax for Responsive Layouts Without Media Queries

Media queries for every screen size is tedious. CSS Grid auto-fit + minmax creates responsive layouts automatically. Traditional Responsive: .grid { display: grid; grid-template-columns: repeat(4, 1fr); } @media (max-width: 1200px) { .grid { grid-template-columns: repeat(3, 1fr); } } @media (max-width: 900px) { .grid { grid-template-columns: repeat(2, 1fr); } } @media (max-width: 600px) { .grid { […]

Read More
Windows

Windows 11: Use Screen Recording Without Third-Party Software

- 15.02.26 - ErcanOPAK comment on Windows 11: Use Screen Recording Without Third-Party Software

Need quick screen recording? Windows has built-in Game Bar for recording any app. Start Recording: Win+G (opens Game Bar) → Click Record button Or shortcut: Win+Alt+R Features: – Record any app window – Include/exclude microphone – Include/exclude system audio – Shows FPS counter (optional) – Saves to Videos/Captures folder as MP4 Settings: Settings → Gaming […]

Read More
Windows

Windows 11: Use Windows Sandbox to Test Software Safely

- 15.02.26 - ErcanOPAK comment on Windows 11: Use Windows Sandbox to Test Software Safely

Installing untrusted software risks your PC. Windows Sandbox creates disposable virtual environment. Enable Sandbox: Control Panel → Programs → Turn Windows features on/off → Check “Windows Sandbox” Use: Start Menu → Search “Windows Sandbox” → Opens clean Windows environment Features: – Completely isolated from main Windows – Closes and deletes everything on exit – Fresh […]

Read More
AI

AI Prompt: Create API Documentation from Code

- 15.02.26 - ErcanOPAK comment on AI Prompt: Create API Documentation from Code

Writing API docs is boring. AI generates beautiful documentation from your endpoints. The Prompt: Create API documentation for these endpoints: [Paste controller/routes code] Format as: 1. Endpoint overview table 2. For each endpoint: – HTTP method and path – Description – Request parameters (query, path, body) – Request example (curl + code) – Response format […]

Read More
AI

AI Prompt: Refactor Legacy Code to Modern Patterns

- 15.02.26 - ErcanOPAK comment on AI Prompt: Refactor Legacy Code to Modern Patterns

Cleaning up old code manually takes days. AI refactors to modern patterns while preserving logic. The Prompt: Refactor this legacy code to modern best practices: [Paste old code] Target language version: [e.g., C# 11, ES2023] Apply: 1. Modern syntax (async/await, arrow functions, etc.) 2. Design patterns where appropriate 3. Better naming conventions 4. Remove code […]

Read More
AI

AI Prompt: Generate Unit Tests from Existing Code

- 15.02.26 - ErcanOPAK comment on AI Prompt: Generate Unit Tests from Existing Code

Writing tests is tedious but necessary. AI generates comprehensive test cases automatically. The Prompt: Generate unit tests for this code: [Paste your function/class] Requirements: 1. Use [testing framework – e.g., Jest, xUnit, pytest] 2. Test happy path 3. Test edge cases (null, empty, invalid input) 4. Test error handling 5. Include setup/teardown if needed 6. […]

Read More
Docker

Docker: Use Docker Init to Generate Dockerfiles Automatically

- 15.02.26 - ErcanOPAK comment on Docker: Use Docker Init to Generate Dockerfiles Automatically

Writing Dockerfiles from scratch is error-prone. Docker init analyzes your project and generates optimized Dockerfile. Run in Project Directory: docker init # Detects project type (Node.js, Python, Go, etc.) # Asks questions about your app # Generates: # – Dockerfile # – .dockerignore # – docker-compose.yml Example Output for Node.js: Creates multi-stage build, sets up […]

Read More
Kubernetes

Kubernetes: Use Horizontal Pod Autoscaler to Scale Based on CPU/Memory

- 15.02.26 - ErcanOPAK comment on Kubernetes: Use Horizontal Pod Autoscaler to Scale Based on CPU/Memory

Manual scaling is reactive and slow. HPA automatically scales pods based on resource usage. Create HPA: kubectl autoscale deployment myapp \ –cpu-percent=70 \ –min=2 \ –max=10 # When CPU > 70%, adds pods (up to 10) # When CPU < 70%, removes pods (down to 2) YAML Version: apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: myapp-hpa […]

Read More
Wordpress

WordPress: Use WP-CLI to Manage WordPress from Command Line

- 15.02.26 - ErcanOPAK comment on WordPress: Use WP-CLI to Manage WordPress from Command Line

Clicking through admin for repetitive tasks is slow. WP-CLI automates everything from terminal. Install: curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar chmod +x wp-cli.phar sudo mv wp-cli.phar /usr/local/bin/wp Common Commands: # Install plugin wp plugin install contact-form-7 –activate # Update all plugins wp plugin update –all # Create user wp user create john john@example.com –role=author # Search and replace […]

Read More
Wordpress

WordPress: Use wp_mail() SMTP to Fix Email Delivery Issues

- 15.02.26 - ErcanOPAK comment on WordPress: Use wp_mail() SMTP to Fix Email Delivery Issues

WordPress emails going to spam or not sending? PHP mail() is unreliable. Use SMTP instead. Install Plugin: “WP Mail SMTP” or “Easy WP SMTP” Or Add to functions.php: add_action(‘phpmailer_init’, function($phpmailer) { $phpmailer->isSMTP(); $phpmailer->Host = ‘smtp.gmail.com’; $phpmailer->SMTPAuth = true; $phpmailer->Port = 587; $phpmailer->Username = ‘your-email@gmail.com’; $phpmailer->Password = ‘your-app-password’; $phpmailer->SMTPSecure = ‘tls’; $phpmailer->From = ‘your-email@gmail.com’; $phpmailer->FromName = […]

Read More
Photoshop

Photoshop: Use High Pass Filter for Professional Sharpening

- 15.02.26 - ErcanOPAK comment on Photoshop: Use High Pass Filter for Professional Sharpening

Regular sharpen filter creates artifacts. High Pass sharpening gives professional results with full control. Steps: 1. Duplicate layer (Ctrl+J) 2. Filter → Other → High Pass 3. Set Radius 1-3 pixels (subtle edges visible) 4. Change blend mode to Overlay or Soft Light 5. Adjust opacity to taste Why Better: – Non-destructive (adjust opacity anytime) […]

Read More
Photoshop

Photoshop: Use Match Color to Copy Color Grading Between Photos

- 15.02.26 - ErcanOPAK comment on Photoshop: Use Match Color to Copy Color Grading Between Photos

Manually matching colors between photos is tedious. Match Color automatically transfers color tone. Steps: 1. Open photo you want to adjust (target) 2. Image → Adjustments → Match Color 3. Source dropdown → Select reference photo 4. Photoshop automatically matches colors! Fine-tune: – Luminance slider: Adjust brightness – Color Intensity: Increase/decrease saturation – Fade: Blend […]

Read More
Visual Studio

Visual Studio: Use Solution Filters to Load Only Projects You Need

- 15.02.26 - ErcanOPAK comment on Visual Studio: Use Solution Filters to Load Only Projects You Need

Large solution taking 5 minutes to load? Solution filters load only selected projects instantly. Create Filter: 1. Right-click solution → Unload unnecessary projects 2. File → Save As Solution Filter (.slnf) 3. Next time: Open .slnf instead of .sln Result: Solution with 50 projects: 5 min load time Filter with 5 projects: 10 sec load […]

Read More
C#

C#: Use Pattern Matching in Property Patterns for Complex Conditions

- 15.02.26 - ErcanOPAK comment on C#: Use Pattern Matching in Property Patterns for Complex Conditions

Nested if statements for object properties are messy. Property patterns make complex checks clean. Messy If-Else: if (user != null && user.Address != null && user.Address.Country == “USA” && user.Age >= 18) { return “Eligible”; } Clean Property Pattern: var result = user switch { { Address.Country: “USA”, Age: >= 18 } => “Eligible”, { […]

Read More
C#

C#: Use IAsyncEnumerable for Streaming Large Data Sets

- 15.02.26 - ErcanOPAK comment on C#: Use IAsyncEnumerable for Streaming Large Data Sets

Loading all results into memory first is wasteful. IAsyncEnumerable streams results as they’re retrieved. Old Way – Load Everything: public async Task GetOrdersAsync() { return await _db.Orders.ToListAsync(); // Loads all 1 million orders into memory! } // Caller: var orders = await GetOrdersAsync(); // 5GB in memory foreach (var order in orders) ProcessOrder(order); Stream with […]

Read More
C#

C#: Use ValueTask for Async Methods That Often Return Synchronously

- 15.02.26 - ErcanOPAK comment on C#: Use ValueTask for Async Methods That Often Return Synchronously

Task allocates even when result is immediately available. ValueTask avoids allocation for synchronous returns. Scenario: // Cache that often has value ready (no async needed) public async Task GetUserAsync(int id) { if (_cache.TryGetValue(id, out var user)) return user; // Immediate return, but still allocates Task return await _db.Users.FindAsync(id); } Better with ValueTask: public async ValueTask […]

Read More
C#

C#: Use Span for High-Performance Array Operations

- 15.02.26 - ErcanOPAK comment on C#: Use Span for High-Performance Array Operations

Array operations creating copies wastes memory. Span provides view over memory without copying. Traditional Array Slicing: int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] slice = numbers.Skip(2).Take(5).ToArray(); // Creates new array, copies 5 elements With Span: int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; […]

Read More
Page 1 of 2
1 2 Next »

Posts navigation

Older posts
February 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
232425262728  
« Jan    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (935)
  • How to add default value for Entity Framework migrations for DateTime and Bool (832)
  • Get the First and Last Word from a String or Sentence in SQL (826)
  • How to select distinct rows in a datatable in C# (799)
  • How to make theater mode the default for Youtube (714)
  • Add Constraint to SQL Table to ensure email contains @ (574)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (552)
  • Average of all values in a column that are not zero in SQL (520)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (474)
  • Find numbers with more than two decimal places in SQL (436)

Recent Posts

  • C#: Use ArgumentNullException.ThrowIfNull for Cleaner Validation
  • C#: Use Discard Pattern to Ignore Unwanted Values
  • C#: Use Deconstruction with Tuples for Cleaner Multiple Returns
  • C#: Use File-Scoped Types to Limit Class Visibility
  • SQL: Use PIVOT to Transform Rows into Columns
  • SQL: Use MERGE OUTPUT to Track What Changed During Upsert
  • .NET Core: Use Polly for Resilient HTTP Requests with Retry Logic
  • .NET Core: Use Dapper for Lightweight ORM Alternative to Entity Framework
  • Git: Use git sparse-checkout to Clone Only Specific Folders
  • Git: Use git switch and git restore Instead of Confusing git checkout

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (935)
  • How to add default value for Entity Framework migrations for DateTime and Bool (832)
  • Get the First and Last Word from a String or Sentence in SQL (826)
  • How to select distinct rows in a datatable in C# (799)
  • How to make theater mode the default for Youtube (714)

Recent Posts

  • C#: Use ArgumentNullException.ThrowIfNull for Cleaner Validation
  • C#: Use Discard Pattern to Ignore Unwanted Values
  • C#: Use Deconstruction with Tuples for Cleaner Multiple Returns
  • C#: Use File-Scoped Types to Limit Class Visibility
  • SQL: Use PIVOT to Transform Rows into Columns

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com