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

HTML

HTML5 Web Workers: Run JavaScript in Background Thread Without Freezing UI

- 01.02.26 - ErcanOPAK comment on HTML5 Web Workers: Run JavaScript in Background Thread Without Freezing UI

Heavy JavaScript computation freezing your webpage? Web Workers run code in a separate thread, keeping your UI responsive. The UI Freezing Problem: // โŒ BAD: Blocks UI for 5 seconds function processLargeData() { const data = Array.from({ length: 10000000 }, (_, i) => i); const result = data .filter(n => n % 2 === 0) […]

Read More
SQL

SQL: When CTEs Kill Performance and You Should Use Temp Tables Instead

- 01.02.26 - ErcanOPAK comment on SQL: When CTEs Kill Performance and You Should Use Temp Tables Instead

Common Table Expressions (CTEs) make queries readable but can cause performance disasters when SQL Server evaluates them multiple times. The CTE Performance Trap: — โŒ BAD: CTE evaluated 3 times! WITH RecentOrders AS ( SELECT CustomerId, OrderDate, Total FROM Orders WHERE OrderDate >= DATEADD(month, -1, GETDATE()) — Complex calculation that takes 5 seconds ) SELECT […]

Read More
SQL

SQL Indexing: Why Your Query Ignores Indexes and Scans 10 Million Rows Instead

- 01.02.26 - ErcanOPAK comment on SQL Indexing: Why Your Query Ignores Indexes and Scans 10 Million Rows Instead

Created an index but your query still takes 30 seconds? SQL Server might be ignoring it due to implicit conversions, functions, or wildcard positioning. Index Killer #1 – Functions on Indexed Columns: — Index exists on CreatedDate CREATE INDEX IX_Orders_CreatedDate ON Orders(CreatedDate); — โŒ BAD: Index ignored, full table scan SELECT * FROM Orders WHERE […]

Read More
C#

C# String Interpolation: Use $”” for Readability, StringBuilder for Performance

- 01.02.26 - ErcanOPAK comment on C# String Interpolation: Use $”” for Readability, StringBuilder for Performance

Building strings in loops? String interpolation is clean but creates a new string on every concatenation. Here’s when to use what. The Readability Winner: // Old way – hard to read string message = “User ” + userName + ” (ID: ” + userId + “) logged in at ” + timestamp; // Modern way […]

Read More
C#

LINQ Performance Trap: Why .Any() Is 10,000x Faster Than .Count() > 0

- 01.02.26 - ErcanOPAK comment on LINQ Performance Trap: Why .Any() Is 10,000x Faster Than .Count() > 0

Using .Count() > 0 to check if a collection has items? You’re forcing LINQ to enumerate the entire collection just to answer a yes/no question. The Performance Killer: var users = dbContext.Users.Where(u => u.IsActive); // BAD: Counts ALL active users first if (users.Count() > 0) { Console.WriteLine(“We have active users”); } // Database query generated: […]

Read More
C#

C# Pattern Matching: Replace Complex If-Else Chains with Switch Expressions

- 01.02.26 - ErcanOPAK comment on C# Pattern Matching: Replace Complex If-Else Chains with Switch Expressions

Nested if-else statements making your code unreadable? C# 9+ switch expressions with pattern matching can reduce 50+ lines to 10. The Old Nightmare: public decimal CalculateDiscount(Customer customer, Order order) { if (customer == null) return 0; if (customer.IsPremium) { if (order.Total > 1000) return order.Total * 0.20m; else if (order.Total > 500) return order.Total * […]

Read More
C#

C# Records: Immutable Data Classes with Built-In Value Equality (C# 9+)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on C# Records: Immutable Data Classes with Built-In Value Equality (C# 9+)

Tired of writing boilerplate Equals, GetHashCode, and ToString methods? C# records do it automatically with better performance. Old Way – Traditional Class: // BAD: 60+ lines for simple data class public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } […]

Read More
C#

C#: Async/Await Common Mistakes That Kill Performance (And How to Fix Them)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on C#: Async/Await Common Mistakes That Kill Performance (And How to Fix Them)

