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

C#

C#: Use MemoryPack for 10x Faster Serialization than JSON

- 17.02.26 - ErcanOPAK comment on C#: Use MemoryPack for 10x Faster Serialization than JSON

System.Text.Json is fast but MemoryPack uses binary format for extreme performance. Install: dotnet add package MemoryPack Define Serializable Type: [MemoryPackable] public partial class User { public int Id { get; set; } public string Name { get; set; } = string.Empty; public string Email { get; set; } = string.Empty; public DateTime CreatedAt { get; […]

Read More
C#

C#: Use params ReadOnlySpan for Allocation-Free Variable Arguments

- 17.02.26 - ErcanOPAK comment on C#: Use params ReadOnlySpan for Allocation-Free Variable Arguments

params arrays create heap allocation on every call. C# 13 allows params with Span for zero-allocation variable args. Old Way (Allocates): // params creates new int[] on every call public int Sum(params int[] numbers) { return numbers.Sum(); } // Called 1 million times = 1 million array allocations! Sum(1, 2, 3); New Way – C# […]

Read More
C#

C#: Use ObjectPool for Reusing Expensive Objects

- 17.02.26 - ErcanOPAK comment on C#: Use ObjectPool for Reusing Expensive Objects

Creating and destroying heavy objects (StringBuilder, MemoryStream) repeatedly wastes memory. ObjectPool reuses them. Install: dotnet add package Microsoft.Extensions.ObjectPool Setup: // Program.cs builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => { var provider = sp.GetRequiredService(); return provider.CreateStringBuilderPool(); }); Use in Service: public class TextService(ObjectPool pool) { public string BuildLargeText(IEnumerable items) { // Get StringBuilder from pool (reuse, no new allocation) var […]

Read More
C#

C#: Use Lazy for Expensive Object Initialization

- 17.02.26 - ErcanOPAK comment on C#: Use Lazy for Expensive Object Initialization

Creating expensive objects at startup wastes resources if they’re never used. Lazy defers creation until first access. Without Lazy: public class ReportService { // Created on class instantiation even if never used private readonly PdfGenerator _pdfGen = new PdfGenerator(); // Heavy! private readonly ExcelExporter _excelExporter = new ExcelExporter(); // Heavy! public void GeneratePdf() => _pdfGen.Generate(); […]

Read More
SQL

SQL: Use STRING_AGG to Concatenate Rows into Comma-Separated List

- 17.02.26 - ErcanOPAK comment on SQL: Use STRING_AGG to Concatenate Rows into Comma-Separated List

Collecting multiple rows into one comma-separated string used to require cursors. STRING_AGG does it in one line. Basic Usage: — Get all tags for each post SELECT PostId, STRING_AGG(TagName, ‘, ‘) AS Tags FROM PostTags GROUP BY PostId; — Result: — PostId Tags — 1 CSS, HTML, JavaScript — 2 SQL, Database, Performance With Ordering: […]

Read More
SQL

SQL: Use Filtered Indexes to Index Only Subset of Rows

- 17.02.26 - ErcanOPAK comment on SQL: Use Filtered Indexes to Index Only Subset of Rows

Regular index on status column with 95% ‘active’ rows is inefficient. Filter index to index only relevant rows. Problem – Full Index: — Index includes ALL rows (95% active, 5% inactive) CREATE INDEX IX_Orders_Status ON Orders(Status); — Query only needs inactive SELECT * FROM Orders WHERE Status = ‘inactive’; — Reads huge index to find […]

Read More
Asp.Net Core

.NET Core: Use Result Pattern to Avoid Exceptions for Expected Errors

- 17.02.26 - ErcanOPAK comment on .NET Core: Use Result Pattern to Avoid Exceptions for Expected Errors

Throwing exceptions for business logic (user not found, invalid input) is expensive. Result pattern is cleaner and faster. Define Result Type: public class Result { public T? Value { get; } public string? Error { get; } public bool IsSuccess { get; } private Result(T value) { Value = value; IsSuccess = true; } private […]

Read More
Asp.Net Core

.NET Core: Use IOptions Pattern for Strongly-Typed Configuration

- 17.02.26 - ErcanOPAK comment on .NET Core: Use IOptions Pattern for Strongly-Typed Configuration

Reading config with magic strings breaks on typos. IOptions pattern gives strongly-typed, validated config. Define Config Class: public class EmailSettings { public string SmtpHost { get; set; } = string.Empty; public int SmtpPort { get; set; } public string Username { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; […]

Read More
Git

Git: Use .gitattributes to Handle Line Endings Across OS

- 17.02.26 - ErcanOPAK comment on Git: Use .gitattributes to Handle Line Endings Across OS

Team uses Windows and Mac? Mixed line endings (CRLF/LF) cause constant unnecessary diffs. Fix with .gitattributes. Create .gitattributes in repo root: # Normalize all text files to LF in repo * text=auto # Force LF for these file types *.js text eol=lf *.ts text eol=lf *.css text eol=lf *.html text eol=lf *.json text eol=lf # […]

Read More
Git

Git: Use git notes to Add Comments to Commits Without Changing History

- 17.02.26 - ErcanOPAK comment on Git: Use git notes to Add Comments to Commits Without Changing History

Want to add context to old commits without rewriting history? Git notes attach metadata to any commit. Add Note to Commit: # Add note to last commit git notes add -m “Reviewed by John. Deployed to staging 2024-03-15” # Add note to specific commit git notes add -m “This fixed the prod outage on Black […]

Read More
Ajax

AJAX: Use Cache API to Serve Assets Offline Like Native App

- 17.02.26 - ErcanOPAK comment on AJAX: Use Cache API to Serve Assets Offline Like Native App

Users lose access when offline. Cache API stores assets so app works without internet. Register Service Worker: // main.js if (‘serviceWorker’ in navigator) { navigator.serviceWorker.register(‘/sw.js’); } Service Worker (sw.js): const CACHE = ‘v1’; const ASSETS = [‘/’, ‘/styles.css’, ‘/app.js’, ‘/logo.png’]; // Install: cache assets self.addEventListener(‘install’, event => { event.waitUntil( caches.open(CACHE).then(cache => cache.addAll(ASSETS)) ); }); // […]

Read More
JavaScript

JavaScript: Use WeakMap for Private Class Data Without Symbols

- 17.02.26 - ErcanOPAK comment on JavaScript: Use WeakMap for Private Class Data Without Symbols

Private class fields with # work but WeakMap provides better encapsulation and no memory leaks. Private Fields Approach: class Counter { #count = 0; // Private increment() { this.#count++; } get value() { return this.#count; } } WeakMap Approach: const _private = new WeakMap(); class Counter { constructor() { _private.set(this, { count: 0, history: [] […]

Read More
HTML

HTML5: Use output Element to Display Calculation Results Instantly

- 17.02.26 - ErcanOPAK comment on HTML5: Use output Element to Display Calculation Results Instantly

Showing form calculation results in a div is hacky. HTML5 output element is semantic and accessible. Basic Example: <form oninput=”result.value = parseInt(a.value) + parseInt(b.value)”> <input type=”number” id=”a” value=”0″> + <input type=”number” id=”b” value=”0″> = <output name=”result” for=”a b”>0</output> </form> Tips Calculator: <form oninput=”tip.value = (bill.value * pct.value / 100).toFixed(2)”> Bill: <input type=”number” id=”bill”> Tip %: […]

Read More
CSS

CSS: Use text-wrap: balance for Better Heading Line Breaks

- 17.02.26 - ErcanOPAK comment on CSS: Use text-wrap: balance for Better Heading Line Breaks

Headlines with one word on last line look unprofessional. text-wrap: balance distributes text evenly across lines. The Problem: This is a Long Heading That Ends With Just One Awkward Word Alone The Fix: h1, h2, h3 { text-wrap: balance; } Result: This is a Long Heading That Ends Much More Nicely Balanced Also Available: p […]

Read More
Windows

Windows 11: Use Resource Monitor to Find What’s Hogging Network or Disk

- 17.02.26 - ErcanOPAK comment on Windows 11: Use Resource Monitor to Find What’s Hogging Network or Disk

Something using all your bandwidth or disk but Task Manager doesn’t show what? Resource Monitor has the details. Open: Task Manager → Performance tab → Open Resource Monitor Or: Start → Search “Resource Monitor” Network Tab: – Shows EVERY process with active network connection – Bytes sent/received per process – Which remote addresses each app […]

Read More
Windows

Windows 11: Use Reliability Monitor to Find What Caused System Crashes

- 17.02.26 - ErcanOPAK comment on Windows 11: Use Reliability Monitor to Find What Caused System Crashes

PC crashing randomly? Reliability Monitor shows exact timeline of crashes, errors, and what caused them. Open: Start → Search “Reliability Monitor” Or: Control Panel → Security and Maintenance → View Reliability History What You See: – Timeline of stability (1-10 score) – Red X = critical events (crashes, failures) – Yellow ! = warnings – […]

Read More
AI

AI Prompt: Negotiate Your Salary with AI-Prepared Talking Points

- 17.02.26 - ErcanOPAK comment on AI Prompt: Negotiate Your Salary with AI-Prepared Talking Points

Salary negotiation is nerve-wracking without preparation. AI coaches you with specific talking points. The Prompt: Help me prepare for salary negotiation: My role: [Job title] My experience: [X years] Current salary: [$X or N/A if new job] Target salary: [$X] Their offer: [$X if applicable] Location: [City/Remote] Company type: [Startup/Corp/etc] My strengths: [Key skills/achievements] Prepare: […]

Read More
AI

AI Prompt: Explain Your Medical Test Results in Plain Language

- 17.02.26 - ErcanOPAK comment on AI Prompt: Explain Your Medical Test Results in Plain Language

Blood test results full of confusing numbers and abbreviations? AI explains what they mean. The Prompt: Explain these medical test results in plain English: [Paste or type your results] For each value: 1. What does this measure? 2. Is my value normal, high, or low? 3. What does abnormal mean for health? 4. What lifestyle […]

Read More
AI

AI Prompt: Create Personalized Workout Plan Based on Equipment and Goals

- 17.02.26 - ErcanOPAK comment on AI Prompt: Create Personalized Workout Plan Based on Equipment and Goals

Generic workout plans don’t fit your equipment or schedule. AI creates perfectly tailored plan. The Prompt: Create personalized workout plan: My equipment: [gym / home / dumbbells only / no equipment] Goal: [lose weight / build muscle / improve endurance / stay active] Current level: [beginner / intermediate / advanced] Days per week: [3/4/5/6] Time […]

Read More
Docker

Docker: Use Compose Profiles to Start Only Needed Services

- 17.02.26 - ErcanOPAK comment on Docker: Use Compose Profiles to Start Only Needed Services

Running all services (database, cache, queue, monitoring) every time is slow. Profiles start only what you need. docker-compose.yml: services: app: build: . ports: – “3000:3000” db: image: postgres profiles: [“dev”, “test”] redis: image: redis profiles: [“dev”] monitoring: image: grafana profiles: [“monitoring”] mailhog: image: mailhog/mailhog profiles: [“dev”] Start Different Profiles: # Just the app (no extras) […]

Read More
Kubernetes

Kubernetes: Use Pod Disruption Budget to Ensure Availability During Maintenance

- 17.02.26 - ErcanOPAK comment on Kubernetes: Use Pod Disruption Budget to Ensure Availability During Maintenance

Rolling updates can accidentally take down too many pods. PDB guarantees minimum availability. Create PDB: apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: myapp-pdb spec: minAvailable: 2 # Always keep at least 2 pods running selector: matchLabels: app: myapp Or Use maxUnavailable: spec: maxUnavailable: 1 # At most 1 pod can be down at a time selector: […]

Read More
Wordpress

WordPress: Add noindex to Tag and Author Pages to Prevent Duplicate Content

- 17.02.26 - ErcanOPAK comment on WordPress: Add noindex to Tag and Author Pages to Prevent Duplicate Content

Tag pages and author archives can be seen as duplicate content by Google. Noindex them to protect SEO. Add to functions.php: add_action(‘wp_head’, function() { if (is_tag() || is_author() || is_date()) { echo ”; } }); Or Disable Archives Completely: // Redirect tag pages to homepage add_action(‘template_redirect’, function() { if (is_tag()) { wp_redirect(home_url(), 301); exit; } […]

Read More
Wordpress

WordPress: Use Heartbeat API Control to Reduce CPU Usage by 80%

- 17.02.26 - ErcanOPAK comment on WordPress: Use Heartbeat API Control to Reduce CPU Usage by 80%

WordPress Heartbeat API pings server every 15-60 seconds causing CPU spikes. Slow it down or disable. Add to functions.php: // Reduce heartbeat frequency add_filter(‘heartbeat_settings’, function($settings) { $settings[‘interval’] = 60; // From 15-60 to 60 seconds return $settings; }); // Disable on frontend only (keep for editor autosave) add_action(‘init’, function() { if (!is_admin()) { wp_deregister_script(‘heartbeat’); } […]

Read More
Photoshop

Photoshop: Use Frequency Separation for Professional Skin Retouching

- 17.02.26 - ErcanOPAK comment on Photoshop: Use Frequency Separation for Professional Skin Retouching

Blurring skin for retouching also removes texture. Frequency Separation edits skin tone and texture on separate layers. Setup: 1. Duplicate layer twice (Ctrl+J twice) 2. Name layers: “Low Frequency” (bottom) and “High Frequency” (top) Low Frequency layer (tone/color): Filter → Blur → Gaussian Blur → 4-6px High Frequency layer (texture/detail): Image → Apply Image: Layer: […]

Read More
Photoshop

Photoshop: Use Sky Replacement for Instant Dramatic Sky Swaps

- 17.02.26 - ErcanOPAK comment on Photoshop: Use Sky Replacement for Instant Dramatic Sky Swaps

Manually masking skies takes hours. Sky Replacement uses AI to detect and replace skies automatically. Access: Edit → Sky Replacement Steps: 1. Open photo with boring sky 2. Edit → Sky Replacement 3. Click Sky dropdown → Choose preset or load custom sky 4. AI auto-selects sky and blends colors! Fine-tune Options: – Edge Lighting: […]

Read More
Visual Studio

Visual Studio: Use Hot Reload to Apply Code Changes Without Restarting App

- 17.02.26 - ErcanOPAK comment on Visual Studio: Use Hot Reload to Apply Code Changes Without Restarting App

Restarting app after every small change wastes minutes. Hot Reload applies changes to running app instantly. Enable Hot Reload: Click the flame icon 🔥 in Debug toolbar (or Alt+F10) Works While: – App is running (with or without debugger) – Even during breakpoints Supports: – Method body changes – Adding new methods – CSS/XAML changes […]

Read More
February 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
232425262728  
« Jan   Mar »

Most Viewed Posts

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

Recent Posts

  • C#: Saving Memory with yield return (Lazy Streams)
  • C#: Why Records are Better Than Classes for Data DTOs
  • C#: Creating Strings Without Memory Pressure with String.Create
  • SQL: Protecting Sensitive Data with Dynamic Data Masking
  • SQL: Writing Readable Queries with Common Table Expressions (CTE)
  • .NET Core: Handling Errors Gracefully with Middleware
  • .NET Core: Mastering Service Lifetimes (A Visual Guide)
  • Git: Surgical Stashing – Don’t Save Everything!
  • Git: Writing Commits That Your Future Self Won’t Hate
  • Ajax: Improving Perceived Speed with Skeleton Screens

Most Viewed Posts

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

Recent Posts

  • C#: Saving Memory with yield return (Lazy Streams)
  • C#: Why Records are Better Than Classes for Data DTOs
  • C#: Creating Strings Without Memory Pressure with String.Create
  • SQL: Protecting Sensitive Data with Dynamic Data Masking
  • SQL: Writing Readable Queries with Common Table Expressions (CTE)

Social

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