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: May 26, 2026

C#

C#: LINQ Performance Tips to Avoid Common Pitfalls

- 26.05.26 - ErcanOPAK comment on C#: LINQ Performance Tips to Avoid Common Pitfalls

⚡ LINQ is Beautiful, But Know Its Cost LINQ makes code readable, but hidden performance traps exist. Multiple enumerations, wrong collection types, predicate order — fix them all. ❌ Multiple Enumeration var filtered = items.Where(x => x.IsActive); // Executes query 3 times! var count = filtered.Count(); // Query executes var first = filtered.First(); // Query […]

Read More
C#

C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues

- 26.05.26 - ErcanOPAK comment on C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues

⚡ Async All the Way Up Async/await is powerful but dangerous. Deadlocks, thread pool starvation, sync-over-async — avoid common pitfalls with these patterns. ❌ Deadlock Pattern // UI or ASP.NET Context – DEADLOCK! public void Button_Click(object sender, EventArgs e) { var result = GetDataAsync().Result; // 💀 DEADLOCK } public async Task GetDataAsync() { await Task.Delay(1000); […]

Read More
SQL

SQL: Clustered vs Non-Clustered Indexes Explained

- 26.05.26 - ErcanOPAK comment on SQL: Clustered vs Non-Clustered Indexes Explained

