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

Author: ErcanOPAK

Asp.Net Core / C#

ASP.NET Core “IHostedService Never Stops” — Fixing Broken Graceful Shutdowns

- 08.12.25 - ErcanOPAK comment on ASP.NET Core “IHostedService Never Stops” — Fixing Broken Graceful Shutdowns

Many background workers never stop on SIGTERM. ✔ Real Fix Bind cancellation token: public Task StartAsync(CancellationToken ct) { _ = DoWorkAsync(ct); return Task.CompletedTask; } 💡 Super Tip In Program.cs: builder.Services.AddHostedService<MyWorker>(); builder.Services.Configure<HostOptions>(o => { o.ShutdownTimeout = TimeSpan.FromSeconds(20); }); Most devs don’t know this exists → massively improves controlled shutdown.

Read More
Asp.Net Core / C#

.NET Core Dependency Injection “Multiple Registrations” Bug

- 08.12.25 - ErcanOPAK comment on .NET Core Dependency Injection “Multiple Registrations” Bug

This bug causes random services to switch implementations unexpectedly. ⚠ Problem Registering twice: services.AddSingleton<IMailer, SmtpMailer>(); services.AddSingleton<IMailer, FakeMailer>(); ASP.NET Core uses the last registration → extremely hard-to-debug issues. ✔ Fix Remove duplicates OR name your registrations: services.AddSingleton<IMailer, SmtpMailer>(“smtp”); 💡 Hidden Debug Trick Log all registrations: services.ToList().ForEach(x => Console.WriteLine(x.ServiceType));  

Read More
SQL

SQL “Blocking Sessions” — The Hidden Killer: Orphaned Transactions

- 08.12.25 - ErcanOPAK comment on SQL “Blocking Sessions” — The Hidden Killer: Orphaned Transactions

Long-running transaction = entire DB slowdown. ✔ Quick Diagnostic SELECT * FROM sys.dm_tran_active_transactions; If you see an uncommitted transaction running for hours → that’s your culprit. ✔ The Fix Enable XACT_ABORT to auto-kill faulty transactions: SET XACT_ABORT ON; This is rarely known but prevents ghost locks forever.

Read More
SQL

SQL “Slow Pagination” — The Secret Trick: Seek Method

- 08.12.25 - ErcanOPAK comment on SQL “Slow Pagination” — The Secret Trick: Seek Method

Most devs use: ORDER BY Id OFFSET @Skip ROWS FETCH NEXT @Take ROWS This is painfully slow after page 5000+because SQL scans all skipped rows. ✔ REAL FIX: Seek Pagination SELECT TOP (@Take) * FROM Orders WHERE Id > @LastSeenId ORDER BY Id; 💡 Benefit No full scans No offsets Linear, predictable speed

Read More
C#

C# “List Reallocations” — Stop Hidden Performance Loss

- 08.12.25 - ErcanOPAK comment on C# “List Reallocations” — Stop Hidden Performance Loss

Large lists cause hidden reallocations: ⚠ Problem When List grows past capacity → reallocates + copies entire array. ✔ Fix Pre-size it: var list = new List<Order>(50000); 💡 Hidden Tip To estimate size: use .Count from previous runs → AUTO-TUNE your list capacity.

Read More
C#

C# DTO Mapping Speed Issues — The Hidden Cost of Reflection in AutoMapper

- 08.12.25 - ErcanOPAK comment on C# DTO Mapping Speed Issues — The Hidden Cost of Reflection in AutoMapper

Many devs see slow API responses and blame SQL, not realizing the slowdown is Mapper. ⚠ The Problem AutoMapper uses reflection for complex object graphs.Under load → becomes slow. ✔ Life-Saver Solution Switch to compiled mapping: var config = new MapperConfiguration(cfg => { cfg.CreateMap<User, UserDto>().ConvertUsing(src => new UserDto(src.Id, src.Name)); }); or write your own mapping: […]

Read More
C#

C# “Random Freezes” — The REAL Cause: Async → Sync Deadlocks

- 08.12.25 - ErcanOPAK comment on C# “Random Freezes” — The REAL Cause: Async → Sync Deadlocks

Developers often write: var result = GetDataAsync().Result; or var result = GetDataAsync().GetAwaiter().GetResult(); This is how 80% of production deadlocks happen. 👉 Why It Deadlocks Async code tries to resume on the captured context (SynchronizationContext).But since you blocked the thread with .Result, it can’t resume → deadlock. ✔ The Fix Make the entire call chain async: […]