Using async/await everywhere doesn’t automatically make your code faster – it can actually make it slower if done wrong. Here are the critical mistakes. Mistake 1: Async All The Way Down (Unnecessarily): // BAD: Unnecessary async overhead public async Task GetUserIdAsync(string username) { return await Task.FromResult(_cache.Get(username)); // Why async? } // This creates a Task, […]

Read More
C#

C# Performance: Use Span and Memory to Eliminate Array Allocations

- 01.02.26 | 01.02.26 - ErcanOPAK comment on C# Performance: Use Span and Memory to Eliminate Array Allocations

Processing large arrays or strings eating up memory? Span<T> lets you work with slices of memory without allocating new arrays. The Problem – Traditional Approach: // BAD: Creates new array on every call public byte[] ProcessChunk(byte[] data, int start, int length) { byte[] chunk = new byte[length]; // Heap allocation Array.Copy(data, start, chunk, 0, length); […]

Read More
SQL

Fix Deadlocks by Understanding Lock Ordering and Using Proper Isolation Levels

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Fix Deadlocks by Understanding Lock Ordering and Using Proper Isolation Levels

Getting “Transaction was deadlocked” errors randomly? Deadlocks happen when two transactions lock resources in opposite order. Here’s how to fix them permanently. Identify Deadlocks – System Health Session: — SQL Server automatically logs deadlocks to system_health session SELECT CAST(target_data AS XML) AS deadlock_xml FROM sys.dm_xe_session_targets st JOIN sys.dm_xe_sessions s ON s.address = st.event_session_address WHERE s.name […]

Read More
SQL

SQL Server: Find Slow Queries with Query Store (No Third-Party Tools Needed)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on SQL Server: Find Slow Queries with Query Store (No Third-Party Tools Needed)

