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 3, 2026

C#

C#: Use Source Generators to Generate Boilerplate Code at Compile Time

- 03.02.26 - ErcanOPAK comment on C#: Use Source Generators to Generate Boilerplate Code at Compile Time

Writing repetitive mapping code, serialization logic, or validators? Source Generators create code at compile time, eliminating runtime reflection overhead. What Are Source Generators: // You write this: [GenerateToString] public partial class Person { public string Name { get; set; } public int Age { get; set; } } // Source Generator automatically creates this at […]

Read More
C#

C#: Use Channels for Producer-Consumer Patterns (Better Than BlockingCollection)

- 03.02.26 - ErcanOPAK comment on C#: Use Channels for Producer-Consumer Patterns (Better Than BlockingCollection)

Processing queue of tasks between threads? System.Threading.Channels provides async-first, high-performance producer-consumer patterns. Install Package: dotnet add package System.Threading.Channels Basic Producer-Consumer: using System.Threading.Channels; // Create unbounded channel var channel = Channel.CreateUnbounded(); // Producer task var producer = Task.Run(async () => { for (int i = 0; i < 100; i++) { await channel.Writer.WriteAsync($"Message {i}"); await Task.Delay(10); […]

Read More
C#

C#: Use Record Types with With-Expressions for Immutable Data Transformations

- 03.02.26 - ErcanOPAK comment on C#: Use Record Types with With-Expressions for Immutable Data Transformations