Read More
Visual Studio

Visual Studio “IntelliSense Slow” — Fix the Hidden Roslyn Cache Issue

- 07.12.25 - ErcanOPAK comment on Visual Studio “IntelliSense Slow” — Fix the Hidden Roslyn Cache Issue

If IntelliSense lags, it’s usually Roslyn’s temp files. ✔ Fix Delete: %LOCALAPPDATA%\Microsoft\VisualStudio\*\ComponentModelCache Restart VS → Instant improvement. 💡 Bonus Disable unused analyzers for huge solutions.

Read More
Wordpress

WordPress “White Screen of Death” — The Real Fix Nobody Mentions

- 07.12.25 - ErcanOPAK comment on WordPress “White Screen of Death” — The Real Fix Nobody Mentions

The WSOD usually comes from PHP memory limit — not plugins. ✔ Fix Add to wp-config.php: define(‘WP_MEMORY_LIMIT’, ‘256M’); Default is often 40M → insufficent. 💡 Bonus Enable debug without exposing logs publicly: define(‘WP_DEBUG’, true); define(‘WP_DEBUG_LOG’, true); define(‘WP_DEBUG_DISPLAY’, false);  

Read More
Windows

Windows 11 “File Explorer Slow” — The Thumbnail Cache Killer

- 07.12.25 | 15.02.26 - ErcanOPAK comment on Windows 11 “File Explorer Slow” — The Thumbnail Cache Killer

The Nightmare: You open a folder, and the green loading bar at the top crawls like a snail. Your icons are blank, the scroll is laggy, and File Explorer feels like it’s running on a computer from 1995. This is rarely a hardware issue; it is almost always a corrupted Thumbnail Cache. The Reason: Windows […]

Read More
Windows

Windows 11 “Network Freezes” — Fix the Hidden Power Throttling Issue

- 07.12.25 - ErcanOPAK comment on Windows 11 “Network Freezes” — Fix the Hidden Power Throttling Issue

When Windows aggressively throttles network power, WiFi drops happen. ✔ Fix Disable power throttling: Settings → System → Power → Turn off “Power Throttling”Also run: powercfg -setacvalueindex SCHEME_CURRENT SUB_PROCESSOR PROCTHROTTLEMAX 100 💡 Massive stability boost.

Read More
Ajax / JavaScript

AJAX Cache Nightmare — Why Your GET Requests Don’t Update

- 07.12.25 - ErcanOPAK comment on AJAX Cache Nightmare — Why Your GET Requests Don’t Update

Browsers cache GET requests aggressively. ✔ Life-Saving Fix $.ajax({ url: ‘/api/data’, cache: false }); Under the hood, jQuery adds:?_={timestamp} → bypasses cache. 💡 If using fetch: fetch(‘/api/data’, { cache: ‘no-store’ });  

Read More
JavaScript

JS “Debounce vs Throttle” — Why Your Search Bar Lags

- 07.12.25 - ErcanOPAK comment on JS “Debounce vs Throttle” — Why Your Search Bar Lags