Application running slow but can’t figure out which queries are the culprits? Query Store is SQL Server’s built-in performance tracker that records everything. Enable Query Store (SQL Server 2016+): — Enable for your database ALTER DATABASE YourDatabaseName SET QUERY_STORE = ON ( OPERATION_MODE = READ_WRITE, DATA_FLUSH_INTERVAL_SECONDS = 900, INTERVAL_LENGTH_MINUTES = 60, MAX_STORAGE_SIZE_MB = 1000, QUERY_CAPTURE_MODE […]

Read More
Asp.Net Core / C#

.NET Core: Fix Memory Leaks by Understanding IDisposable and Using Patterns

- 01.02.26 | 01.02.26 - ErcanOPAK comment on .NET Core: Fix Memory Leaks by Understanding IDisposable and Using Patterns

Your .NET application’s memory usage grows infinitely? You’re probably not disposing resources properly. Here’s the complete guide. The Memory Leak – Classic Example: // WRONG: Memory leak public async Task ProcessOrdersAsync() { var dbContext = new ApplicationDbContext(); var orders = await dbContext.Orders.ToListAsync(); // Process orders… // dbContext never disposed = connection stays open = memory […]

Read More
Asp.Net Core

.NET Core: Reduce Docker Image Build Time with Layer Caching Optimization

- 01.02.26 | 01.02.26 - ErcanOPAK comment on .NET Core: Reduce Docker Image Build Time with Layer Caching Optimization

Your .NET Docker builds take 5-10 minutes every time? Improper Dockerfile layer ordering is killing your cache efficiency. Bad Dockerfile (No Cache Optimization): FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src # This invalidates cache on EVERY code change COPY . . RUN dotnet restore RUN dotnet build -c Release RUN dotnet publish -c Release -o /app/publish […]

Read More
Git

Speed Up Git Operations 10x by Cleaning Up Bloated Repository History

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Speed Up Git Operations 10x by Cleaning Up Bloated Repository History

Is ‘git clone’ taking 10 minutes? Your repository probably has bloated history from large files that were deleted years ago but still exist in Git’s object database. Diagnose the Problem: # Check repository size du -sh .git # If this is >500MB for a code project, you have bloat # Find largest objects in Git […]

Read More
Git

Recover Deleted Git Commits Even After Hard Reset (It’s Not Gone)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Recover Deleted Git Commits Even After Hard Reset (It’s Not Gone)

Accidentally did ‘git reset –hard’ and lost hours of work? Your commits aren’t deleted – they’re just orphaned. Here’s how to find them. The Magic Command – Reflog: git reflog This shows every HEAD movement in your repository, even deleted commits. Output looks like: a1b2c3d HEAD@{0}: reset: moving to HEAD~3 e4f5g6h HEAD@{1}: commit: Added user […]

Read More
Ajax / JavaScript

Handle AJAX Errors Properly: Retry Logic with Exponential Backoff

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Handle AJAX Errors Properly: Retry Logic with Exponential Backoff

Your AJAX calls fail randomly due to network hiccups or server load? Implement smart retry logic that actually works. The Problem with Basic Retry: // Bad: Immediate retry can make things worse function badRetry(url, maxAttempts) { for (let i = 0; i < maxAttempts; i++) { try { return await fetch(url); } catch (error) { […]

Read More
JavaScript

Debounce vs Throttle in JavaScript: When to Use Which (With Real Examples)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Debounce vs Throttle in JavaScript: When to Use Which (With Real Examples)

Search inputs lagging? Scroll events killing performance? Understanding debounce vs throttle is critical for responsive UIs. Debounce – Wait Until User Stops: function debounce(func, delay) { let timeoutId; return function(…args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } // Usage: Search input const searchInput = document.getElementById(‘search’); const performSearch = debounce((query) […]

Read More
HTML

Use HTML Dialog Element for Accessible Modals (Forget JavaScript Libraries)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Use HTML Dialog Element for Accessible Modals (Forget JavaScript Libraries)

Still using Bootstrap modals or custom JavaScript? The native <dialog> element handles accessibility, focus trapping, and backdrop clicks automatically. The Complete HTML: <!– The dialog element –> <dialog id=”myModal”> <form method=”dialog”> <h2>Confirm Action</h2> <p>Are you sure you want to delete this item?</p> <div class=”actions”> <button value=”cancel”>Cancel</button> <button value=”confirm” autofocus>Delete</button> </div> </form> </dialog> <!– Trigger button […]

Read More
CSS

Create Smooth Page Transitions with CSS View Transitions API (No JavaScript)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Create Smooth Page Transitions with CSS View Transitions API (No JavaScript)

Page navigation feels jarring? The new CSS View Transitions API creates native app-like transitions without a single line of JavaScript. The Basic Setup: /* Enable view transitions for all navigations */ @view-transition { navigation: auto; } /* Customize the transition */ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: 0.3s; animation-timing-function: ease-in-out; } /* Fade effect */ ::view-transition-old(root) { […]

Read More
Windows

Fix Windows 11 Slow Boot by Cleaning Up Startup Items (PowerShell Method)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Fix Windows 11 Slow Boot by Cleaning Up Startup Items (PowerShell Method)

Windows taking 2-3 minutes to reach the desktop? Your startup folder is probably cluttered with apps you don’t need launching immediately. See What’s Slowing Your Boot: # PowerShell command to list all startup programs with delay impact Get-CimInstance -ClassName Win32_StartupCommand | Select-Object Name, Command, Location, User | Format-Table -AutoSize This shows every program that auto-starts, […]

Read More
Windows

Disable Windows 11 Bloatware and Telemetry with PowerShell (Takes 2 Minutes)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Disable Windows 11 Bloatware and Telemetry with PowerShell (Takes 2 Minutes)

Fresh Windows 11 install comes with 30+ unnecessary apps and aggressive telemetry. Here’s the nuclear option to clean it all at once. The One-Script Solution: Open PowerShell as Administrator and run: # Remove bloatware apps Get-AppxPackage -AllUsers | Where-Object { $_.Name -like “*Xbox*” -or $_.Name -like “*3DViewer*” -or $_.Name -like “*Solitaire*” -or $_.Name -like “*Spotify*” […]

Read More
AI

AI Prompt: Plan the Perfect Road Trip with Hidden Gems and Time Optimization

- 01.02.26 | 01.02.26 - ErcanOPAK comment on AI Prompt: Plan the Perfect Road Trip with Hidden Gems and Time Optimization

Skip generic tourist traps and discover authentic local experiences with this comprehensive road trip planning prompt. The Ultimate Road Trip Planner Prompt: You are a travel planning expert with deep knowledge of hidden gems and local culture. Create a detailed road trip itinerary. **Trip Details:** – Start: [City/Location] – End: [City/Location] – Duration: [Number of […]

Read More
AI

AI Prompt: Debug Production Errors by Analyzing Stack Traces and Logs

- 01.02.26 | 01.02.26 - ErcanOPAK comment on AI Prompt: Debug Production Errors by Analyzing Stack Traces and Logs

Stop spending hours deciphering cryptic error messages. This prompt turns stack traces into actionable debugging steps. The Master Debugging Prompt: You are a senior software engineer debugging a production issue. Analyze the following error and provide a step-by-step debugging plan. **Error Context:** Application: [e.g., ASP.NET Core Web API] Environment: [Production/Staging] Frequency: [How often does this […]

Read More
AI

AI Prompt: Generate Production-Ready API Documentation from Code Comments

- 01.02.26 | 01.02.26 - ErcanOPAK comment on AI Prompt: Generate Production-Ready API Documentation from Code Comments

Turn scattered code comments into beautiful, structured API docs in seconds with this prompt template. The Prompt Template: You are a technical documentation expert. Analyze the following code and generate comprehensive API documentation. **Input Code:** [PASTE YOUR CODE HERE] **Output Requirements:** 1. Extract all public methods/endpoints 2. For each endpoint, document: – HTTP method and […]

Read More
Docker

Reduce Docker Image Sizes by 10x with Multi-Stage Builds

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Reduce Docker Image Sizes by 10x with Multi-Stage Builds

Your Docker image is 1.2GB when it should be 120MB? Multi-stage builds eliminate build dependencies from your final image. The Problem – Single Stage Build: FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install # Installs 300MB of dev dependencies COPY . . RUN npm run build # Creates 10MB production build CMD [“node”, […]

Read More
Kubernetes

Debug Kubernetes Pods That Keep Crashing Before Logs Disappear

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Debug Kubernetes Pods That Keep Crashing Before Logs Disappear

Your pod crashes in 2 seconds, and logs vanish before you can read them? Here’s how to catch the output before Kubernetes deletes the container. The Problem: When a pod CrashLoops, the container exits so fast that ‘kubectl logs’ shows nothing useful or “container not found” errors. By the time you run the command, Kubernetes […]

Read More
Wordpress

Recover Deleted WordPress Posts from Database (Even Without Backups)

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Recover Deleted WordPress Posts from Database (Even Without Backups)

Accidentally permanently deleted a post? If you acted within 30 days and your host hasn’t optimized the database, there’s a good chance it’s still recoverable. How WordPress “Deletes” Posts: When you empty trash, WordPress doesn’t immediately erase the post row. It updates the post_status to ‘trash’ first, then later to ‘inherit’ (for revisions). The actual […]

Read More
Wordpress

Stop WordPress Comment Spam Without Plugins Using This .htaccess Rule

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Stop WordPress Comment Spam Without Plugins Using This .htaccess Rule

Getting hundreds of spam comments daily? Here’s a plugin-free solution that blocks 95% of spam bots at the server level. The Problem: Most spam bots post comments by directly hitting your wp-comments-post.php file, bypassing your website’s front-end entirely. Anti-spam plugins catch this AFTER it reaches WordPress, wasting server resources processing garbage requests. The Solution – […]

Read More
Photoshop

Fix Photoshop Lag on High-Resolution Displays with This GPU Setting

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Fix Photoshop Lag on High-Resolution Displays with This GPU Setting

Is Photoshop stuttering on your 4K monitor while other apps run smoothly? The problem isn’t your GPU – it’s how Photoshop uses it. The Issue: Modern GPUs have multiple performance modes. Photoshop often defaults to “power saving” mode on laptops or multi-monitor setups, limiting GPU acceleration even when plugged in and running intensive edits. The […]

Read More
Photoshop

Remove Photoshop’s Annoying ‘Save As’ Cloud Dialog Forever in 3 Clicks

- 01.02.26 | 01.02.26 - ErcanOPAK comment on Remove Photoshop’s Annoying ‘Save As’ Cloud Dialog Forever in 3 Clicks

Tired of Photoshop forcing you into Creative Cloud save dialogs every single time? Here’s the permanent fix. The Frustration: Adobe changed the default ‘Save As’ behavior to push their cloud services. What used to be a simple Ctrl+Shift+S now opens a cloud upload dialog, adding 4-5 extra clicks to save files locally. The 3-Click Fix: […]

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