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

Day: December 6, 2025

JavaScript

JavaScript Event Loop Misconceptions — Why setTimeout(fn, 0) Is NOT Instant

- 06.12.25 - ErcanOPAK comment on JavaScript Event Loop Misconceptions — Why setTimeout(fn, 0) Is NOT Instant

Many devs think: setTimeout(() => console.log(“hi”), 0); runs immediately. It does NOT. 🔍 Why? It is put into the task queue, which only runs after: microtasks (Promise callbacks) current call stack render steps Example Promise.resolve().then(() => console.log(“promise”)); setTimeout(() => console.log(“timeout”), 0); // Output: // promise // timeout 💡 Why This Matters Debugging race conditions Handling […]

Read More
HTML

HTML5 Input Validation — Why Your Patterns “Don’t Work”

- 06.12.25 - ErcanOPAK comment on HTML5 Input Validation — Why Your Patterns “Don’t Work”

HTML5 validation fails when: Wrong regex style Missing anchors Using lookaheads (not supported) Using unescaped characters ❌ Wrong <input pattern=”[A-Z]{3}-[0-9]+” /> ✔ Correct Always anchor: <input pattern=”^[A-Z]{3}-[0-9]+$” /> 💡 Life-Saving Detail HTML5 pattern must match the entire string.Not a substring — the whole value. This rule is rarely known and causes hours of debugging.

Read More
CSS

CSS Z-Index Hell — Why Elements Randomly Disappear (and the Real Fix)

- 06.12.25 - ErcanOPAK comment on CSS Z-Index Hell — Why Elements Randomly Disappear (and the Real Fix)

Z-index doesn’t work the way most devs think.It depends on stacking contexts, not numbers. 🔥 The Real Causes position: relative creates a new stacking context transform creates a new stacking context opacity < 1 creates a new stacking context Parent stacking contexts override children You can set z-index: 999999 and STILL not see your element. […]

Read More
Asp.Net Core / C#

.NET Core JSON Serializer Pitfalls — Why Your Properties Don’t Serialize

- 06.12.25 - ErcanOPAK comment on .NET Core JSON Serializer Pitfalls — Why Your Properties Don’t Serialize

System.Text.Json is fast……but very strict. Common Pain Points Missing getters Private setters PascalCase vs camelCase mismatch Ignored fields without [JsonInclude] Cycles now break serialization ✔ Life-Saving Fix Add: options.PropertyNameCaseInsensitive = true; options.ReferenceHandler = ReferenceHandler.IgnoreCycles; ✔ Hidden Trick For private setters: [JsonInclude] public string Name { get; private set; } This is rarely mentioned but solves […]

Read More
Asp.Net Core / C#

ASP.NET Core Middleware Order — Why Your App Breaks for No Reason

- 06.12.25 - ErcanOPAK comment on ASP.NET Core Middleware Order — Why Your App Breaks for No Reason

The #1 misunderstood part of ASP.NET Core is middleware order. ❌ Bad Order Example app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); Authentication runs BEFORE routing → user can’t be authorized → random 401s. ✔ Correct Order app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(…); 💡 Life-Saving Insight Routing must ALWAYS come first.Authorization must ALWAYS come after Authentication. Confusing ordering makes APIs randomly break.

Read More
SQL

SQL The “Too Many Indexes” Problem — Why Over-Indexing Slows Everything

- 06.12.25 - ErcanOPAK comment on SQL The “Too Many Indexes” Problem — Why Over-Indexing Slows Everything

Many devs think more indexes = faster queries.Nope. ⚠ Real Risks Inserts slow down Updates slow down Deletes slow down Database size explodes Memory grants skyrocket Locking increases ✔ The Life-Saving Rule Every index must support a query.If the query does NOT exist → the index should NOT exist. ✔ How To Check Query sys.dm_db_index_usage_stats: […]

Read More
SQL

SQL Parameter Sniffing — The REAL Fix Nobody Explains Properly

- 06.12.25 - ErcanOPAK comment on SQL Parameter Sniffing — The REAL Fix Nobody Explains Properly

Most “solutions” online are myths.Here’s the real fix. 🧨 The Problem SQL Server caches a plan using the first parameter value. If first call is small dataset → plan optimized for smallIf next call is huge → BAD performance ✔ The Correct Fix (Rarely Understood) Use OPTIMIZE FOR UNKNOWN: SELECT * FROM Orders WHERE CustomerId […]

Read More
C#

C# HttpClient Misuse — The Root of Random Slowdowns / DNS Failures

- 06.12.25 - ErcanOPAK comment on C# HttpClient Misuse — The Root of Random Slowdowns / DNS Failures