📚 The Phone Book vs The Library Catalog Clustered indexes physically order data (like phone book). Non-clustered indexes point to data (like library catalog). Choose wisely. 📖 Clustered Index Only one per table Physically reorders data Fast for range queries (BETWEEN, >,

Read More
Asp.Net Core

.NET Core: Understand Scoped, Transient, and Singleton Services

- 26.05.26 - ErcanOPAK comment on .NET Core: Understand Scoped, Transient, and Singleton Services

🔄 One Instance vs One Per Request Choosing wrong lifecycle = bugs, memory leaks, or poor performance. Transient, Scoped, Singleton — each has its purpose. 🟢 Transient services.AddTransient<IMyService, MyService>(); Created every time requested. Best for lightweight, stateless services. 🟡 Scoped services.AddScoped<IMyService, MyService>(); One instance per HTTP request. Best for DbContext, request-scoped data. 🔴 Singleton services.AddSingleton<IMyService, […]

Read More
Git

Git: Use Git Stash to Temporarily Save Uncommitted Changes

- 26.05.26 - ErcanOPAK comment on Git: Use Git Stash to Temporarily Save Uncommitted Changes

📦 Shelve Your Work in Progress Half-finished feature? Urgent bug on another branch? Git stash saves your uncommitted changes, cleans working directory, restores later. # Save changes to stash git stash # Save with message git stash save “WIP: login feature” # List all stashes git stash list # stash@{0}: On main: WIP: login feature […]

Read More
Ajax

Ajax: Why Axios is Better Than Fetch for HTTP Requests

- 26.05.26 - ErcanOPAK comment on Ajax: Why Axios is Better Than Fetch for HTTP Requests

🌐 Fetch is Good, Axios is Better Fetch requires response.ok check? No automatic JSON parsing? Axios handles errors, transforms JSON, supports progress, and works in Node.js. ❌ Fetch (More Boilerplate) try { const res = await fetch(url); if (!res.ok) throw new Error(‘HTTP error’); const data = await res.json(); } catch (err) { console.error(err); } ✅ […]

Read More
JavaScript

JavaScript: Use Optional Chaining (?.) to Avoid Cannot Read Property of Undefined

- 26.05.26 - ErcanOPAK comment on JavaScript: Use Optional Chaining (?.) to Avoid Cannot Read Property of Undefined

🔗 Stop the Cannot Read Property Error Optional chaining (?.) safely accesses nested properties. No more Cannot read property ‘x’ of undefined. ❌ Old Way (Crash-prone) // 💥 CRASH if user or address is undefined const city = user.address.city; // Verbose fix let city = ‘Unknown’; if (user && user.address) { city = user.address.city; } […]

Read More
HTML

HTML: Use Picture Element and srcset for Responsive Images

- 26.05.26 - ErcanOPAK comment on HTML: Use Picture Element and srcset for Responsive Images

🖼️ Serve the Right Image to Every Device Mobile users downloading 4K images? Picture element and srcset serve different images based on screen size, resolution, and format support. 📱 srcset: Different Resolutions <img src=”image-800.jpg” srcset=”image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w, image-1600.jpg 1600w” sizes=”(max-width: 600px) 400px, (max-width: 1200px) 800px, 1200px” alt=”Responsive image”> 🎨 Picture: Art Direction […]

Read More
CSS

CSS: Use Container Queries for Component-Level Responsive Design

- 26.05.26 - ErcanOPAK comment on CSS: Use Container Queries for Component-Level Responsive Design

📦 Components That Adapt to Their Parent Media queries look at viewport. Container queries look at parent container size. Finally, truly reusable responsive components. ❌ Old Way (Media Queries) .card { display: flex; flex-direction: column; } @media (min-width: 800px) { .card { flex-direction: row; /* Changes everywhere */ } } ✅ Container Queries .sidebar { […]

Read More
Windows

Windows 11: Master Snap Layouts and Snap Groups for Multitasking

- 26.05.26 - ErcanOPAK comment on Windows 11: Master Snap Layouts and Snap Groups for Multitasking

🪟 The Best Windows Feature You’re Not Using Manually resizing windows? Snap Layouts tile windows instantly. Snap Groups remember your layouts. Task switching just got superpowers. 🖱️ Snap Layouts (Win + Z) Hover over maximize button or press Win + Z → Choose layout → Snap windows into zones. Available layouts: ┌─────────┬─────────┐ ┌─────────────┐ │ │ […]

Read More
AI

AI Prompt: Generate Comprehensive Code Documentation from Source Files

- 26.05.26 - ErcanOPAK comment on AI Prompt: Generate Comprehensive Code Documentation from Source Files

📚 AI Writes Your Docs Nobody reads undocumented code. Nobody writes docs. AI documentation generator creates README, API docs, and inline comments from your codebase. 📝 The Documentation Prompt Generate comprehensive documentation for this code: [paste code here] Include: 1. Overview: What does this module/class do? 2. Installation/setup instructions 3. API Reference: All public methods […]

Read More
Docker

Docker: Volumes vs Bind Mounts for Persistent Data Storage

- 26.05.26 - ErcanOPAK comment on Docker: Volumes vs Bind Mounts for Persistent Data Storage

💾 Don’t Lose Your Data Container deleted = data gone? Volumes and bind mounts persist data outside containers. Database, uploads, logs survive container restarts. 📦 Volumes (Managed by Docker) # Create volume docker volume create mydata # Use volume docker run -v mydata:/app/data myapp # List volumes docker volume ls # Inspect volume docker volume […]

Read More
Kubernetes

Kubernetes: Use Init Containers for Setup Tasks Before App Starts

- 26.05.26 - ErcanOPAK comment on Kubernetes: Use Init Containers for Setup Tasks Before App Starts

⏳ Wait for Database, Then Start App needs database schema? Cache warmup? File permissions? Init containers run to completion before your main container starts. apiVersion: v1 kind: Pod metadata: name: my-app-pod spec: initContainers: – name: init-myservice image: busybox:1.28 command: [‘sh’, ‘-c’, ‘until nslookup myservice; do echo waiting; sleep 2; done;’] – name: init-db image: busybox:1.28 […]

Read More
Wordpress

WordPress: Use Transients API to Cache Expensive Queries and API Calls

- 26.05.26 - ErcanOPAK comment on WordPress: Use Transients API to Cache Expensive Queries and API Calls

⚡ Speed Up Slow Queries External API on every page load? Complex database query killing performance? Transients API caches data with expiration. Page loads in milliseconds. // Set transient with 12-hour expiration $weather_data = get_weather_api(); set_transient(‘weather_data’, $weather_data, 12 * HOUR_IN_SECONDS); // Get cached data $cached_data = get_transient(‘weather_data’); if (false === $cached_data) { // Cache expired […]

Read More
Photoshop

Photoshop: Master the Pen Tool for Precise Selections and Vector Paths

- 26.05.26 - ErcanOPAK comment on Photoshop: Master the Pen Tool for Precise Selections and Vector Paths

✒️ Cut Out Anything Perfectly Magic Wand not cutting it? Pen Tool creates ultra-precise vector paths. Once you learn it, you’ll never use Lasso again. 📌 Shortcuts P → Pen Tool Click → Straight line anchor point Click + Drag → Curve (bezier handles) Ctrl/Cmd → Direct Selection (move points) Alt/Opt → Convert Point Tool […]

Read More
Visual Studio

Visual Studio: Use Conditional Breakpoints and Tracepoints for Smarter Debugging

- 26.05.26 - ErcanOPAK comment on Visual Studio: Use Conditional Breakpoints and Tracepoints for Smarter Debugging

🎯 Stop Wasting Time on Loops Break on iteration 1000? Log values without stopping? Conditional breakpoints and tracepoints save hours of debugging. Conditional Breakpoints Right-click red breakpoint dot → Conditions // Break only when specific condition is true for (int i = 0; i < 10000; i++) { // Breakpoint condition: i == 5000 ProcessItem(i); […]

Read More
C#

C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

- 26.05.26 - ErcanOPAK comment on C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

🛡️ No More NullReferenceException NullReferenceException killing your app? Can’t tell if variable can be null? Nullable reference types (C# 8+) make nullability explicit. Compiler warns about potential null errors. <PropertyGroup> <Nullable>enable</Nullable> </PropertyGroup> <!– Or in specific files –> #nullable enable // At top of .cs file ❌ Before (Runtime crash) public string GetName(int id) { […]

Read More
C#

C#: Use Record Types for Immutable Data Objects

- 26.05.26 - ErcanOPAK comment on C#: Use Record Types for Immutable Data Objects

📦 Value Objects Made Easy DTOs with 50 lines of boilerplate? Equals(), GetHashCode(), ToString()? Record types (C# 9+) are immutable, value-based, with auto-generated methods. One line replaces 50. ❌ Traditional Class (40+ lines) public class Person { public string Name { get; init; } public int Age { get; init; } public Person(string name, int […]

Read More
SQL

SQL: Use Window Functions for Advanced Analytical Queries

- 26.05.26 - ErcanOPAK comment on SQL: Use Window Functions for Advanced Analytical Queries

📊 SQL Superpowers Need row numbers? Running totals? Rankings? Window functions perform calculations across table rows without GROUP BY. Game-changing for analytics. ROW_NUMBER() – Assign Row Numbers — Simple row number SELECT ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num, name, salary, department FROM employees; — Result: — row_num | name | salary | department […]

Read More
Asp.Net Core

.NET Core: Use Minimal APIs for Lightweight HTTP Services

- 26.05.26 - ErcanOPAK comment on .NET Core: Use Minimal APIs for Lightweight HTTP Services

🚀 APIs in 10 Lines of Code MVC Controllers for simple API? Overkill. Minimal APIs (.NET 6+) create HTTP endpoints with minimal ceremony. Perfect for microservices, simple APIs. ❌ Traditional Controller [ApiController] [Route(“api/[controller]”)] public class UsersController : ControllerBase { [HttpGet] public async Task Get() { return await _service.GetAllAsync(); } [HttpPost] public async Task Post(User user) […]

Read More
Git

Git: Use Interactive Rebase to Clean Up Commit History Before Merge

- 26.05.26 - ErcanOPAK comment on Git: Use Interactive Rebase to Clean Up Commit History Before Merge

🔧 Rewrite Git History 50 commits saying ‘fix typo’, ‘WIP’, ‘oops’? Messy history before PR? Interactive rebase lets you squash, reword, reorder commits. Clean history like a pro. 📋 The Messy History Problem git log –oneline a1b2c3d fix typo d4e5f6g WIP g7h8i9j oops forgot file j1k2l3m fix typo again m4n5o6p actually fix the bug p7q8r9s […]

Read More
Ajax

Ajax: Use Fetch API Instead of XMLHttpRequest for Clean Async Requests

- 26.05.26 - ErcanOPAK comment on Ajax: Use Fetch API Instead of XMLHttpRequest for Clean Async Requests

🌐 Modern Ajax Made Simple XMLHttpRequest? 10 lines for simple GET? Callback hell? Fetch API is promise-based, clean syntax, built-in JSON parsing. Modern Ajax the right way. ❌ XMLHttpRequest (10+ lines) const xhr = new XMLHttpRequest(); xhr.open(‘GET’, ‘https://api.example.com/users’); xhr.onload = function() { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); console.log(data); } else { […]

Read More
JavaScript

JavaScript: Use Destructuring to Extract Values Cleanly

- 26.05.26 - ErcanOPAK comment on JavaScript: Use Destructuring to Extract Values Cleanly

📦 Unpack Like Python Accessing nested properties? const x = obj.prop.nested? Verbose. Destructuring extracts values from objects and arrays elegantly. One line replaces five. ❌ Old Way const name = user.name; const age = user.age; const email = user.email; ✅ Destructuring const { name, age, email } = user; 🎯 Advanced Patterns // Rename variables […]

Read More
HTML

HTML: Use Semantic HTML5 Elements for Better SEO and Accessibility

- 26.05.26 - ErcanOPAK comment on HTML: Use Semantic HTML5 Elements for Better SEO and Accessibility

📝 Meaningful HTML Markup Everything is a div? Search engines confused, screen readers lost. Semantic HTML5 uses elements that describe their purpose: <header>, <nav>, <article>, <section>. Better SEO, better accessibility. ❌ Div Soup <div class=”header”> <div class=”nav”> <div class=”nav-item”>Home</div> </div> </div> <div class=”main”> <div class=”content”>…</div> </div> ✅ Semantic HTML5 <header> <nav> <a href=”/”>Home</a> </nav> </header> […]

Read More
CSS

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

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

📱 Responsive Grids, Zero Media Queries Media queries for every breakpoint? Tedious. Grid auto-fit/auto-fill creates responsive layouts automatically. Items reflow based on space available. The Magic Formula .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; } /* That’s it! Fully responsive without media queries Items wrap automatically based on available space */ auto-fit […]

Read More
Windows

Windows 11: Install PowerToys for 20+ Productivity Features

- 26.05.26 - ErcanOPAK comment on Windows 11: Install PowerToys for 20+ Productivity Features

⚡ Windows Superpowers Windows missing features? Microsoft’s PowerToys adds FancyZones, color picker, bulk rename, image resize, always-on-top, and 15+ more tools. Free, official, essential. Install PowerToys # Method 1: Microsoft Store (easiest) winget install Microsoft.PowerToys # Method 2: GitHub Release # Download from: https://github.com/microsoft/PowerToys/releases # After install, PowerToys runs in system tray # Right-click tray […]

Read More
AI

AI Prompt: Use AI as Senior Code Reviewer for Pull Requests

- 26.05.26 - ErcanOPAK comment on AI Prompt: Use AI as Senior Code Reviewer for Pull Requests

👨‍💻 AI Senior Developer at Your Service No senior dev for code review? AI can spot bugs, security issues, performance problems. Acts like experienced tech lead reviewing your code. The Code Review Prompt Act as a senior software engineer conducting a thorough code review. Review this code for: 1. Bugs and logical errors 2. Security […]

Read More
Docker

Docker: Use Multi-Stage Builds to Reduce Image Size by 90%

- 26.05.26 - ErcanOPAK comment on Docker: Use Multi-Stage Builds to Reduce Image Size by 90%

📦 Tiny Production Images 1.5GB Docker image? Build tools in production? Security nightmare. Multi-stage builds create small, secure images. Only runtime files shipped. ❌ Single Stage (1.2GB) FROM node:18 WORKDIR /app COPY . . RUN npm install RUN npm run build CMD [“node”, “dist/server.js”] ✅ Multi-Stage (150MB) FROM node:18 AS builder WORKDIR /app COPY . […]

Read More
Kubernetes

Kubernetes: Use HPA to Auto-Scale Pods Based on CPU/Memory

- 26.05.26 - ErcanOPAK comment on Kubernetes: Use HPA to Auto-Scale Pods Based on CPU/Memory

📈 Auto-Scale Based on Load Fixed 3 replicas? CPU spikes, users wait. Traffic drops, you waste money. HPA (Horizontal Pod Autoscaler) scales pods automatically based on metrics. How HPA Works # deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: web-app spec: replicas: 2 template: spec: containers: – name: app image: myapp:latest resources: requests: cpu: 100m # […]

Read More
Wordpress

WordPress: Use WP-CLI for Command-Line Site Management

- 26.05.26 - ErcanOPAK comment on WordPress: Use WP-CLI for Command-Line Site Management

⚡ Manage WordPress from Terminal Clicking through admin for every site update? Slow. WP-CLI lets you install plugins, update core, manage users—all from command line. 10x faster. Install WP-CLI # Download curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar # Make executable chmod +x wp-cli.phar # Move to PATH sudo mv wp-cli.phar /usr/local/bin/wp # Test wp –info 🚀 Essential Commands […]

Read More
Page 1 of 2
1 2 Next »

Posts pagination

1 2 Next »
May 2026
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031
« Mar   Jun »

Most Viewed Posts

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

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files
  • Ajax: Add Custom Headers to Fetch Requests
  • JavaScript: Use console.table to Display Arrays as Tables
  • HTML: Use Spellcheck Attribute to Enable Browser Spell Check
  • CSS: Use user-select to Prevent Text Selection
  • Windows 11: Use Snipping Tool for Instant Screenshots

Most Viewed Posts

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

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files

Social

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