Real problem:Search inputs trigger too many backend calls. ✔ Debounce (use for search) function debounce(fn, delay){ let timeout; return (…args)=>{ clearTimeout(timeout); timeout = setTimeout(()=>fn(…args), delay); }; } ✔ Throttle (use for scroll/resize) function throttle(fn, delay){ let last = 0; return (…args)=>{ const now = Date.now(); if(now – last >= delay){ last = now; fn(…args); } […]

Read More
HTML

HTML5 “Inputmode” — The Feature That Makes Mobile Forms 10× Better

- 07.12.25 - ErcanOPAK comment on HTML5 “Inputmode” — The Feature That Makes Mobile Forms 10× Better

Most devs don’t know this exists. ✔ Example <input type=”text” inputmode=”numeric” /> This forces numeric keyboard on mobile — even though type is text. Also supports: decimal email search tel url 💡 Immediate UX win.

Read More
CSS

CSS Flexbox Gap Not Working? — The Hidden Flex Wrapping Trap

- 07.12.25 - ErcanOPAK comment on CSS Flexbox Gap Not Working? — The Hidden Flex Wrapping Trap

gap: only works when flex items wrap correctly. ❌ Wrong .container { display: flex; gap: 20px; flex-wrap: nowrap; } ✔ Correct .container { display: flex; flex-wrap: wrap; gap: 20px; } 💡 Hidden Detail Safari had partial support — updating fixes 90% layout bugs.

Read More
Asp.Net Core / C#

Rate Limiting in .NET — Fix ‘Random 429 Errors’ the Right Way

- 07.12.25 | 15.02.26 - ErcanOPAK comment on Rate Limiting in .NET — Fix ‘Random 429 Errors’ the Right Way

The Trap: Most developers dutifully add a Rate Limiter to their API to prevent abuse. However, they often make a critical mistake: they set a Global Limit. If you set a limit of “1000 requests per minute” globally, a single malicious bot can use up all 1000 requests in 5 seconds. The result? Your legitimate […]

Read More
Asp.Net Core / C#

ASP.NET Core “ValidateOnStart” — Stop Production Crashes at Runtime

- 07.12.25 - ErcanOPAK comment on ASP.NET Core “ValidateOnStart” — Stop Production Crashes at Runtime

One of the least known but most powerful features. ✔ Use: builder.Services.AddOptions<MySettings>() .Bind(configuration.GetSection(“MySettings”)) .ValidateDataAnnotations() .ValidateOnStart(); Now, invalid configs fail at startup, not during production traffic. 💡 Saves Hours Prevents: null reference crashes broken API keys missing secrets

Read More
SQL

SQL Deadlocks — The 3-Lock Pattern That Solves 90% Cases

- 07.12.25 - ErcanOPAK comment on SQL Deadlocks — The 3-Lock Pattern That Solves 90% Cases

Deadlocks happen when queries lock different resources in different orders. ✔ The Fix Always lock tables in the same sequence. Example: BEGIN TRAN SELECT … FROM Users WITH (UPDLOCK) SELECT … FROM Orders WITH (UPDLOCK) COMMIT If every stored procedure follows this sequence →deadlocks drop to near zero.

Read More
SQL

SQL “Slow LIKE Query” — The Real Fix (Not Indexes!)

- 07.12.25 - ErcanOPAK comment on SQL “Slow LIKE Query” — The Real Fix (Not Indexes!)

LIKE ‘%abc%’ is un-indexable — always full scan. ✔ Rarely Known Fix Use a computed column + index: ALTER TABLE Products ADD NameIndex AS LOWER(Name); CREATE INDEX IX_Products_NameIndex ON Products(NameIndex); Query: WHERE NameIndex LIKE ‘%abc%’ 💡 Result Massive speed boost without full scans.

Read More
C#

C# “Enum Flags” — The Powerful Feature 90% Underuse

- 07.12.25 - ErcanOPAK comment on C# “Enum Flags” — The Powerful Feature 90% Underuse

Developers often create multiple boolean columns instead of using bitwise enums. ✔ Correct Pattern [Flags] public enum Permissions { None = 0, Read = 1, Write = 2, Admin = 4 } Check: if (user.Permissions.HasFlag(Permissions.Admin)) { … } 💡 Benefit Reduces: table columns complexity storage condition checks

Read More
C#

C# Memory Leaks in LINQ — Why Your App Keeps Eating RAM

- 07.12.25 - ErcanOPAK comment on C# Memory Leaks in LINQ — Why Your App Keeps Eating RAM

LINQ is beautiful but dangerous. ⚠ Root Cause Deferred execution + large collections = hidden leaks. Example: var result = bigList.Where(x => x.IsActive); This doesn’t execute yet — the original list must stay alive. ✔ Fix Materialize immediately: var result = bigList.Where(x => x.IsActive).ToList(); 💡 Life-Saving Detection Tip If RAM grows when iterating lists →you […]

Read More
C#

C# “ConfigureAwait(false)” — The Most Misunderstood Performance Trick

- 07.12.25 - ErcanOPAK comment on C# “ConfigureAwait(false)” — The Most Misunderstood Performance Trick

Most devs know ConfigureAwait(false)…But few actually know when to use it — or how much performance it saves. ⚠ Problem Default awaits try to resume on the captured context (UI thread / ASP.NET request context).This slows down: high-load async APIs microservices background tasks ✔ Real Fix Use ConfigureAwait(false) in library code, background workers, hosted services: […]

Read More
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
Page 58 of 69
« Previous 1 … 53 54 55 56 57 58 59 60 61 62 63 … 69 Next »

Posts pagination

« Previous 1 … 56 57 58 59 60 … 69 Next »
April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

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

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

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

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

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