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

C#

C#: Use Collection Expressions for Cleaner Array and List Initialization

- 30.05.26 - ErcanOPAK comment on C#: Use Collection Expressions for Cleaner Array and List Initialization

[] Instead of new List { } Python has [1,2,3]. C# finally gets collection expressions! Same syntax for arrays, lists, spans. More readable, less typing. โŒ Old Way (Verbose) int[] arr = new int[] { 1, 2, 3 }; List list = new List { “a”, “b”, “c” }; Span span = new int[] { […]

Read More
C#

C#: Use Primary Constructors to Reduce Boilerplate (.NET 8)

- 30.05.26 - ErcanOPAK comment on C#: Use Primary Constructors to Reduce Boilerplate (.NET 8)

๐ŸŽฏ Dependency Injection Just Got Cleaner private readonly ILogger _logger; + constructor = 4 lines. Primary constructors do it in 1 line. C# 12 changes everything. โŒ Old Way (12 lines) public class OrderService { private readonly IOrderRepository _repository; private readonly ILogger _logger; private readonly IEmailService _emailService; public OrderService( IOrderRepository repository, ILogger logger, IEmailService emailService) […]

Read More
SQL

SQL: Use UPSERT (INSERT ON CONFLICT) for Insert or Update

- 30.05.26 - ErcanOPAK comment on SQL: Use UPSERT (INSERT ON CONFLICT) for Insert or Update

๐Ÿ”„ One Query: Insert or Update Check if exists โ†’ Update or Insert = 2 queries. UPSERT does it in one. Faster, atomic, race-condition free. ๐Ÿ“ PostgreSQL (ON CONFLICT) — Basic UPSERT (update if conflict) INSERT INTO users (id, name, email, last_login) VALUES (1, ‘Alice’, ‘alice@example.com’, NOW()) ON CONFLICT (id) DO UPDATE SET name = […]

Read More
Asp.Net Core

.NET Core: Implement API Versioning Without Breaking Clients

- 30.05.26 - ErcanOPAK comment on .NET Core: Implement API Versioning Without Breaking Clients

๐Ÿ”„ V1, V2, V3 โ€” All Running Simultaneously Change API = break clients. API versioning lets you run multiple versions. Old clients stay on V1, new clients use V2. No downtime. ๐Ÿ“ Setup Versioning dotnet add package Asp.Versioning.Mvc dotnet add package Asp.Versioning.Mvc.ApiExplorer // Program.cs builder.Services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); options.AssumeDefaultVersionWhenUnspecified = true; […]

Read More
Git

Git: Create Custom Aliases for Frequently Used Commands

- 30.05.26 | 30.05.26 - ErcanOPAK comment on Git: Create Custom Aliases for Frequently Used Commands

โšก git st โ†’ git status Typing ‘git status –short –branch’ every time? Git aliases create shortcuts. Save keystrokes, create powerful composite commands. ๐Ÿ“ Create Aliases # Basic aliases git config –global alias.st status git config –global alias.co checkout git config –global alias.br branch git config –global alias.ci commit git config –global alias.df diff git […]

Read More
Ajax

Ajax: Use EventSource for Real-Time Server Push (Simpler than WebSockets)

- 30.05.26 - ErcanOPAK comment on Ajax: Use EventSource for Real-Time Server Push (Simpler than WebSockets)

๐Ÿ“ก One-Way Real-Time Updates Need live updates but not bidirectional? EventSource (SSE) is simpler than WebSockets. Auto-reconnects. Built-in retry. Perfect for dashboards, notifications. ๐Ÿ“ Client-Side const eventSource = new EventSource(‘/api/events’); // Listen for messages eventSource.onmessage = (event) => { const data = JSON.parse(event.data); console.log(‘Update:’, data); updateUI(data); }; // Listen for specific event type eventSource.addEventListener(‘notification’, (event) […]

Read More
JavaScript