Modifying objects causes bugs when multiple parts of code reference the same instance. Records with with-expressions create modified copies safely. The Mutable Class Problem: public class Person { public string Name { get; set; } public int Age { get; set; } } var person = new Person { Name = “John”, Age = 30 […]

Read More
SQL

SQL: Use MERGE to Upsert (Insert or Update) in One Statement

- 03.02.26 - ErcanOPAK comment on SQL: Use MERGE to Upsert (Insert or Update) in One Statement

Inserting if row doesn’t exist, updating if it does? MERGE statement does both in one atomic operation without race conditions. The Problem – Separate Insert/Update: — Check if exists IF EXISTS (SELECT 1 FROM Products WHERE ProductId = @Id) BEGIN — Update UPDATE Products SET ProductName = @Name, Price = @Price WHERE ProductId = @Id; […]

Read More
SQL

SQL: Use Window Functions to Calculate Running Totals Without Self-Joins

- 03.02.26 - ErcanOPAK comment on SQL: Use Window Functions to Calculate Running Totals Without Self-Joins

Need running totals, rankings, or moving averages? Window functions do it in one query without complex self-joins or cursors. The Old Painful Way – Self-Join: — Calculate running total of sales SELECT o1.OrderDate, o1.Amount, (SELECT SUM(o2.Amount) FROM Orders o2 WHERE o2.OrderDate

Read More
Asp.Net Core

.NET Core: Use Minimal APIs to Create Lightweight Endpoints Without Controllers

- 03.02.26 - ErcanOPAK comment on .NET Core: Use Minimal APIs to Create Lightweight Endpoints Without Controllers

Creating a controller, action method, and routing just to return simple JSON? Minimal APIs in .NET 6+ let you define endpoints in 3 lines. Traditional Controller Way: [ApiController] [Route(“api/[controller]”)] public class ProductsController : ControllerBase { private readonly IProductService _productService; public ProductsController(IProductService productService) { _productService = productService; } [HttpGet] public async Task GetAll() { var products […]

Read More
Asp.Net Core

.NET Core: Use IMemoryCache for Lightning-Fast Data Access Without Redis

- 03.02.26 - ErcanOPAK comment on .NET Core: Use IMemoryCache for Lightning-Fast Data Access Without Redis

Hitting database for same data 1000 times per second? IMemoryCache stores frequently-accessed data in RAM for instant access. Setup: // Program.cs or Startup.cs builder.Services.AddMemoryCache(); Basic Usage: public class ProductService { private readonly IMemoryCache _cache; private readonly ApplicationDbContext _db; public ProductService(IMemoryCache cache, ApplicationDbContext db) { _cache = cache; _db = db; } public async Task GetProductAsync(int […]

Read More
Git

Git: Find and Remove Sensitive Data from Entire Repository History

- 03.02.26 - ErcanOPAK comment on Git: Find and Remove Sensitive Data from Entire Repository History

Accidentally committed API keys or passwords? Deleting the file in a new commit doesn’t remove it from history. Here’s how to purge it completely. ⚠️ The Problem: # You committed config.json with API key git add config.json git commit -m “Add config” git push # Then realized mistake and deleted it git rm config.json git […]

Read More
Git

Git: Undo Last Commit Without Losing Changes (3 Different Scenarios)

- 03.02.26 - ErcanOPAK comment on Git: Undo Last Commit Without Losing Changes (3 Different Scenarios)

Committed too early or to wrong branch? Here’s how to undo commits without losing your work, depending on whether you’ve pushed or not. Scenario 1: Undo Last Commit (Not Pushed Yet) # Keep changes in working directory (most common) git reset –soft HEAD~1 # Now your changes are uncommitted, ready to re-commit # Use case: […]

Read More
Ajax

AJAX: Use Axios Interceptors to Automatically Retry Failed Requests

- 03.02.26 - ErcanOPAK comment on AJAX: Use Axios Interceptors to Automatically Retry Failed Requests

Network hiccups causing failed API requests? Axios interceptors can automatically retry failed requests before showing errors to users. Install Axios: npm install axios The Basic Retry Interceptor: import axios from ‘axios’; // Configure retry axios.interceptors.response.use( response => response, // Success – return as is async error => { const config = error.config; // If no […]

Read More
JavaScript

JavaScript: Use Optional Chaining to Prevent ‘Cannot Read Property of Undefined’ Errors

- 03.02.26 - ErcanOPAK comment on JavaScript: Use Optional Chaining to Prevent ‘Cannot Read Property of Undefined’ Errors

Your app crashes with “Cannot read property ‘name’ of undefined”? Optional chaining (?.) safely accesses nested properties without try-catch blocks. The Error-Prone Old Way: const user = getUserData(); // Might return null // ❌ This crashes if user is null/undefined const name = user.profile.name; // TypeError: Cannot read property ‘profile’ of undefined // ❌ Traditional […]

Read More
HTML

HTML5: Use Picture Element for Responsive Images (Better Than srcset)

- 03.02.26 - ErcanOPAK comment on HTML5: Use Picture Element for Responsive Images (Better Than srcset)

Serving same 4K image to mobile users? Picture element lets you serve different images per device, saving 80% bandwidth and loading 3x faster. The Old Way – One Image for All: <img src=”hero-4k.jpg” alt=”Hero” /> <!– Problems: – Mobile downloads 5MB 4K image – Only displays 800px wide on phone – Wasted 80% of bandwidth […]

Read More
CSS

CSS: Create Smooth Skeleton Loading Screens with Pure CSS (No JavaScript)

- 03.02.26 - ErcanOPAK comment on CSS: Create Smooth Skeleton Loading Screens with Pure CSS (No JavaScript)

Loading spinners look outdated. Modern sites use skeleton screens that show content placeholders while data loads. Pure CSS, no libraries needed. The Basic Skeleton: .skeleton { background: linear-gradient( 90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75% ); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 4px; } @keyframes loading { 0% { background-position: 200% 0; } […]

Read More
Windows

Windows 11: Bring Back Classic Right-Click Context Menu Permanently

- 03.02.26 - ErcanOPAK comment on Windows 11: Bring Back Classic Right-Click Context Menu Permanently

Tired of the simplified Windows 11 right-click menu that hides all useful options behind “Show more options”? Get the full Windows 10 menu back. The Problem: Windows 11 right-click menu shows: – Cut, Copy, Paste – Rename, Delete – “Show more options” → Opens full menu Extra click needed for: – Send to – Open […]

Read More
Windows

Windows 11: Disable Bing Search in Start Menu to Get Instant Local Results

- 03.02.26 - ErcanOPAK comment on Windows 11: Disable Bing Search in Start Menu to Get Instant Local Results

Start Menu searches taking 5 seconds because Windows is searching Bing? Disable web search to get instant local file/app results. The Annoying Problem: You type “calc” in Start Menu Windows searches: 1. Local apps (0.1 seconds) 2. Bing web search (5 seconds loading…) 3. Shows web results you don’t want Result: 5 second delay just […]

Read More
AI

AI Prompt: Analyze Contracts and Legal Documents to Find Hidden Fees and Unfair Terms

- 03.02.26 - ErcanOPAK comment on AI Prompt: Analyze Contracts and Legal Documents to Find Hidden Fees and Unfair Terms

Signing a lease, employment contract, or service agreement? AI can highlight hidden fees, unfair clauses, and red flags you might miss. The Contract Analysis Prompt: I need help analyzing a legal contract before signing. **Document Type:** [e.g., Apartment Lease, Employment Contract, Service Agreement, Phone Plan] **Full Contract Text:** [Paste entire contract here] **What I Need:** […]

Read More
AI

AI Prompt: Transform Any Recipe to Match Your Dietary Restrictions and Available Ingredients

- 03.02.26 - ErcanOPAK comment on AI Prompt: Transform Any Recipe to Match Your Dietary Restrictions and Available Ingredients

Found the perfect recipe but you’re vegan, gluten-free, or missing half the ingredients? AI can adapt any recipe to your needs while keeping it delicious. The Recipe Adaptation Prompt: I need help adapting a recipe to my dietary needs and available ingredients. **Original Recipe:** [Paste entire recipe here – ingredients and instructions] **Dietary Restrictions:** [e.g., […]

Read More
AI

AI Prompt: Diagnose Home Repair Issues with Photos and Get Step-by-Step Fix Instructions

- 03.02.26 - ErcanOPAK comment on AI Prompt: Diagnose Home Repair Issues with Photos and Get Step-by-Step Fix Instructions

Strange noise from your HVAC? Leak under the sink? Use AI to diagnose and get repair instructions without calling an expensive technician. The Diagnostic Prompt Template: I need help diagnosing and fixing a home repair issue. **The Problem:** [Describe what’s wrong: noise, leak, not working, etc.] **Location:** [Where: kitchen sink, basement furnace, bedroom ceiling, etc.] […]

Read More
Docker

Docker: Clean Up Disk Space by Removing Unused Images and Containers

- 03.02.26 - ErcanOPAK comment on Docker: Clean Up Disk Space by Removing Unused Images and Containers

Docker eating 50GB of disk space? Old images, stopped containers, and dangling volumes pile up fast. One command reclaims it all. Check Current Disk Usage: docker system df # Output: TYPE TOTAL ACTIVE SIZE RECLAIMABLE Images 47 12 28.5GB 18.2GB (63%) Containers 89 5 10.2GB 9.8GB (96%) Local Volumes 23 8 2.3GB 1.1GB (47%) Build […]

Read More
Kubernetes

Kubernetes: Force Delete Stuck Pods in Terminating State Instantly

- 03.02.26 - ErcanOPAK comment on Kubernetes: Force Delete Stuck Pods in Terminating State Instantly

Pod stuck in “Terminating” state for hours? Kubernetes is waiting for graceful shutdown that will never complete. Force delete it properly. The Problem: # Pod stuck forever kubectl get pods NAME STATUS AGE stuck-pod-abc123 Terminating 3h # Normal delete doesn’t work kubectl delete pod stuck-pod-abc123 # Still shows Terminating… Why Pods Get Stuck: When deleting […]

Read More
Wordpress

WordPress: Limit Login Attempts Without Plugins Using .htaccess

- 03.02.26 - ErcanOPAK comment on WordPress: Limit Login Attempts Without Plugins Using .htaccess

Brute force bots hammering wp-login.php with 1000s of password attempts? Block them at Apache level before they even reach WordPress. The Plugin-Free Solution: Add to .htaccess in WordPress root: # Limit wp-login.php access to specific IPs <Files wp-login.php> Order Deny,Allow Deny from all Allow from YOUR_IP_ADDRESS Allow from YOUR_OFFICE_IP </Files> Replace YOUR_IP_ADDRESS with your actual […]

Read More
Wordpress

WordPress: Speed Up Admin Dashboard by Disabling Heartbeat API

- 03.02.26 - ErcanOPAK comment on WordPress: Speed Up Admin Dashboard by Disabling Heartbeat API

WordPress admin panel sluggish and using 100% CPU? The Heartbeat API polls your server every 15 seconds for autosave and notifications, eating resources. What Heartbeat Does: Every 15 seconds: – Check for new comments – Check for plugin updates – Autosave post drafts – Notify about other users editing same post – Trigger scheduled tasks […]

Read More
Photoshop

Photoshop: Fix Blurry Text After Transform with This One Setting

- 03.02.26 - ErcanOPAK comment on Photoshop: Fix Blurry Text After Transform with This One Setting

Scaled or rotated text looks blurry and pixelated? Photoshop’s transform interpolation is set wrong. One checkbox fixes it permanently. The Blurry Text Problem: 1. Create text layer 2. Ctrl+T to transform 3. Scale up 200% 4. Text looks jagged and blurry Why? Photoshop is treating vector text like pixels! The Permanent Fix: Edit → Preferences […]

Read More
Photoshop

Photoshop: Batch Resize 1000 Images in 30 Seconds Without Actions

- 03.02.26 - ErcanOPAK comment on Photoshop: Batch Resize 1000 Images in 30 Seconds Without Actions

Need to resize hundreds of images for web? Skip the tedious Actions panel – Image Processor is faster and requires zero setup. The Old Tedious Way: 1. Create Action 2. Record resize steps 3. File → Automate → Batch 4. Configure 10+ settings 5. Hope it works = 10 minutes setup + easy to mess […]

Read More
Visual Studio

Visual Studio: Stop Debugger from Stepping Into .NET Framework Source Code

- 03.02.26 - ErcanOPAK comment on Visual Studio: Stop Debugger from Stepping Into .NET Framework Source Code

Debugging your code but accidentally stepping into framework methods like String.Format() or Linq internals? This wastes precious debugging time. The Annoying Problem: var users = GetUsers(); var result = users.Where(u => u.IsActive).ToList(); // Press F11 here // Debugger jumps into: // → Enumerable.cs (framework code) // → Buffer.cs // → List.cs // You just wanted […]

Read More
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