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

C#

C#: Use CallerArgumentExpression to Improve Validation Error Messages

- 14.02.26 - ErcanOPAK comment on C#: Use CallerArgumentExpression to Improve Validation Error Messages

Validation throwing generic ‘Value cannot be null’ messages? CallerArgumentExpression shows which argument failed. Old Generic Message: public void ProcessUser(User user) { if (user == null) throw new ArgumentNullException(nameof(user)); // Error: “user cannot be null” – not very helpful in complex code } With CallerArgumentExpression: public void ThrowIfNull(T value, [CallerArgumentExpression(“value”)] string? paramName = null) { if […]

Read More
C#

C#: Use Tuple Deconstruction in foreach for Dictionary Iteration

- 14.02.26 - ErcanOPAK comment on C#: Use Tuple Deconstruction in foreach for Dictionary Iteration

Dictionary foreach with KeyValuePair is verbose. Tuple deconstruction makes it clean. Old Verbose Way: var scores = new Dictionary { [“Alice”] = 95, [“Bob”] = 87, [“Charlie”] = 92 }; foreach (KeyValuePair kvp in scores) { Console.WriteLine($”{kvp.Key}: {kvp.Value}”); } Clean Deconstruction: foreach (var (name, score) in scores) { Console.WriteLine($”{name}: {score}”); } // Or with types: […]

Read More
C#

C#: Use var Pattern in Switch Expressions for Type Matching

- 14.02.26 - ErcanOPAK comment on C#: Use var Pattern in Switch Expressions for Type Matching

Checking object types with multiple if-else is messy. Switch expressions with type patterns are cleaner. Old If-Else Chain: object obj = GetData(); if (obj is string s) { Console.WriteLine($”String: {s.Length} chars”); } else if (obj is int i) { Console.WriteLine($”Number: {i * 2}”); } else if (obj is List list) { Console.WriteLine($”List: {list.Count} items”); } […]

Read More
SQL

SQL: Use TRY_CAST Instead of CAST to Avoid Conversion Errors

- 14.02.26 - ErcanOPAK comment on SQL: Use TRY_CAST Instead of CAST to Avoid Conversion Errors

CAST throws error on invalid data. TRY_CAST returns NULL instead – safer for user input. CAST – Throws Error: SELECT CAST(‘123’ AS INT); — Works: 123 SELECT CAST(‘abc’ AS INT); — Error: Conversion failed! — Query crashes, returns nothing TRY_CAST – Returns NULL: SELECT TRY_CAST(‘123’ AS INT); — Returns: 123 SELECT TRY_CAST(‘abc’ AS INT); — […]

Read More
SQL

SQL: Use ISNULL vs COALESCE Correctly for Best Performance

- 14.02.26 - ErcanOPAK comment on SQL: Use ISNULL vs COALESCE Correctly for Best Performance

Both replace NULL values but work differently. ISNULL is faster, COALESCE is more flexible. ISNULL – SQL Server Specific: — Takes exactly 2 arguments, returns first if not null SELECT ISNULL(MiddleName, ”) AS MiddleName FROM Users; — Faster – compiled inline — Data type from first argument COALESCE – ANSI Standard: — Takes 2+ arguments, […]

Read More
Asp.Net Core

.NET Core: Use BackgroundService for Long-Running Tasks

- 14.02.26 - ErcanOPAK comment on .NET Core: Use BackgroundService for Long-Running Tasks

Need background job in your ASP.NET app? BackgroundService is built-in – no Hangfire or Quartz needed. Create Background Service: public class EmailCleanupService : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { // Do work await CleanupOldEmails(); // Wait 1 hour await Task.Delay(TimeSpan.FromHours(1), stoppingToken); } } private async Task CleanupOldEmails() { // […]

Read More
Asp.Net Core

.NET Core: Use IConfiguration.GetValue for Type-Safe Config Reading

- 14.02.26 - ErcanOPAK comment on .NET Core: Use IConfiguration.GetValue for Type-Safe Config Reading

Parsing config strings manually is error-prone. GetValue handles conversion automatically. Manual Parsing (Error-Prone): // appsettings.json: “MaxRetries”: “3” var maxRetries = int.Parse(_config[“MaxRetries”]); // NullReferenceException if key missing! // FormatException if value is not a number! Type-Safe GetValue: var maxRetries = _config.GetValue(“MaxRetries”, defaultValue: 5); // Returns 3 if exists // Returns 5 if missing or invalid // […]

Read More
Git

Git: Use git blame -L to See Who Changed Specific Lines

- 14.02.26 - ErcanOPAK comment on Git: Use git blame -L to See Who Changed Specific Lines

Whole file blame is overwhelming. See only who changed specific lines you care about. Blame Specific Line Range: # See who changed lines 50-60 git blame -L 50,60 file.js # See who changed from line 100 to end git blame -L 100,+1000 file.js Ignore Whitespace Changes: # Ignore commits that only changed indentation git blame […]

Read More
Git

Git: Use git commit –fixup to Easily Amend Older Commits

- 14.02.26 - ErcanOPAK comment on Git: Use git commit –fixup to Easily Amend Older Commits

Found a typo in commit from 5 commits ago? –fixup marks it for automatic squashing later. Create Fixup Commit: # Find commit hash to fix git log –oneline # abc1234 Add user authentication # def5678 Add email validation ← Want to fix this # Make your fix, then: git add . git commit –fixup def5678 […]

Read More
Ajax

AJAX: Use URLSearchParams to Build Query Strings Cleanly

- 14.02.26 - ErcanOPAK comment on AJAX: Use URLSearchParams to Build Query Strings Cleanly

Manually concatenating query strings is error-prone. URLSearchParams handles encoding and formatting automatically. Messy Manual Way: const query = ‘?name=’ + encodeURIComponent(name) + ‘&email=’ + encodeURIComponent(email) + ‘&age=’ + age; fetch(‘/api/users’ + query); // Easy to forget encoding, messy to read Clean URLSearchParams Way: const params = new URLSearchParams({ name: ‘John Doe’, email: ‘john@example.com’, age: 30 […]

Read More
JavaScript

JavaScript: Use replaceAll() Instead of regex.replace() for Simple Text Replacement

- 14.02.26 - ErcanOPAK comment on JavaScript: Use replaceAll() Instead of regex.replace() for Simple Text Replacement

Replacing all occurrences with regex is overkill. replaceAll() is simpler and more readable. Old Regex Way: const text = “Hello World, Hello Universe”; const result = text.replace(/Hello/g, “Hi”); // “Hi World, Hi Universe” // Easy to mess up – forget ‘g’ flag and only first is replaced! New replaceAll() Way: const text = “Hello World, […]

Read More
HTML

HTML5: Use dialog Element for Native Modals Without JavaScript Libraries

- 14.02.26 - ErcanOPAK comment on HTML5: Use dialog Element for Native Modals Without JavaScript Libraries

Bootstrap modals require heavy JavaScript. HTML5 dialog element is native, lightweight, and fully accessible. HTML: <dialog id=”myDialog”> <h2>Modal Title</h2> <p>Modal content here</p> <button onclick=”closeDialog()”>Close</button> </dialog> <button onclick=”openDialog()”>Open Modal</button> JavaScript: function openDialog() { document.getElementById(‘myDialog’).showModal(); } function closeDialog() { document.getElementById(‘myDialog’).close(); } // Close on backdrop click myDialog.addEventListener(‘click’, (e) => { if (e.target === myDialog) myDialog.close(); }); Features: […]

Read More
CSS

CSS: Use clamp() for Responsive Font Sizes Without Media Queries

- 14.02.26 - ErcanOPAK comment on CSS: Use clamp() for Responsive Font Sizes Without Media Queries

Setting font sizes for mobile, tablet, desktop with media queries is tedious. clamp() does it automatically. Old Way – Multiple Media Queries: h1 { font-size: 24px; } @media (min-width: 768px) { h1 { font-size: 32px; } } @media (min-width: 1200px) { h1 { font-size: 48px; } } New Way – One Line: h1 { font-size: […]

Read More
Windows

Windows 11: Use Quick Settings to Toggle Wi-Fi, Bluetooth Without Opening Settings

- 14.02.26 - ErcanOPAK comment on Windows 11: Use Quick Settings to Toggle Wi-Fi, Bluetooth Without Opening Settings

Opening Settings app to toggle Wi-Fi is slow. Quick Settings panel gives instant access to common toggles. Open Quick Settings: Click Wi-Fi/Sound/Battery icons in system tray Or press Win + A Quick Toggles Available: Wi-Fi on/off Bluetooth on/off Airplane mode Battery saver Night light Focus assist Screen brightness slider Volume slider Customize: Click pencil icon […]

Read More
Windows

Windows 11: Use God Mode to Access All Settings in One Folder

- 14.02.26 - ErcanOPAK comment on Windows 11: Use God Mode to Access All Settings in One Folder

Tired of hunting through Settings app? God Mode creates folder with every Windows setting in one place. Enable God Mode: 1. Right-click Desktop → New → Folder 2. Name it exactly: GodMode.{ED7BA470-8E54-465E-825C-99712043E01C} 3. Press Enter Folder icon changes and opens to show 300+ settings organized by category! What’s Inside: Administrative Tools Backup and Restore Color […]

Read More
AI

AI Prompt: Create Excel Formulas from Description of What You Want to Calculate

- 14.02.26 - ErcanOPAK comment on AI Prompt: Create Excel Formulas from Description of What You Want to Calculate

Excel formulas syntax confusing? Describe what you want in plain English, get working formula. The Prompt: Create Excel formula for: I have: – Column A: Product names – Column B: Prices – Column C: Quantities sold I want in Column D: Total revenue (price × quantity), but only for products starting with “Pro-” If quantity […]

Read More
AI

AI Prompt: Generate SQL Queries from Plain English Descriptions

- 14.02.26 - ErcanOPAK comment on AI Prompt: Generate SQL Queries from Plain English Descriptions

Know what data you need but struggling with SQL syntax? AI writes the query for you. The Prompt: Write SQL query for this: Database: Ecommerce Tables: Users (id, name, email), Orders (id, user_id, total, created_at) I need: Top 10 customers by total order value in last 30 days Also explain what each part does. AI […]

Read More
AI

AI Prompt: Debug Code by Explaining Error Message in Plain English

- 14.02.26 - ErcanOPAK comment on AI Prompt: Debug Code by Explaining Error Message in Plain English

Cryptic error messages confusing you? AI explains what they mean and how to fix them. The Prompt: I got this error in [language/framework]: [Paste full error message and stack trace] Please explain: 1. What this error means in plain English 2. What likely caused it 3. How to fix it with code example 4. How […]

Read More
Docker

Docker: UseHealthCheck to Auto-Restart Unhealthy Containers

- 14.02.26 - ErcanOPAK comment on Docker: UseHealthCheck to Auto-Restart Unhealthy Containers

Container running but app inside crashed? Add HEALTHCHECK to auto-detect and restart failed containers. Add to Dockerfile: FROM node:18 WORKDIR /app COPY . . # Check if app responds on port 3000 HEALTHCHECK –interval=30s –timeout=3s –retries=3 \ CMD curl -f http://localhost:3000/health || exit 1 CMD [“node”, “server.js”] What Happens: Every 30 seconds, Docker runs health […]

Read More
Kubernetes

Kubernetes: Use kubectl top to Monitor Real-Time Resource Usage

- 14.02.26 - ErcanOPAK comment on Kubernetes: Use kubectl top to Monitor Real-Time Resource Usage

Want to see CPU/Memory usage without installing monitoring tools? kubectl top shows real-time stats. Node Resource Usage: kubectl top nodes # Output: # NAME CPU MEMORY # node-1 45% 2.5Gi # node-2 23% 1.8Gi Pod Resource Usage: kubectl top pods # Or specific namespace: kubectl top pods -n production # Sort by CPU: kubectl top […]

Read More
Wordpress

WordPress: Show Different Menus to Logged-In vs Logged-Out Users

- 14.02.26 - ErcanOPAK comment on WordPress: Show Different Menus to Logged-In vs Logged-Out Users

Want different navigation for members vs visitors? WordPress has built-in conditional menu display. Create Two Menus: Appearance → Menus 1. “Public Menu” (for visitors) 2. “Member Menu” (for logged-in users) Add to functions.php: function conditional_menu() { if (is_user_logged_in()) { wp_nav_menu(array(‘theme_location’ => ‘member-menu’)); } else { wp_nav_menu(array(‘theme_location’ => ‘public-menu’)); } } In header.php, replace: <?php wp_nav_menu(); […]

Read More
Wordpress

WordPress: Add Custom Login Logo Without Plugin Using functions.php

- 14.02.26 - ErcanOPAK comment on WordPress: Add Custom Login Logo Without Plugin Using functions.php

Want branded login page? Add custom logo with a few lines of code – no plugin needed. Add to functions.php: function custom_login_logo() { echo ‘<style type=”text/css”> #login h1 a { background-image: url(‘ . get_stylesheet_directory_uri() . ‘/images/logo.png); background-size: contain; width: 300px; height: 100px; } </style>’; } add_action(‘login_enqueue_scripts’, ‘custom_login_logo’); Change Logo URL: function custom_login_url() { return home_url(); […]

Read More
Photoshop

Photoshop: Use Blend If to Remove White/Black Backgrounds Without Selecting

- 14.02.26 - ErcanOPAK comment on Photoshop: Use Blend If to Remove White/Black Backgrounds Without Selecting

Magic wand selection leaving halos? Blend If removes backgrounds based on brightness – no selection needed. Remove White Background: 1. Double-click layer to open Layer Style 2. Find “Blend If” section at bottom 3. Drag This Layer white slider left 4. White pixels become transparent! For Smoother Transition: Hold Alt while dragging to split slider […]

Read More
Photoshop

Photoshop: Use Layer Comps to Save Multiple Design Variations in One File

- 14.02.26 - ErcanOPAK comment on Photoshop: Use Layer Comps to Save Multiple Design Variations in One File

Creating multiple mockup versions in separate files? Layer Comps saves different layer visibility/position states in one PSD. Create Layer Comp: Window → Layer Comps → Click ‘Create New Layer Comp’ icon Choose What to Save: Visibility (which layers are on/off) Position (where layers are located) Appearance (layer styles) Use Case Example: Designing website header with […]

Read More
Visual Studio

Visual Studio: Use Multi-Caret Editing to Change Multiple Lines at Once

- 14.02.26 - ErcanOPAK comment on Visual Studio: Use Multi-Caret Editing to Change Multiple Lines at Once

Editing same text on multiple lines one by one is tedious. Multi-caret lets you edit all simultaneously. Add Carets: Hold Alt + Click where you want additional cursors Or Select Multiple: 1. Select text 2. Press Ctrl+D repeatedly to select next occurrence 3. Type to change all at once Example: // Change all ‘firstName’ to […]

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