JavaScript: Use Object.groupBy() to Group Arrays Without Lodash

- 30.05.26 - ErcanOPAK comment on JavaScript: Use Object.groupBy() to Group Arrays Without Lodash

๐Ÿ“Š Native GroupBy Finally Arrived _.groupBy() required Lodash. Object.groupBy() is now native. Group arrays by any criteria. No more manual reduce hacks. ๐Ÿ“ Basic Usage const users = [ { name: ‘Alice’, role: ‘admin’ }, { name: ‘Bob’, role: ‘user’ }, { name: ‘Charlie’, role: ‘admin’ }, { name: ‘Diana’, role: ‘user’ } ]; // […]

Read More
HTML

HTML: Use Input Pattern Attribute for Client-Side Validation

- 30.05.26 - ErcanOPAK comment on HTML: Use Input Pattern Attribute for Client-Side Validation

โœ”๏ธ Validate Without JavaScript pattern attribute validates input with regex. Built-in error messages, no JS needed. Works on mobile keyboards too. ๐Ÿ“ Common Patterns <!– US Phone Number –> <input type=”tel” pattern=”[0-9]{3}-[0-9]{3}-[0-9]{4}” placeholder=”123-456-7890″> <!– Zip Code (US) –> <input type=”text” pattern=”[0-9]{5}(-[0-9]{4})?” placeholder=”12345″> <!– Username (letters, numbers, underscore) –> <input type=”text” pattern=”[A-Za-z0-9_]{3,20}” title=”3-20 characters: letters, numbers, […]

Read More
CSS

CSS: Use Aspect Ratio for Perfectly Sized Boxes

- 30.05.26 - ErcanOPAK comment on CSS: Use Aspect Ratio for Perfectly Sized Boxes