Developers still do this: var client = new HttpClient(); // ❌ NEVER do this Creating HttpClient per request causes: Port exhaustion DNS reuse issues Slowdown under load Socket exceptions ✔ The ONLY Correct Pattern builder.Services.AddHttpClient(); Or for minimal APIs: var client = httpClientFactory.CreateClient(); 💡 The Life-Saving Insight If you see: random timeouts slow downstream calls […]

Read More
C#

C# Configuration Binding Hell — Why Your Options Return Null

- 06.12.25 - ErcanOPAK comment on C# Configuration Binding Hell — Why Your Options Return Null

Many devs struggle with strongly-typed configuration returning null unexpectedly. 🔥 Main Causes Missing services.Configure<T>() Wrong section name Mistyped property names Missing getters/setters Nested classes not matching JSON structure ✔ The Correct Pattern builder.Services.Configure<MySettings>( builder.Configuration.GetSection(“MySettings”)); public class MySettings { public string ApiKey { get; set; } } ✔ But Here’s the Hidden Trick Add validation to […]

Read More
C#

C# Async “Hangs Forever” Problem — Why Task Never Completes Under Load

- 06.12.25 - ErcanOPAK comment on C# Async “Hangs Forever” Problem — Why Task Never Completes Under Load

This is one of the most painful production issues:async calls sometimes never complete under high load. 🔍 Root Cause: ThreadPool Starvation + Sync-over-Async If your code blocks threads, the async continuations never get a chance to run. Task.Run(() => { Thread.Sleep(3000); // ❌ Blocks threadpool }); Eventually, under load: Tasks queue up ThreadPool can’t spawn […]

Read More
CSS

CSS Subgrid — The Most Misunderstood Layout Feature

- 06.12.25 - ErcanOPAK comment on CSS Subgrid — The Most Misunderstood Layout Feature

Most devs don’t know that Grid can inherit layout from its parent grid. .child { display: grid; grid-template-columns: subgrid; } 🔥 Why It’s Huge Perfect alignment between parent & child Cleaner responsive layouts No duplicated breakpoints Layout consistency made easy

Read More
HTML / JavaScript

Service Workers — Offline-First Apps Made Easy

- 06.12.25 - ErcanOPAK comment on Service Workers — Offline-First Apps Made Easy

Service Workers let your site work offline, cache assets, and load instantly. navigator.serviceWorker.register(‘/service-worker.js’); ✨ What You Get ⚡ Near-instant load time 📦 Cached static assets 📡 Offline browsing 🔋 Reduced server load 💡 Combine with “cache-first” strategies for ultimate speed.

Read More
JavaScript

Debounce vs Throttle — The UI Performance Problem Everyone Gets Wrong

- 06.12.25 - ErcanOPAK comment on Debounce vs Throttle — The UI Performance Problem Everyone Gets Wrong

🎯 Debounce Trigger after user stops typing. Great for: Search boxes Auto-suggest Validation 🌀 Throttle Trigger every X ms, no matter what. Great for: Scroll events Resize events Mouse move Quick Example const debounced = debounce(fn, 300); const throttled = throttle(fn, 200); 💡 Using the wrong one leads to janky UI & wasted CPU.

Read More
Asp.Net Core / C#

Dependency Injection Performance — “AddTransient Everywhere” Is Not the Answer

- 06.12.25 - ErcanOPAK comment on Dependency Injection Performance — “AddTransient Everywhere” Is Not the Answer

Many APIs slow down because lifetime choices are wrong. ❌ Common Mistake Using Transient for heavy services: services.AddTransient<EmailService>(); ✔ Correct Use Singleton for stateless services: services.AddSingleton<IEmailSender, EmailService>(); 💡 Why? Fewer allocations Less GC pressure Faster resolving More consistent performance

Read More
Asp.Net Core

ASP.NET Core Kestrel Limits — Avoid Flooding & Keep APIs Stable

- 06.12.25 - ErcanOPAK comment on ASP.NET Core Kestrel Limits — Avoid Flooding & Keep APIs Stable

Kestrel has built-in protection against floods, slow clients, and excessive headers. Key Settings in appsettings.json: “Kestrel”: { “Limits”: { “MaxRequestBodySize”: 1048576, “KeepAliveTimeout”: “00:00:30”, “RequestHeadersTimeout”: “00:00:30” } } 💡 Why This Matters Stops slow-loris attacks Reduces memory pressure Prevents API overload Ensures predictable scaling Bonus Enable HTTP/2 for better concurrency.

Read More
SQL

SQL Blocking vs Deadlocks — Most Developers Confuse Them

- 06.12.25 - ErcanOPAK comment on SQL Blocking vs Deadlocks — Most Developers Confuse Them

🔒 Blocking Queries wait for each other Slow performance Not fatal ✔ How to Fix Blocking Correct indexing Reduce long transactions Avoid row locks with better filters   💥 Deadlocks Two queries wait on each other SQL kills one session Returns error 1205 ✔ Fix Deadlocks Always access tables in SAME ORDER Keep transactions very […]

Read More
SQL

SQL SARGability — The REAL Reason Your Indexes Don’t Work

- 06.12.25 - ErcanOPAK comment on SQL SARGability — The REAL Reason Your Indexes Don’t Work

SARG (Search ARGument Able) is the biggest reason queries go from 20ms → 10 seconds. ❌ Non-SARGable WHERE YEAR(OrderDate) = 2024 This forces a full scan. ✔ SARGable Version WHERE OrderDate >= ‘2024-01-01’ AND OrderDate < ‘2025-01-01’ 💡 Why It Matters Enables index seeks Saves CPU Reduces IO dramatically

Read More
C#

C# ThreadPool Starvation — Why Tasks Get “Stuck” in High Load

- 06.12.25 - ErcanOPAK comment on C# ThreadPool Starvation — Why Tasks Get “Stuck” in High Load

In high concurrency, ThreadPool starvation causes tasks to freeze for seconds. ⚠ The Symptoms Slow responses under load Random spikes Async operations timing out 😬 Common Cause Task.Run(() => { Thread.Sleep(2000); // ❌ Blocks the threadpool }); ✔ The Fix Use true async APIs: await Task.Delay(2000); 💡 Bonus Use ThreadPool.GetAvailableThreads to diagnose starvation.

Read More
C#

Memory Leaks in C# — The Hidden Culprit: Event Handlers

- 06.12.25 - ErcanOPAK comment on Memory Leaks in C# — The Hidden Culprit: Event Handlers

Unsubscribed event handlers are one of the biggest real-world leak causes. publisher.SomeEvent += OnEvent; // stays forever if not removed ⚠ Why It Leaks The publisher holds a reference to your object GC can’t collect your object Memory keeps climbing ✔ The Fix Always unsubscribe: publisher.SomeEvent -= OnEvent; Or use weak events or IDisposable patterns. […]

Read More
C#

C# Deadlocks Explained — Why ConfigureAwait(false) Saves Your Async Code

- 06.12.25 - ErcanOPAK comment on C# Deadlocks Explained — Why ConfigureAwait(false) Saves Your Async Code

Deadlocks in async/await often come from sync-over-async and the UI/ASP.NET synchronization context. var data = GetDataAsync().Result; // ❌ Possible deadlock 🔥 Why This Happens The UI thread waits Async method tries to resume on the UI thread Both wait forever 😅 ✔ The Fix Use ConfigureAwait(false) in library code: await SomeLibraryCall().ConfigureAwait(false); 💡 Pro Tips Never […]

Read More
Asp.Net Core / C#

.NET Core Connection Pooling — The Hidden Performance Giant

- 06.12.25 - ErcanOPAK comment on .NET Core Connection Pooling — The Hidden Performance Giant

Most API latency problems = opening too many SQL connections. 🚀 Fix Use a single pooled client: builder.Services.AddDbContext<AppDb>(options => options.UseSqlServer(connString, o => o.EnableRetryOnFailure())); ✨ Benefits ⚡ Fast connection acquisition 📉 Lower CPU 🧵 Stable high-load behavior 💡 BonusUse Max Pool Size=200 in connection string for heavy systems.

Read More
Asp.Net Core / C#

Minimal APIs Filters — Middleware Without the Middleware Cost

- 06.12.25 | 06.12.25 - ErcanOPAK comment on Minimal APIs Filters — Middleware Without the Middleware Cost

Filters allow cross-cutting logic without writing a full middleware. builder.Services.AddEndpointFilter<ValidationFilter>(); ⚡ Why They’re Great ⚙ Less overhead 🎯 Scoped to specific endpoints 🧽 Cleaner architectures 🔍 Perfect for validation, auth, logging

Read More
JavaScript

JavaScript Web Workers — Real Multithreading for Heavy Tasks

- 06.12.25 - ErcanOPAK comment on JavaScript Web Workers — Real Multithreading for Heavy Tasks

Web Workers allow JS to run CPU-heavy tasks off the main thread. const worker = new Worker(“worker.js”); worker.postMessage({ action: “process” }); 💥 Why Use Them 🧵 Prevent UI blocking 🚀 Faster data processing 📸 Smooth animations 🧩 Perfect for image, crypto & data tasks

Read More
HTML

HTML5 Lazy Loading Images — Zero-Effort Performance Gains

- 06.12.25 - ErcanOPAK comment on HTML5 Lazy Loading Images — Zero-Effort Performance Gains

Lazy loading is now native in all modern browsers. <img src=”hero.jpg” loading=”lazy” /> 🚀 Why It’s Amazing 📉 Instant LCP improvements 🧠 Saves bandwidth ⚡ Faster page loads 🛠 No JS required

Read More
CSS

CSS Container Queries — The Future of Responsive Design

- 06.12.25 | 06.12.25 - ErcanOPAK comment on CSS Container Queries — The Future of Responsive Design

Media queries scale by viewport…Container queries scale by component. .card { container-type: inline-size; } @container (min-width: 450px) { .card { flex-direction: row; } } ✨ Why They’re a Big Deal 🎯 Component-level responsiveness 📦 No more giant breakpoint spaghetti 🧩 Perfect for design systems

Read More
SQL

SQL Window Functions — The Fastest Way to Do Ranking & Aggregates

- 06.12.25 - ErcanOPAK comment on SQL Window Functions — The Fastest Way to Do Ranking & Aggregates

Window functions eliminate messy subqueries and temp tables. SELECT UserId, Amount, RANK() OVER (ORDER BY Amount DESC) AS RankNo FROM Orders; ⚡ Why They’re Amazing 🚀 Blazingly fast 🧮 Ideal for analytics 🔍 Cleaner than GROUP BY hacks ✂ Replaces many procedural patterns

Read More
SQL

SQL Index Fragmentation — What Actually Matters (and What Doesn’t)

- 06.12.25 - ErcanOPAK comment on SQL Index Fragmentation — What Actually Matters (and What Doesn’t)

Most devs rebuild indexes far too often. ✔ What Matters 📉 Fragmentation < 30% → ignore 🔄 30–80% → reorganize 🔨 > 80% → rebuild ⚡ Better Approach Use sys.dm_db_index_physical_stats to target heavy tables only. SELECT index_type_desc, avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, ‘LIMITED’); 💡 Pro Tip “Rebuild everything nightly” is anti-pattern — kills IO.

Read More
C#

C# Encryption Done Right — AesGcm Instead of AES CBC

- 06.12.25 - ErcanOPAK comment on C# Encryption Done Right — AesGcm Instead of AES CBC

Most devs still use the outdated AES CBC mode.Use AesGcm for modern authenticated encryption. using var aes = new AesGcm(key); aes.Encrypt(nonce, data, ciphertext, tag); 🛡 Why It’s Better ✔ Authenticated ✔ Fast on modern CPUs ✔ Built to prevent tampering ✔ Recommended for APIs & tokens

Read More
C#

C# Source Generators — Compile-Time Performance Boosters

- 06.12.25 - ErcanOPAK comment on C# Source Generators — Compile-Time Performance Boosters

Source Generators remove runtime reflection overhead by generating code during compilation. [MySerialize] public class Product { public string Name { get; set; } } 🚀 Benefits 🧵 Zero runtime reflection ⚙ Blazing-fast mappers & DTO serializers 💾 Smaller memory footprint 🧩 Perfect for AOT workloads (.NET NativeAOT)

Read More
C#

C# Span & Memory — Zero-Allocation Performance Superpowers

- 06.12.25 - ErcanOPAK comment on C# Span & Memory — Zero-Allocation Performance Superpowers

Span<T> gives C# ultra-fast, stack-only slicing without copying memory. Span<char> slice = name.AsSpan(0, 3); ⚡ Why It Matters 🧠 Zero GC allocations 🚀 Safe low-level memory access 📉 Faster parsing, CSV handling, protocol processing ♻ Ideal for high-throughput APIs 💡 Pro Tip Combine with ReadOnlySequence<T> for pipelines.

Read More
December 2025
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
293031  
« Nov   Jan »

Most Viewed Posts

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

Recent Posts

  • C# Value Types Copied More Than You Think
  • C# Async Void Is Dangerous
  • C# Foreach vs For Performance Difference
  • SQL Deletes Lock Tables
  • SQL Queries Slow Despite Indexes
  • .NET Core APIs Feel Slow Under Load
  • ASP.NET Core Memory Grows Slowly
  • Git Conflicts Keep Reappearing
  • Git Rebase Feels Dangerous
  • Ajax Forms Submit Twice

Most Viewed Posts

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

Recent Posts

  • C# Value Types Copied More Than You Think
  • C# Async Void Is Dangerous
  • C# Foreach vs For Performance Difference
  • SQL Deletes Lock Tables
  • SQL Queries Slow Despite Indexes

Social

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