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: June 6, 2026

C#

C#: Use Using Declarations for Automatic Disposal

- 06.06.26 - ErcanOPAK comment on C#: Use Using Declarations for Automatic Disposal

๐Ÿงน using var x = new StreamReader(); Old using needed braces and indentation. Using declarations dispose at end of scope. Less nesting, cleaner code. โŒ Old Using (Nested) using (var file = new StreamReader(“data.txt”)) { using (var writer = new StreamWriter(“output.txt”)) { writer.Write(file.ReadToEnd()); } } โœ… Using Declaration using var file = new StreamReader(“data.txt”); using […]

Read More
C#

C#: Use Default Interface Methods for Versioning and Mixins

- 06.06.26 - ErcanOPAK comment on C#: Use Default Interface Methods for Versioning and Mixins

โž• Add Methods to Interfaces Without Breaking Implementations Adding to interface breaks all implementers. Default interface methods provide implementation. Existing code continues to work. โŒ Before (Breaks) interface ILogger { void Log(string message); // Adding new method breaks all implementers } โœ… Default Method (No Break) interface ILogger { void Log(string message); void LogError(string error) […]

Read More
SQL

SQL: Use Generate Series to Fill Missing Dates

- 06.06.26 - ErcanOPAK comment on SQL: Use Generate Series to Fill Missing Dates

๐Ÿ“… JOIN with Missing Dates? Fill the Gaps Sales report missing dates = misleading. Generate series creates sequences. Fill missing dates with zero sales. ๐Ÿ“ PostgreSQL generate_series — Generate numbers 1 to 100 SELECT generate_series(1, 100); — Generate dates SELECT generate_series( ‘2024-01-01’::date, ‘2024-12-31’::date, ‘1 day’::interval ); — Generate with step SELECT generate_series(0, 100, 10); — […]

Read More
Asp.Net Core

.NET Core: Use Environment Variables for Multi-Environment Configuration

- 06.06.26 - ErcanOPAK comment on .NET Core: Use Environment Variables for Multi-Environment Configuration

๐ŸŒ Development, Staging, Production โ€” One Config appsettings.Development.json works. Environment variables override config in production. No code changes. No redeploys. ๐Ÿ“ ASP.NET Core Setup // Program.cs var builder = WebApplication.CreateBuilder(args); // Environment variables override appsettings.json builder.Configuration.AddEnvironmentVariables(); // Or prefix to avoid conflicts builder.Configuration.AddEnvironmentVariables(“MYAPP_”); // Set environment builder.Environment.EnvironmentName = Environment.GetEnvironmentVariable(“ASPNETCORE_ENVIRONMENT”) ?? “Production”; // appsettings.json { “Database”: […]

Read More
Git

Git: Use Git Bundle to Transfer Repos Without a Server

- 06.06.26 - ErcanOPAK comment on Git: Use Git Bundle to Transfer Repos Without a Server

๐Ÿ“ฆ No Internet? No Problem. Need to share repo offline? Git bundle packs entire repo into a single file. USB transfer, email, any method works. ๐Ÿ“ Create Bundle # Bundle entire repo git bundle create myrepo.bundle –all # Bundle specific branch git bundle create feature.bundle feature-branch # Bundle range of commits git bundle create updates.bundle […]

Read More
Ajax

Ajax: Use Cache-Control Headers to Prevent Stale Data

- 06.06.26 - ErcanOPAK comment on Ajax: Use Cache-Control Headers to Prevent Stale Data

๐Ÿ”„ Browser Cache Returns Old Data GET requests are cached. Cache-Control headers prevent stale data. Always fresh for dynamic content. ๐Ÿ“ Server Headers # No caching (always fresh) Cache-Control: no-store, no-cache, must-revalidate # Cache for 1 hour Cache-Control: public, max-age=3600 # Cache but revalidate Cache-Control: public, max-age=3600, must-revalidate # Private cache (browser only) Cache-Control: private, […]

Read More
JavaScript

JavaScript: Use Labeled Statements to Break Outer Loops

- 06.06.26 - ErcanOPAK comment on JavaScript: Use Labeled Statements to Break Outer Loops

๐Ÿท๏ธ break only breaks inner loop Need to exit nested loops? Labeled statements break or continue outer loops. Perfect for search in matrix. โŒ Without Label (Cannot break outer) for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { if (found) { break; // Only […]

Read More
HTML

HTML: Use Resource Hints to Load Critical Assets Faster

- 06.06.26 - ErcanOPAK comment on HTML: Use Resource Hints to Load Critical Assets Faster

โšก Tell Browser What’s Important Browsers discover resources as they parse HTML. Resource hints tell browser earlier. Faster LCP, better UX. ๐Ÿ“ Preload (Critical Resources) <!– Fonts (discovered late in CSS) –> <link rel=”preload” href=”font.woff2″ as=”font” type=”font/woff2″ crossorigin> <!– Hero image (discovered after CSS) –> <link rel=”preload” href=”hero.jpg” as=”image”> <!– Critical CSS (inline? No, preload) […]

Read More
CSS

CSS: Use :focus-visible for Better Focus Indicators

- 06.06.26 - ErcanOPAK comment on CSS: Use :focus-visible for Better Focus Indicators

โŒจ๏ธ Show Focus Only for Keyboard Users Mouse users don’t need focus rings. Keyboard users do. :focus-visible shows focus only when needed. Best of both worlds. โŒ :focus (Always Shows) /* Ugly outline on mouse click */ button:focus { outline: 2px solid blue; } /* Mouse users see blue ring unnecessarily */ โœ… :focus-visible (Smart) […]

Read More
Windows

Windows 11: Create System Restore Points Before Major Changes

- 06.06.26 - ErcanOPAK comment on Windows 11: Create System Restore Points Before Major Changes

โช Go Back in Time Installing drivers? Registry edits? System Restore takes snapshot. If something breaks, revert to working state. ๐Ÿ”ง Create Restore Point Method 1: Start โ†’ Create a restore point Method 2: Win + R โ†’ sysdm.cpl โ†’ System Protection To create: 1. Click “Create” 2. Name it (e.g., “Before driver update”) 3. […]

Read More
AI

AI Prompt: Optimize Slow SQL Queries with AI Analysis

- 06.06.26 - ErcanOPAK comment on AI Prompt: Optimize Slow SQL Queries with AI Analysis

๐Ÿš€ 10 Second Query โ†’ 0.1 Second Don’t know SQL optimization? AI analyzes query, suggests indexes, rewrites for speed. Massive performance gains. ๐Ÿ“ The Prompt I have a slow SQL query that needs optimization. Current query: [paste your SQL query] Database: [PostgreSQL/MySQL/SQL Server] Table sizes: – users: 1 million rows – orders: 5 million rows […]

Read More
Docker

Docker: Use Docker Context to Switch Between Local and Remote Docker

- 06.06.26 - ErcanOPAK comment on Docker: Use Docker Context to Switch Between Local and Remote Docker

๐Ÿ”„ One CLI, Multiple Docker Daemons Docker CLI talks to local daemon. Docker context switches to remote daemon. Build on local, deploy to remote. No SSH or env vars. ๐Ÿ“ Create and Use Contexts # List contexts docker context ls # Create context for remote Docker (with SSH) docker context create remote –docker host=ssh://user@remote-server # […]

Read More
Kubernetes

Kubernetes: Use Priority Classes to Ensure Critical Pods Run First

- 06.06.26 - ErcanOPAK comment on Kubernetes: Use Priority Classes to Ensure Critical Pods Run First

โญ DNS Pods Should Evict Batch Jobs When cluster is full, which pods get evicted? Priority Classes define importance. Critical pods survive. Batch jobs go first. ๐Ÿ“ Define Priority Classes apiVersion: scheduling.k8s.io/v1 kind: PriorityClass metadata: name: critical value: 1000000000 globalDefault: false description: “Critical system pods that must never be evicted” — apiVersion: scheduling.k8s.io/v1 kind: PriorityClass […]

Read More
Wordpress

WordPress: Create Custom Taxonomies for Better Content Organization

- 06.06.26 - ErcanOPAK comment on WordPress: Create Custom Taxonomies for Better Content Organization

๐Ÿท๏ธ More Than Categories and Tags Posts have categories, tags. Products need brands, sizes, colors. Custom taxonomies create any classification system. ๐Ÿ“ Register Custom Taxonomy // functions.php function create_product_taxonomies() { // Brand taxonomy (hierarchical like categories) register_taxonomy(‘product_brand’, ‘product’, array( ‘labels’ => array( ‘name’ => ‘Brands’, ‘singular_name’ => ‘Brand’, ‘search_items’ => ‘Search Brands’, ‘all_items’ => ‘All […]

Read More
Photoshop

Photoshop: Use Frequency Separation for Professional Skin Retouching

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

โœจ Separate Texture from Color Healing Brush blends texture and color. Frequency Separation separates them. Edit color without affecting skin pores. Edit texture without changing color. ๐Ÿ“ Create Frequency Separation 1. Duplicate layer twice (Ctrl+J, Ctrl+J) 2. Name top layer “Texture”, middle “Color”, hide top 3. Select Color layer โ†’ Filter โ†’ Blur โ†’ Gaussian […]

Read More
Visual Studio

Visual Studio: Use CodeMaid to Automatically Clean and Organize Code

- 06.06.26 - ErcanOPAK comment on Visual Studio: Use CodeMaid to Automatically Clean and Organize Code

๐Ÿงน One Click, Whole Solution Cleaned Code formatting, unused using removal, sorting members โ€” CodeMaid does it all. Automatic code cleanup on save. ๐Ÿ”ง Features Install: Extensions โ†’ CodeMaid Features: – Reorganize members (fields, properties, methods) – Remove unused usings – Sort usings alphabetically – Format document – Remove blank lines – Insert file header […]

Read More
C#

C#: Use ArrayPool to Reduce GC Pressure

- 06.06.26 - ErcanOPAK comment on C#: Use ArrayPool to Reduce GC Pressure

โ™ป๏ธ Stop Allocating Temporary Arrays new byte[1024] allocates and GC collects. ArrayPool<T> reuses arrays. Zero allocation for temporary buffers. Huge GC reduction. ๐Ÿ“ Basic ArrayPool Usage using System.Buffers; // Rent array (might be larger than requested) byte[] buffer = ArrayPool.Shared.Rent(1024); try { // Use buffer await stream.ReadAsync(buffer, 0, 1024); Process(buffer); } finally { // Return […]

Read More
C#

C#: Use Function Pointers for High-Performance Callbacks

- 06.06.26 - ErcanOPAK comment on C#: Use Function Pointers for High-Performance Callbacks

โšก Delegate Overhead? Use Function Pointers. Delegates are fast, but not zero-cost. Function pointers (C# 9+) call native code or high-frequency callbacks with minimal overhead. ๐Ÿ“ Basic Function Pointer unsafe { // Delegate (managed) Func addDelegate = (a, b) => a + b; // Function pointer (unmanaged) delegate* addPointer = &Add; int result1 = addDelegate(5, […]

Read More
SQL

SQL: Use Full-Text Search for Fast Text Search

- 06.06.26 - ErcanOPAK comment on SQL: Use Full-Text Search for Fast Text Search

๐Ÿ” LIKE ‘%word%’ is Slow LIKE with leading wildcard can’t use indexes. Full-Text Search indexes words. Search millions of rows in milliseconds. ๐Ÿ“ Create Full-Text Index — PostgreSQL CREATE INDEX idx_posts_search ON posts USING GIN (to_tsvector(‘english’, title || ‘ ‘ || content)); — MySQL ALTER TABLE posts ADD FULLTEXT INDEX idx_search (title, content); — SQL […]

Read More
Asp.Net Core

.NET Core: Use Output Caching to Cache API Responses

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

โšก 100x Faster Responses with One Line of Code Same endpoint called repeatedly? Database query every time? Output caching stores HTTP responses. No database, no processing. ๐Ÿ“ Basic Output Caching // 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 […]

Read More
Git

Git: Use Git Hooks to Automate Tasks on Commit, Push, Merge

- 06.06.26 - ErcanOPAK comment on Git: Use Git Hooks to Automate Tasks on Commit, Push, Merge

โš™๏ธ Run Scripts Automatically on Git Events Run tests before commit? Lint before push? Git hooks automate anything. No more forgotten steps. ๐Ÿ“ pre-commit Hook #!/bin/bash # .git/hooks/pre-commit # Run linter npm run lint if [ $? -ne 0 ]; then echo “โŒ Linter failed. Fix errors before commit.” exit 1 fi # Run tests […]

Read More
Ajax

Ajax: Use keep-alive to Reuse HTTP Connections

- 06.06.26 - ErcanOPAK comment on Ajax: Use keep-alive to Reuse HTTP Connections

โšก 30% Faster API Calls Each fetch opens new TCP connection. Handshake overhead. Connection: keep-alive reuses connections. Faster subsequent requests. ๐Ÿ“ Server Configuration # Node.js (Express) const server = app.listen(3000); server.keepAliveTimeout = 60000; // 60 seconds server.headersTimeout = 61000; # Nginx keepalive_timeout 65s; keepalive_requests 100; # Apache KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 # IIS […]

Read More
JavaScript

JavaScript: Use Object.groupBy to Group Arrays Without Lodash

- 06.06.26 - ErcanOPAK comment on JavaScript: Use Object.groupBy to Group Arrays Without Lodash

๐Ÿ“Š _.groupBy() is Finally Native Grouping arrays required Lodash or manual reduce. Object.groupBy() is native. No more dependencies. ๐Ÿ“ Basic GroupBy const users = [ { name: ‘Alice’, role: ‘admin’ }, { name: ‘Bob’, role: ‘user’ }, { name: ‘Charlie’, role: ‘admin’ } ]; const byRole = Object.groupBy(users, user => user.role); // { // admin: […]

Read More
HTML

HTML: Use Permissions Policy to Control Browser Features

- 06.06.26 - ErcanOPAK comment on HTML: Use Permissions Policy to Control Browser Features

๐Ÿ”’ Disable Camera, Microphone, Geolocation by Default Third-party scripts accessing sensitive APIs? Permissions Policy controls which features are allowed. Defense in depth. ๐Ÿ“ HTTP Header # Disable everything Permissions-Policy: geolocation=(), camera=(), microphone=(), payment=() # Allow only same origin Permissions-Policy: geolocation=(self), camera=(self) # Allow specific domains Permissions-Policy: geolocation=(self “https://trusted.com”) # Allow all (default) Permissions-Policy: geolocation=* ๐ŸŽฏ […]

Read More
CSS

CSS: Use @property to Define Typed Custom Properties

- 06.06.26 - ErcanOPAK comment on CSS: Use @property to Define Typed Custom Properties

๐Ÿ“ CSS Variables Now Have Types! CSS variables are strings. @property defines types: number, color, length. Enables smooth transitions. ๐Ÿ“ Defining Typed Properties @property –progress { syntax: ”; inherits: false; initial-value: 0%; } @property –primary-color { syntax: ”; inherits: true; initial-value: #3498db; } @property –spacing { syntax: ‘ | ‘; inherits: false; initial-value: 0px; } […]

Read More
Windows

Windows 11: Use Storage Sense to Automatically Free Up Disk Space

- 06.06.26 - ErcanOPAK comment on Windows 11: Use Storage Sense to Automatically Free Up Disk Space

๐Ÿ—‘๏ธ Never Run Disk Cleanup Again Temporary files, recycle bin, downloads folder โ€” fill your disk. Storage Sense cleans automatically. Set it and forget it. ๐Ÿ”ง Enable Storage Sense Settings โ†’ System โ†’ Storage โ†’ Storage Sense โ†’ On Configure: – Run Storage Sense: Every day / Week / Month / Low disk space – […]

Read More
AI

AI Prompt: Generate API Documentation from Code Comments

- 06.06.26 - ErcanOPAK comment on AI Prompt: Generate API Documentation from Code Comments

๐Ÿ“š Turn // Comments into Beautiful Documentation JSDoc, XML comments, docstrings are structured. AI converts comments to Markdown docs. Publish anywhere. ๐Ÿ“ The Prompt Convert these code comments into API documentation: [Paste code with JSDoc/XML comments here] Requirements: – Generate readable Markdown – Include function signatures with types – Add example usage for each function […]

Read More
Docker

Docker: Use Build Secrets to Keep API Keys Out of Images

- 06.06.26 - ErcanOPAK comment on Docker: Use Build Secrets to Keep API Keys Out of Images

๐Ÿ”‘ npm install Needs Token. But Token Shouldn’t Be in Image. Build-time secrets (npm tokens, SSH keys) often leak into layers. Docker BuildKit secrets mount secrets at build time, never stored. ๐Ÿ“ Dockerfile with Secrets # syntax=docker/dockerfile:1.4 FROM node:18 AS builder WORKDIR /app COPY package*.json ./ # Secret mount (not stored in layer) RUN –mount=type=secret,id=npmrc […]

Read More
Kubernetes

Kubernetes: Use PodDisruptionBudget to Prevent Service Interruption

- 06.06.26 - ErcanOPAK comment on Kubernetes: Use PodDisruptionBudget to Prevent Service Interruption

๐Ÿ›ก๏ธ Don’t Drain All Pods at Once Node draining, cluster upgrades kill pods. PodDisruptionBudget (PDB) ensures minimum availability during voluntary disruptions. ๐Ÿ“ PDB Examples # At least 2 pods available at all times apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: app-pdb spec: minAvailable: 2 selector: matchLabels: app: myapp # No more than 1 pod unavailable apiVersion: […]

Read More
Wordpress

WordPress: Run Custom SQL Queries with $wpdb Object

- 06.06.26 - ErcanOPAK comment on WordPress: Run Custom SQL Queries with $wpdb Object

๐Ÿ’พ WP_Query Too Slow? Go Direct. WP_Query is convenient but slow for complex reports. $wpdb runs raw SQL. 100x faster for large datasets. ๐Ÿ“ Basic $wpdb global $wpdb; // Get single value $user_count = $wpdb->get_var(“SELECT COUNT(*) FROM {$wpdb->users}”); // Get single row $user = $wpdb->get_row(“SELECT * FROM {$wpdb->users} WHERE ID = 123”); // Get all […]

Read More
Page 1 of 2
1 2 Next ยป

Posts pagination

1 2 Next »
June 2026
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  
« May    

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