๐Ÿ“ No More Padding Hack Remember padding-bottom: 56.25% for 16:9? aspect-ratio property does it natively. Videos, images, cards โ€” perfect proportions. ๐Ÿ“ Basic Usage /* Square */ .square { aspect-ratio: 1 / 1; background: blue; width: 200px; } /* 16:9 video container */ .video-container { aspect-ratio: 16 / 9; background: black; width: 100%; } /* […]

Read More
Windows

Windows 11: Use Focus Assist to Block Notifications While Working

- 30.05.26 - ErcanOPAK comment on Windows 11: Use Focus Assist to Block Notifications While Working

๐Ÿ”• Silence the Distractions Every Slack ping breaks flow. Focus Assist hides all notifications during focus time. Only priority contacts get through. ๐Ÿ”ง Enable Focus Assist Settings โ†’ System โ†’ Focus Assist Three modes: – Off: All notifications (default) – Priority only: Only from specified contacts/apps – Alarms only: No notifications except alarms Quick toggle: […]

Read More
AI

AI Prompt: Generate Unit Tests from Function Signatures

- 30.05.26 - ErcanOPAK comment on AI Prompt: Generate Unit Tests from Function Signatures

๐Ÿงช AI Writes Your Tests Writing tests is tedious. AI generates unit tests from function signatures. Edge cases, error handling, happy paths โ€” all covered. ๐Ÿ“ The Prompt Generate comprehensive unit tests for this function: [Paste function code here] Testing framework: [Jest / pytest / NUnit / xUnit] Language: [JavaScript / Python / C# / […]

Read More
Docker

Docker: Use Prune Commands to Reclaim Gigabytes of Disk Space

- 30.05.26 - ErcanOPAK comment on Docker: Use Prune Commands to Reclaim Gigabytes of Disk Space

๐Ÿ—‘๏ธ Your Disk is Full of Dead Containers Stopped containers, unused images, unused volumes โ€” they eat disk space. docker system prune cleans everything in one command. ๐Ÿ“ Prune Commands # Clean everything (containers, images, networks, build cache) docker system prune -a –volumes # Stop and remove all stopped containers docker container prune # Remove […]

Read More
Kubernetes

Kubernetes: Use Resource Quotas to Prevent One Namespace from Draining Cluster

- 30.05.26 - ErcanOPAK comment on Kubernetes: Use Resource Quotas to Prevent One Namespace from Draining Cluster

๐Ÿ“Š Don’t Let One Team Hog All Resources One namespace uses all CPU? Others starve. Resource quotas limit total CPU, memory, storage per namespace. Fair sharing for multi-tenant clusters. ๐Ÿ“ Basic Quota apiVersion: v1 kind: ResourceQuota metadata: name: namespace-quota namespace: development spec: hard: requests.cpu: “4” requests.memory: “8Gi” limits.cpu: “8” limits.memory: “16Gi” persistentvolumeclaims: “10” pods: “20” […]

Read More
Wordpress

WordPress: Create Custom Widget Areas with register_sidebar()

- 30.05.26 - ErcanOPAK comment on WordPress: Create Custom Widget Areas with register_sidebar()

๐Ÿ“ฆ Drag-and-Drop Everywhere Widgets only in sidebar? Not anymore. register_sidebar() creates widget areas anywhere: header, footer, after content, before comments. ๐Ÿ“ Register Sidebars // functions.php function custom_widget_areas() { // Footer widget area register_sidebar(array( ‘name’ => ‘Footer Widget Area’, ‘id’ => ‘footer-widgets’, ‘description’ => ‘Appears at the bottom of every page’, ‘before_widget’ => ”, ‘after_widget’ => […]

Read More
Photoshop

Photoshop: Use Layer Groups to Organize Complex Designs

- 30.05.26 - ErcanOPAK comment on Photoshop: Use Layer Groups to Organize Complex Designs

๐Ÿ“ 100 Layers? Collapse Them! Scrolling through endless layers is a nightmare. Layer Groups organize related layers. Collapse, rename, color-code, apply effects to entire group. ๐Ÿ“ Create Layer Group Method 1: Layer โ†’ New โ†’ Group (Ctrl + G) Method 2: Select multiple layers โ†’ Ctrl + G Method 3: Drag layers onto folder icon […]

Read More
Visual Studio

Visual Studio: Navigate Backward (Ctrl + -) Like a Time Machine

- 30.05.26 - ErcanOPAK comment on Visual Studio: Navigate Backward (Ctrl + -) Like a Time Machine

โช Ctrl + – Takes You Back to Where You Were Jumped to definition? Scrolled away? Navigate Backward (Ctrl + -) returns to your previous cursor position. Like a browser back button for your code. โŒจ๏ธ Shortcuts Ctrl + – โ†’ Navigate Backward (go to previous cursor location) Ctrl + Shift + – โ†’ Navigate […]

Read More
C#

C#: Use Interpolated String Handler for High-Performance Logging

- 30.05.26 - ErcanOPAK comment on C#: Use Interpolated String Handler for High-Performance Logging

โšก Zero Allocation Until You Log Logging with string interpolation allocates memory even when log level is off. Interpolated string handlers defer formatting until needed. โŒ Regular Interpolation (Always Allocates) // Even if log level is Error and this is Debug // string is still allocated! _logger.LogDebug($”User {userId} logged in at {DateTime.Now}”); // 2 allocations: […]

Read More
C#

C#: Use Throw Helpers for Concise Null Checks (.NET 6+)

- 30.05.26 - ErcanOPAK comment on C#: Use Throw Helpers for Concise Null Checks (.NET 6+)

๐ŸŽฏ One Line Null Check if (arg == null) throw new ArgumentNullException(nameof(arg)); is so 2019. Throw helpers do it in one line. Less code, fewer bugs. โŒ Old Way (4 lines) public void Process(string name, int? age) { if (name == null) throw new ArgumentNullException(nameof(name)); if (age == null) throw new ArgumentNullException(nameof(age)); // Logic here […]

Read More
SQL

SQL: Use Window Frame Clauses for Running Totals and Moving Averages

- 30.05.26 - ErcanOPAK comment on SQL: Use Window Frame Clauses for Running Totals and Moving Averages

๐Ÿ“Š ROWS BETWEEN Is the Secret Sauce Running total? Moving average? Cumulative sum? Window frame clauses define exactly which rows to include. Powerful analytics in pure SQL. ๐Ÿ“ Running Total (Cumulative Sum) SELECT order_date, amount, SUM(amount) OVER ( ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_total FROM orders; — UNBOUNDED […]

Read More
Asp.Net Core

.NET Core: Use Output Caching to Cache Entire API Responses

- 30.05.26 - ErcanOPAK comment on .NET Core: Use Output Caching to Cache Entire API Responses

โšก 1000x Faster with One Attribute Same endpoint called repeatedly? Database query every time? Output caching stores HTTP responses. One line of code, huge performance. ๐Ÿ”ง Setup (.NET 7+) // Program.cs builder.Services.AddOutputCache(); app.UseOutputCache(); // Controller [ApiController] [Route(“api/[controller]”)] public class ProductsController : ControllerBase { [HttpGet] [OutputCache(Duration = 60)] // Cache for 60 seconds public async Task […]

Read More
Git

Git: Use Git Grep to Search History Faster Than grep

- 30.05.26 - ErcanOPAK comment on Git: Use Git Grep to Search History Faster Than grep

๐Ÿ” Search Only Tracked Files, Faster grep searches everything, including .git folder. git grep searches only tracked files. Respects .gitignore. Much faster. ๐Ÿ“ Basic Search # Search for word in tracked files git grep “functionName” # Search with line numbers git grep -n “TODO” # Search with context (2 lines before/after) git grep -B 2 […]

Read More
Ajax

Ajax: Use Web Workers for CPU-Intensive Tasks Without Freezing UI

- 30.05.26 | 30.05.26 - ErcanOPAK comment on Ajax: Use Web Workers for CPU-Intensive Tasks Without Freezing UI

โš™๏ธ Heavy Math? Don’t Block UI! JavaScript runs on main thread. Long loops freeze the page. Web Workers run in background threads. UI stays responsive. ๐Ÿ“ Basic Worker // main.js const worker = new Worker(‘worker.js’); worker.postMessage({ data: largeArray, operation: ‘process’ }); worker.onmessage = (event) => { console.log(‘Result:’, event.data); updateUI(event.data); }; worker.onerror = (error) => { […]

Read More
JavaScript

JavaScript: Use Intl API for Native Date, Number, and String Localization

- 30.05.26 - ErcanOPAK comment on JavaScript: Use Intl API for Native Date, Number, and String Localization

๐ŸŒ No More Moment.js Dates, numbers, currencies, plurals โ€” all have different formats per locale. Intl API is built-in. No libraries needed. ๐Ÿ“ Date Formatting const date = new Date(); // US English new Intl.DateTimeFormat(‘en-US’).format(date); // “12/31/2024” // UK English new Intl.DateTimeFormat(‘en-GB’).format(date); // “31/12/2024” // German new Intl.DateTimeFormat(‘de-DE’).format(date); // “31.12.2024” // Japanese new Intl.DateTimeFormat(‘ja-JP’).format(date); // […]

Read More
HTML

HTML: Use Contenteditable to Make Any Element Editable

- 30.05.26 - ErcanOPAK comment on HTML: Use Contenteditable to Make Any Element Editable

โœ๏ธ Edit Any Element Like a Text Editor Need inline editing? contenteditable makes any element editable. divs, spans, whole pages. Like a text editor on the web. ๐Ÿ“ Basic Usage <div contenteditable=”true”> Click me and edit this text directly! </div> <h1 contenteditable=”true”>Editable Title</h1> <p contenteditable=”true”> This paragraph can be edited by users. Great for notes, […]

Read More
CSS

CSS: Use Logical Properties for International Layouts

- 30.05.26 - ErcanOPAK comment on CSS: Use Logical Properties for International Layouts

๐ŸŒ margin-left breaks in RTL languages Arabic, Hebrew read right-to-left. CSS Logical Properties use ‘inline’ and ‘block’ instead of ‘left’ and ‘right’. Works for any language. โŒ Physical Properties .sidebar { margin-left: 20px; padding-right: 10px; text-align: left; border-left: 1px solid; } // In RTL, all these are wrong! โœ… Logical Properties .sidebar { margin-inline-start: 20px; […]

Read More
Windows

Windows 11: Use Storage Spaces to Combine Multiple Drives

- 30.05.26 - ErcanOPAK comment on Windows 11: Use Storage Spaces to Combine Multiple Drives

๐Ÿ’พ JBOD โ†’ RAID Without Hardware Multiple external drives? Different sizes? Storage Spaces pools them together. Add mirroring, parity, or just combine capacity. ๐Ÿ“ Create Storage Pool Control Panel โ†’ Storage Spaces โ†’ Create a new pool Or PowerShell: # List available disks Get-PhysicalDisk | Where-Object CanPool -eq $True # Create pool New-StoragePool -FriendlyName “MediaPool” […]

Read More
AI

AI Prompt: Decode Cryptic Error Messages into Human Language

- 30.05.26 - ErcanOPAK comment on AI Prompt: Decode Cryptic Error Messages into Human Language

๐Ÿ”„ “Invalid token”? AI Explains What It Actually Means Error messages are often cryptic. AI translates them into plain English, suggests fixes, and explains the real issue. ๐Ÿ“ The Prompt I received this error message: [Paste error message here] Please: 1. Explain what this error means in plain English 2. What is the most likely […]

Read More
Docker

Docker: Build Images for Multiple Architectures (AMD64 + ARM64)

- 30.05.26 - ErcanOPAK comment on Docker: Build Images for Multiple Architectures (AMD64 + ARM64)

๐Ÿณ One Build, All Architectures Intel Mac, Apple Silicon, ARM servers, AMD servers โ€” different architectures. Docker Buildx builds for all from a single machine. ๐Ÿ”ง Setup Buildx # Create new builder instance (supports multiple platforms) docker buildx create –name multiarch –use # Bootstrap builder docker buildx inspect –bootstrap # Verify platforms docker buildx ls […]

Read More
Kubernetes

Kubernetes: Use Taints and Tolerations to Control Pod Placement

- 30.05.26 - ErcanOPAK comment on Kubernetes: Use Taints and Tolerations to Control Pod Placement

๐Ÿšซ Dedicated Nodes for Special Workloads Some nodes have GPUs. Some are spot instances. Taints repel pods. Tolerations allow them. Control exactly where workloads run. ๐Ÿ“ Add Taint to Node # Taint effects: # NoSchedule: Pods without toleration won’t be scheduled # PreferNoSchedule: Avoid if possible # NoExecute: Evict existing pods without toleration # Add […]

Read More
Wordpress

WordPress: Control Autoloaded Options to Speed Up Admin

- 30.05.26 - ErcanOPAK comment on WordPress: Control Autoloaded Options to Speed Up Admin

โšก 80% of Options Load on Every Page WordPress loads all ‘autoload’ options on every request. Many are never used. Clean your autoloaded options for faster admin. ๐Ÿ“ Check Autoloaded Options — SQL Query to see autoloaded options SELECT COUNT(*), SUM(LENGTH(option_value)) as total_size FROM wp_options WHERE autoload = ‘yes’; — List largest autoloaded options SELECT […]

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 (953)
  • 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)
  • Add Constraint to SQL Table to ensure email contains @ (580)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (579)
  • Average of all values in a column that are not zero in SQL (538)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (506)
  • Find numbers with more than two decimal places in SQL (454)

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 (953)
  • 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