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

C#

C#: Create Custom Interpolated String Handlers for Zero-Allocation Logging

- 05.06.26 - ErcanOPAK comment on C#: Create Custom Interpolated String Handlers for Zero-Allocation Logging

โšก Logging Without String Allocation Interpolation allocates strings even if log level is off. Custom interpolated string handlers defer formatting until needed. ๐Ÿ“ Custom Handler [InterpolatedStringHandler] public ref struct DebugLogHandler { private readonly bool _enabled; private StringBuilder? _builder; public DebugLogHandler(int literalLength, int formattedCount, bool enabled, out bool shouldAppend) { _enabled = enabled; shouldAppend = enabled; […]

Read More
C#

C#: Use CallerArgumentExpression for Better Argument Validation

- 05.06.26 - ErcanOPAK comment on C#: Use CallerArgumentExpression for Better Argument Validation

๐Ÿ” Know Which Argument Caused the Error ArgumentNullException with parameter name is good. CallerArgumentExpression shows the actual expression. Even better for complex validations. โŒ Standard Validation public void Process(string data) { if (data == null) throw new ArgumentNullException(nameof(data)); } // Exception: Parameter name: data โœ… CallerArgumentExpression static void GuardNotNull(object value, [CallerArgumentExpression(“value”)] string expr = null) […]

Read More
SQL

SQL: Use WITH RECURSIVE to Query Hierarchical Data

- 05.06.26 - ErcanOPAK comment on SQL: Use WITH RECURSIVE to Query Hierarchical Data

๐ŸŒณ Org Charts, Categories, Comment Threads Self-joins are messy. Recursive CTEs query parent-child relationships elegantly. Get entire organization tree in one query. ๐Ÿ“ Employee Hierarchy WITH RECURSIVE org_tree AS ( — Anchor: top-level managers SELECT id, name, manager_id, 0 as level, name as path FROM employees WHERE manager_id IS NULL UNION ALL — Recursive: employees […]

Read More
Asp.Net Core

.NET Core: Publish as Native AOT for Self-Contained Executables

- 05.06.26 - ErcanOPAK comment on .NET Core: Publish as Native AOT for Self-Contained Executables

๐Ÿ“ฆ One EXE, No Runtime, Instant Start .NET apps need runtime installed. Native AOT compiles to single native executable. Works on machines without .NET. 10ms startup. ๐Ÿ”ง Enable Native AOT <Project Sdk=”Microsoft.NET.Sdk”> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <PublishAot>true</PublishAot> </PropertyGroup> </Project> # Publish command dotnet publish -c Release -r win-x64 –self-contained # Output: single .exe file (~10-30MB) ๐ŸŽฏ […]

Read More
Git

Git: Use Git Stash Show to See What’s in a Stash

- 05.06.26 - ErcanOPAK comment on Git: Use Git Stash Show to See What’s in a Stash

๐Ÿ“ฆ Which Stash Had That Code? Forgot what’s in stash @{3}? git stash show reveals changes. Preview before applying. ๐Ÿ“ Basic Show # Show latest stash (summary) git stash show # Show latest stash (full diff) git stash show -p # Show specific stash git stash show stash@{2} git stash show -p stash@{2} # Show […]

Read More
Ajax

Ajax: Use Priority Hints to Tell Browser Which Resources Load First

- 05.06.26 - ErcanOPAK comment on Ajax: Use Priority Hints to Tell Browser Which Resources Load First

โšก Hero Image > Analytics Script Browsers guess priority. They’re often wrong. Priority Hints (fetchpriority) tell browser exactly what’s important. Faster LCP, better UX. ๐Ÿ“ Basic Priority Hints <!– High priority (hero image, main content) –> <img src=”hero.jpg” fetchpriority=”high”> <link rel=”preload” href=”font.woff2″ as=”font” fetchpriority=”high”> <!– Low priority (below fold, analytics) –> <img src=”footer-logo.png” fetchpriority=”low”> <script […]

Read More
JavaScript

JavaScript: Use WeakRef and FinalizationRegistry to Prevent Memory Leaks

- 05.06.26 - ErcanOPAK comment on JavaScript: Use WeakRef and FinalizationRegistry to Prevent Memory Leaks

๐Ÿ—‘๏ธ Know When Objects Are Garbage Collected WeakMap is known. WeakRef and FinalizationRegistry give advanced memory management. Cache cleanup, resource release, memory leak detection. ๐Ÿ“ WeakRef Example let obj = { data: ‘important’ }; const weakRef = new WeakRef(obj); // Later, obj might be garbage collected obj = null; // Check if still alive const […]

Read More
HTML

HTML: Use COOP and COEP Headers for Cross-Origin Isolation

- 05.06.26 - ErcanOPAK comment on HTML: Use COOP and COEP Headers for Cross-Origin Isolation
Read More
CSS

CSS: Use Scroll-Driven Animations for Parallax Without JS

- 05.06.26 - ErcanOPAK comment on CSS: Use Scroll-Driven Animations for Parallax Without JS

๐Ÿ“œ Animation Tied to Scroll Position Scroll-triggered animations needed JavaScript. Scroll-driven animations are pure CSS. Progress bar, reveal on scroll, parallax โ€” all native. ๐Ÿ“ Basic Scroll Progress /* Progress bar that fills as you scroll */ @keyframes grow-progress { from { transform: scaleX(0); } to { transform: scaleX(1); } } .progress-bar { position: fixed; […]

Read More
Windows

Windows 11: Use Steps Recorder to Document Bugs for IT Support

- 05.06.26 - ErcanOPAK comment on Windows 11: Use Steps Recorder to Document Bugs for IT Support

๐Ÿ“ธ Record Screen Steps Automatically ‘It doesn’t work’ isn’t helpful. Steps Recorder captures every click, keystroke, and screen. Perfect for IT tickets, bug reports, user training. ๐Ÿ”ง Start Steps Recorder Start โ†’ Steps Recorder (or “psr”) Alternative: Win + R โ†’ psr โ†’ Enter Buttons: – Start Record (Ctrl + Shift + R) – Stop […]

Read More
AI

AI Prompt: Generate Performance Review Comments from Metrics

- 05.06.26 - ErcanOPAK comment on AI Prompt: Generate Performance Review Comments from Metrics

๐Ÿ“ Write Better Reviews, Faster Performance reviews are hard to write. AI generates review comments from metrics, achievements, and feedback. Professional, balanced, specific. ๐Ÿ“ The Prompt Write a performance review for an employee with the following data: Role: [Software Engineer / Product Manager / Designer] Tenure: [6 months / 2 years / etc.] Key achievements: […]

Read More
Docker

Docker: Run Containers as Non-Root User for Better Security

- 05.06.26 - ErcanOPAK comment on Docker: Run Containers as Non-Root User for Better Security
Read More
Kubernetes

Kubernetes: Use Kustomize to Manage Multiple Environments Without Templates

- 05.06.26 - ErcanOPAK comment on Kubernetes: Use Kustomize to Manage Multiple Environments Without Templates

๐Ÿ“ No Helm. No Templating. Pure YAML. Helm templates are complex. Kustomize is built into kubectl. Overlay configs for dev, staging, prod. No new syntax to learn. ๐Ÿ“ Folder Structure k8s/ โ”œโ”€โ”€ base/ โ”‚ โ”œโ”€โ”€ deployment.yaml โ”‚ โ”œโ”€โ”€ service.yaml โ”‚ โ””โ”€โ”€ kustomization.yaml โ””โ”€โ”€ overlays/ โ”œโ”€โ”€ dev/ โ”‚ โ”œโ”€โ”€ replica_count.yaml โ”‚ โ”œโ”€โ”€ configmap.yaml โ”‚ โ””โ”€โ”€ kustomization.yaml […]

Read More
Wordpress

WordPress: Understand the Difference Between Actions and Filters

- 05.06.26 - ErcanOPAK comment on WordPress: Understand the Difference Between Actions and Filters

๐Ÿ”Œ Actions Do Something. Filters Change Something. Both hooks, but different purposes. Actions execute code. Filters modify data. Knowing the difference saves hours of debugging. โšก Action Hook // Do something (no return value) add_action(‘wp_head’, ‘add_google_analytics’); function add_google_analytics() { echo ‘<script>// GA code</script>’; } // do_action() executes callbacks // Returns nothing, just runs ๐Ÿ”„ Filter […]

Read More
Photoshop

Photoshop: Use Color Range to Select All Pixels of Same Color

- 05.06.26 - ErcanOPAK comment on Photoshop: Use Color Range to Select All Pixels of Same Color

๐ŸŽจ Magic Wand on Steroids Magic Wand selects contiguous pixels. Color Range selects ALL pixels matching a color, anywhere in image. Perfect for removing backgrounds, color correction. ๐Ÿ“ How to Use Select โ†’ Color Range Sampled Colors: (dropdown) – Sampled Colors: Use eyedropper to pick color – Reds / Yellows / Greens / Cyans / […]

Read More
Visual Studio

Visual Studio: Shift + Right Click to Copy Full File Path

- 05.06.26 - ErcanOPAK comment on Visual Studio: Shift + Right Click to Copy Full File Path

๐Ÿ“‹ Copy File Path Without Opening Properties Need to share file location? Copy path? Shift + Right Click reveals hidden context menu items. Copy as path, copy full path, open in terminal. โŒจ๏ธ Hidden Shortcut Normal right-click: – Open – Open With – Copy (Ctrl+C) Shift + Right Click: – Copy as path – Copy […]

Read More
C#

C#: Use List Patterns for Powerful Array and List Matching

- 05.06.26 - ErcanOPAK comment on C#: Use List Patterns for Powerful Array and List Matching

๐Ÿ“‹ Match Arrays Like Prolog Match first element, last element, empty list โ€” all with pattern matching. List patterns make array processing declarative. ๐Ÿ“ Basic Patterns int[] numbers = [1, 2, 3, 4, 5]; // Match first two elements if (numbers is [1, 2, ..]) { Console.WriteLine(“Starts with 1,2”); } // Match last two elements […]

Read More
C#

C#: Use Generic Math for Mathematical Algorithms on Any Numeric Type

- 05.06.26 - ErcanOPAK comment on C#: Use Generic Math for Mathematical Algorithms on Any Numeric Type

๐Ÿงฎ One Algorithm, Any Number Type Sum() works on int, double, decimal? Not before. Generic math lets you write math algorithms once for all numeric types. โŒ Before (Duplicated Code) int Sum(int[] numbers) { int total = 0; foreach (var n in numbers) total += n; return total; } double Sum(double[] numbers) { double total […]

Read More
SQL

SQL: Use JSON Functions to Query JSON Columns

- 05.06.26 - ErcanOPAK comment on SQL: Use JSON Functions to Query JSON Columns

๐Ÿ“Š NoSQL in SQL, Best of Both Worlds Store flexible data as JSON. Query inside JSON. Index specific fields. PostgreSQL JSON functions give you relational + document database. ๐Ÿ“ Store and Query JSON CREATE TABLE products ( id SERIAL PRIMARY KEY, name TEXT, metadata JSONB ); INSERT INTO products (name, metadata) VALUES (‘Laptop’, ‘{“brand”: “Apple”, […]

Read More
Asp.Net Core

.NET Core: Use Source Generators for Compile-Time Code Generation

- 05.06.26 - ErcanOPAK comment on .NET Core: Use Source Generators for Compile-Time Code Generation

โš™๏ธ Write Code That Writes Code Reflection is slow. Source generators run at compile time. Generate JSON serializers, INotifyPropertyChanged, mappers โ€” zero runtime overhead. ๐Ÿ“ Simple Source Generator [Generator] public class HelloWorldGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { } public void Execute(GeneratorExecutionContext context) { string source = @” namespace Generated { public static […]

Read More
Git

Git: Use Git Bisect to Find Which Commit Introduced a Bug

- 05.06.26 - ErcanOPAK comment on Git: Use Git Bisect to Find Which Commit Introduced a Bug

๐Ÿ” Binary Search Through Git History Bug appeared sometime. Which commit? Git bisect does binary search through commits. Find culprit in O(log n) steps. ๐Ÿ”ง Manual Bisect # Start bisect git bisect start # Mark current commit as bad (bug exists) git bisect bad # Mark a known good commit (no bug) git bisect good […]

Read More
Ajax

Ajax: Use AbortController to Cancel In-flight Fetch Requests

- 05.06.26 - ErcanOPAK comment on Ajax: Use AbortController to Cancel In-flight Fetch Requests

๐Ÿ›‘ Stop Slow Requests When User Navigates User typed new search term? Old request still running. AbortController cancels fetch. Save bandwidth, avoid race conditions. ๐Ÿ“ Basic Usage const controller = new AbortController(); const signal = controller.signal; // Start request fetch(‘/api/search’, { signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(err => { if (err.name === […]

Read More
JavaScript

JavaScript: Use import.meta to Get Module Information

- 05.06.26 - ErcanOPAK comment on JavaScript: Use import.meta to Get Module Information

โ„น๏ธ Know Your Module’s URL, Resolve Paths Need to load assets relative to current file? import.meta gives you module URL, hot reload status, and more. ๐Ÿ“ import.meta.url // main.js console.log(import.meta.url); // “file:///C:/project/src/main.js” (Node.js) // “https://example.com/js/main.js” (browser) // Get directory of current module const modulePath = new URL(‘.’, import.meta.url).pathname; // Load sibling file dynamically const data […]

Read More
HTML

HTML: Use Inert Attribute to Temporarily Disable Sections

- 05.06.26 - ErcanOPAK comment on HTML: Use Inert Attribute to Temporarily Disable Sections

๐Ÿšซ Make Content Unclickable, Unfocusable, Invisible to Screen Readers Modal open? Background content should be ignored. inert attribute disables everything inside. ๐Ÿ“ Basic Usage <!– Main content with modal open –> <main inert> <button>Can’t click me!</button> <a href=”#”>Can’t focus me!</a> <input placeholder=”Can’t type here”> </main> <div class=”modal”> <h2>This is accessible</h2> <button onclick=”closeModal()”>Close</button> </div> <script> function […]

Read More
CSS

CSS: Use Variable Fonts for Multiple Weights in One File

- 05.06.26 - ErcanOPAK comment on CSS: Use Variable Fonts for Multiple Weights in One File

๐Ÿ“ฆ One Font File, Infinite Styles Normal fonts need separate files for each weight (400, 700). Variable fonts contain all weights in one file. Smaller total size, smoother transitions. ๐Ÿ“ Using Variable Fonts @font-face { font-family: ‘InterVariable’; src: url(‘InterVariable.woff2’) format(‘woff2’); font-weight: 100 900; /* Range of weights */ font-stretch: 75% 125%; /* Optional width range […]

Read More
Windows

Windows 11: Use Nearby Sharing to Send Files to Nearby PCs

- 05.06.26 - ErcanOPAK comment on Windows 11: Use Nearby Sharing to Send Files to Nearby PCs

๐Ÿ“ก Send Files Without USB, Email, or Cloud Need to send a file to the computer next to you? Nearby Sharing uses Bluetooth + Wi-Fi. Like Airdrop for Windows. ๐Ÿ”ง Enable Nearby Sharing Settings โ†’ System โ†’ Nearby sharing โ†’ On Choose: – Everyone nearby (anyone with Bluetooth) – My devices only (same Microsoft account) […]

Read More
AI

AI Prompt: Migrate Code from One Language to Another

- 05.06.26 - ErcanOPAK comment on AI Prompt: Migrate Code from One Language to Another

๐Ÿ”„ Convert Python to C#, Java to TypeScript Rewriting code manually is slow and error-prone. AI translates between languages preserving logic, edge cases, and structure. ๐Ÿ“ The Prompt Migrate the following code from [Source Language] to [Target Language]: [Paste source code here] Requirements: 1. Preserve exact logic and edge case handling 2. Use idiomatic patterns […]

Read More
Docker

Docker: Add Labels to Images for Better Organization

- 05.06.26 - ErcanOPAK comment on Docker: Add Labels to Images for Better Organization

๐Ÿท๏ธ Who Built This Image? When? Why? Image tags tell version. But who built it? Git commit? Labels add metadata. Filter images by label. Audit trail built-in. ๐Ÿ“ Add Labels in Dockerfile FROM node:18-alpine LABEL maintainer=”team@example.com” LABEL version=”1.2.3″ LABEL build-date=”2024-01-15″ LABEL git-commit=”a1b2c3d” LABEL description=”API service for user management” LABEL org.opencontainers.image.source=”https://github.com/example/repo” LABEL org.opencontainers.image.licenses=”MIT” # Multi-line labels […]

Read More
Kubernetes

Kubernetes: Use Topology Spread Constraints for Even Pod Distribution

- 05.06.26 - ErcanOPAK comment on Kubernetes: Use Topology Spread Constraints for Even Pod Distribution

๐Ÿ—บ๏ธ Spread Pods Across Zones, Nodes, Racks All pods on same node? Node failure = downtime. Topology spread constraints spread pods evenly across zones, nodes, or custom domains. ๐Ÿ“ Pod Topology Spread apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 6 template: spec: topologySpreadConstraints: – maxSkew: 1 topologyKey: kubernetes.io/hostname whenUnsatisfiable: DoNotSchedule labelSelector: matchLabels: app: […]

Read More
Wordpress

WordPress: Enqueue Scripts and Styles the Right Way

- 05.06.26 - ErcanOPAK comment on WordPress: Enqueue Scripts and Styles the Right Way

admin_url(‘admin-ajax.php’), ‘nonce’ => wp_create_nonce(‘my_nonce’) )); } add_action(‘wp_enqueue_scripts’, ‘my_theme_assets’); ๐ŸŽฏ Conditional Loading // Only on single post pages if (is_single()) { wp_enqueue_script(‘post-specific’, ‘…’); } // Only on contact page if (is_page(‘contact’)) { wp_enqueue_script(‘google-maps’, ‘https://maps.googleapis.com/…’); } // Only for logged-in users if (is_user_logged_in()) { wp_enqueue_script(‘logged-in’, ‘…’); } // Deregister unused scripts (performance) wp_deregister_script(‘wp-embed’); wp_dequeue_style(‘wp-block-library’); ๐Ÿ’ก Best Practices […]

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