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

C#

C#: Use ArgumentNullException.ThrowIfNull for Cleaner Validation

- 16.02.26 - ErcanOPAK comment on C#: Use ArgumentNullException.ThrowIfNull for Cleaner Validation

Manual null checks are verbose. C# 11 has built-in helper for cleaner validation. Old Way: public void ProcessUser(User user, string name, ILogger logger) { if (user == null) throw new ArgumentNullException(nameof(user)); if (name == null) throw new ArgumentNullException(nameof(name)); if (logger == null) throw new ArgumentNullException(nameof(logger)); // Actual logic… } New Way (C# 11): public void […]

Read More
C#

C#: Use Discard Pattern to Ignore Unwanted Values

- 16.02.26 - ErcanOPAK comment on C#: Use Discard Pattern to Ignore Unwanted Values

Variables you’ll never use clutter code. Discards (_) explicitly mark them as unused. Tuple Deconstruction: // Don’t need middle value var (first, _, last) = (“John”, “middle”, “Doe”); // Don’t need first two var (_, _, important) = GetThreeValues(); Out Parameters: // Only care if it parses, not the value if (int.TryParse(input, out _)) { […]

Read More
C#

C#: Use Deconstruction with Tuples for Cleaner Multiple Returns

- 16.02.26 - ErcanOPAK comment on C#: Use Deconstruction with Tuples for Cleaner Multiple Returns

Returning multiple values via out parameters is messy. Tuples with deconstruction are clean. Old Way (out parameters): public bool TryParse(string input, out int result, out string error) { // Ugly signature, can’t use in expressions } // Usage if (TryParse(input, out int result, out string error)) { // … } Tuple Return: public (bool success, […]

Read More
C#

C#: Use File-Scoped Types to Limit Class Visibility

- 16.02.26 - ErcanOPAK comment on C#: Use File-Scoped Types to Limit Class Visibility

Helper classes polluting your namespace? File-scoped types are only visible in their file. Problem: // HelperClass visible everywhere in project public class ProductService { // … } public class HelperClass // Only used by ProductService { // But visible to entire project! } Solution – File-Scoped Types: // ProductService.cs public class ProductService { private readonly […]

Read More
SQL

SQL: Use PIVOT to Transform Rows into Columns

- 16.02.26 - ErcanOPAK comment on SQL: Use PIVOT to Transform Rows into Columns

Displaying row data as columns manually requires complex CASE statements. PIVOT does it automatically. Source Data: Month Product Sales January Widget 100 January Gadget 150 February Widget 120 February Gadget 180 PIVOT Query: SELECT * FROM ( SELECT Month, Product, Sales FROM SalesData ) AS SourceTable PIVOT ( SUM(Sales) FOR Product IN ([Widget], [Gadget]) ) […]

Read More
SQL

SQL: Use MERGE OUTPUT to Track What Changed During Upsert

- 16.02.26 - ErcanOPAK comment on SQL: Use MERGE OUTPUT to Track What Changed During Upsert

After MERGE, don’t know what was inserted vs updated? OUTPUT clause captures the changes. MERGE with OUTPUT: MERGE INTO Products AS target USING @NewProducts AS source ON target.ProductId = source.ProductId WHEN MATCHED THEN UPDATE SET Price = source.Price WHEN NOT MATCHED THEN INSERT (ProductId, Name, Price) VALUES (source.ProductId, source.Name, source.Price) OUTPUT $action AS Action, INSERTED.ProductId, […]

Read More
Asp.Net Core

.NET Core: Use Polly for Resilient HTTP Requests with Retry Logic

- 16.02.26 - ErcanOPAK comment on .NET Core: Use Polly for Resilient HTTP Requests with Retry Logic

Network failures happen. Polly adds retry, circuit breaker, and timeout policies automatically. Install: dotnet add package Polly dotnet add package Microsoft.Extensions.Http.Polly Add to HttpClient: // Program.cs builder.Services.AddHttpClient(“MyAPI”, client => { client.BaseAddress = new Uri(“https://api.example.com”); }) .AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))) ) .AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(5, TimeSpan.FromMinutes(1)) ); Usage: public class MyService { private readonly […]

Read More
Asp.Net Core

.NET Core: Use Dapper for Lightweight ORM Alternative to Entity Framework

- 16.02.26 - ErcanOPAK comment on .NET Core: Use Dapper for Lightweight ORM Alternative to Entity Framework

Entity Framework too heavy for simple queries? Dapper is micro-ORM with near-raw SQL performance. Install: dotnet add package Dapper Basic Usage: using Dapper; using System.Data.SqlClient; var connection = new SqlConnection(connectionString); // Query (returns list) var users = connection.Query( “SELECT * FROM Users WHERE Age > @MinAge”, new { MinAge = 18 } ).ToList(); // Single […]

Read More
Git

Git: Use git sparse-checkout to Clone Only Specific Folders

- 16.02.26 - ErcanOPAK comment on Git: Use git sparse-checkout to Clone Only Specific Folders

Cloning huge repo when you only need one folder wastes time and disk. Sparse checkout downloads only what you need. Clone with Sparse Checkout: # Clone repository (no files yet) git clone –no-checkout https://github.com/user/repo.git cd repo # Enable sparse checkout git sparse-checkout init –cone # Specify folders you want git sparse-checkout set frontend/src backend/api # […]

Read More
Git

Git: Use git switch and git restore Instead of Confusing git checkout

- 16.02.26 - ErcanOPAK comment on Git: Use git switch and git restore Instead of Confusing git checkout

git checkout does too many things (switch branches, restore files, create branches). Git 2.23+ splits it into clear commands. Old Confusing Way: # Switch branch git checkout main # Create and switch to new branch git checkout -b feature # Restore file git checkout — file.txt # All same command! Confusing! New Clear Commands: # […]

Read More
Ajax

AJAX: Use Beacon API to Send Analytics Before Page Unload

- 16.02.26 - ErcanOPAK comment on AJAX: Use Beacon API to Send Analytics Before Page Unload

Regular fetch() in beforeunload is unreliable – browser may cancel it. Beacon API guarantees delivery. Problem with fetch(): window.addEventListener(‘beforeunload’, () => { fetch(‘/api/analytics’, { method: ‘POST’, body: JSON.stringify(data) }); // Browser often cancels this! }); Solution – Beacon API: window.addEventListener(‘beforeunload’, () => { navigator.sendBeacon(‘/api/analytics’, JSON.stringify({ timeSpent: Date.now() – pageLoadTime, scrollDepth: getScrollDepth(), clickData: clickTracker })); // […]

Read More
JavaScript

JavaScript: Use Proxy to Create Reactive Objects Without Framework

- 16.02.26 - ErcanOPAK comment on JavaScript: Use Proxy to Create Reactive Objects Without Framework

Frameworks like Vue use Proxy for reactivity. You can too – update UI automatically when data changes. Basic Reactive Object: const data = { count: 0, name: ‘John’ }; const reactive = new Proxy(data, { set(target, property, value) { target[property] = value; // Update UI automatically document.getElementById(property).textContent = value; console.log(`${property} changed to ${value}`); return true; […]

Read More
HTML

HTML5: Use meter Element for Visual Progress Indicators

- 16.02.26 - ErcanOPAK comment on HTML5: Use meter Element for Visual Progress Indicators

Creating progress bars with divs and CSS is complex. HTML5 meter shows value ranges natively. Basic Usage: <meter min=”0″ max=”100″ value=”75″>75%</meter> With Optimal Ranges: <meter min=”0″ max=”100″ low=”25″ high=”75″ optimum=”50″ value=”80″> 80% (High) </meter> <!– Browser colors bar automatically: 0-25: Red (low) 25-75: Yellow (medium) 75-100: Green (high) –> Use Cases: – Disk usage – […]

Read More
CSS

CSS: Use focus-visible Instead of focus for Better Accessibility

- 16.02.26 - ErcanOPAK comment on CSS: Use focus-visible Instead of focus for Better Accessibility

:focus shows outline on mouse clicks (annoying). :focus-visible shows only for keyboard navigation. Old Way (:focus): button:focus { outline: 2px solid blue; } /* Problem: Shows outline when clicked with mouse Users disable it: outline: none; (BAD for accessibility!) */ Better Way (:focus-visible): button:focus { outline: none; /* Remove default */ } button:focus-visible { outline: […]

Read More
Windows

Windows 11: Use Battery Report to See Detailed Battery Health

- 16.02.26 - ErcanOPAK comment on Windows 11: Use Battery Report to See Detailed Battery Health

Don’t know your battery’s real health? Windows generates detailed battery report from command line. Generate Report: # Run as Administrator powercfg /batteryreport # Output: C:\Windows\System32\battery-report.html Report Shows: – Design capacity vs current capacity – Battery health percentage – Charge/discharge history – Battery usage over time – Battery life estimates Example: Design Capacity: 50,000 mWh Full […]

Read More
Windows

Windows 11: Use Mouse Without Borders to Control Multiple PCs with One Keyboard/Mouse

- 16.02.26 - ErcanOPAK comment on Windows 11: Use Mouse Without Borders to Control Multiple PCs with One Keyboard/Mouse

Switching between multiple computers is annoying. Mouse Without Borders shares one keyboard/mouse across up to 4 PCs. Install: Download “Mouse Without Borders” from Microsoft Setup: 1. Install on all PCs 2. On first PC: Get security code 3. On other PCs: Enter that code 4. Done! Mouse moves seamlessly between screens Features: – Drag mouse […]

Read More
AI

AI Prompt: Review Code for Security Vulnerabilities

- 16.02.26 - ErcanOPAK comment on AI Prompt: Review Code for Security Vulnerabilities

Manual security reviews miss issues. AI scans code for common vulnerabilities comprehensively. The Prompt: Review this code for security vulnerabilities: [Paste code] Check for: 1. SQL Injection 2. XSS (Cross-Site Scripting) 3. CSRF vulnerabilities 4. Authentication issues 5. Authorization flaws 6. Input validation problems 7. Sensitive data exposure 8. Insecure dependencies 9. API security issues […]

Read More
AI

AI Prompt: Generate Database Schema from Description

- 16.02.26 - ErcanOPAK comment on AI Prompt: Generate Database Schema from Description

Designing database schema takes hours. AI creates normalized schema with relationships instantly. The Prompt: Design database schema for: [Describe your application] Requirements: 1. Normalized (3NF minimum) 2. Include primary keys, foreign keys 3. Add indexes for common queries 4. Specify data types (be specific) 5. Add constraints (NOT NULL, UNIQUE, etc.) 6. Show relationships (1:1, […]

Read More
AI

AI Prompt: Convert Requirements Document to User Stories

- 16.02.26 - ErcanOPAK comment on AI Prompt: Convert Requirements Document to User Stories

Writing user stories from requirements is tedious. AI converts them automatically in proper format. The Prompt: Convert these requirements to user stories: [Paste requirements document] Format each as: – As a [role] – I want [feature] – So that [benefit] Also include: – Acceptance criteria (Given/When/Then) – Story points estimate (1-13 scale) – Priority (High/Medium/Low) […]

Read More
Docker

Docker: Use ARG for Build-Time Variables and ENV for Runtime

- 16.02.26 - ErcanOPAK comment on Docker: Use ARG for Build-Time Variables and ENV for Runtime

Confusing ARG and ENV causes build issues. Know when to use each. ARG – Build-Time Only: FROM node:18 ARG NODE_ENV=production ARG API_URL=https://api.example.com RUN echo “Building for ${NODE_ENV}” RUN npm install –${NODE_ENV} # ARG values NOT available at runtime! Build with ARG: docker build –build-arg NODE_ENV=development -t myapp . ENV – Runtime Variables: FROM node:18 ENV […]

Read More
Kubernetes

Kubernetes: Use Secrets to Store Sensitive Data Instead of ConfigMaps

- 16.02.26 - ErcanOPAK comment on Kubernetes: Use Secrets to Store Sensitive Data Instead of ConfigMaps

Storing passwords in ConfigMaps exposes them in plain text. Secrets encode data and have better access control. Create Secret: kubectl create secret generic db-secret \ –from-literal=username=admin \ –from-literal=password=secretpass123 Use in Pod: apiVersion: v1 kind: Pod metadata: name: myapp spec: containers: – name: app image: myapp:1.0 env: – name: DB_USER valueFrom: secretKeyRef: name: db-secret key: username […]

Read More
Wordpress

WordPress: Use Action Scheduler for Background Processing

- 16.02.26 - ErcanOPAK comment on WordPress: Use Action Scheduler for Background Processing

Running heavy tasks on page load slows site. Action Scheduler queues tasks to run in background. Install: Built into WooCommerce, or install standalone “Action Scheduler” plugin Schedule Task: // Schedule single action as_schedule_single_action( time() + 3600, // 1 hour from now ‘my_custom_hook’, array(‘user_id’ => 123) // Arguments ); // Schedule recurring action (daily) as_schedule_recurring_action( time(), […]

Read More
Wordpress

WordPress: Use Object Caching with Redis to Speed Up Dynamic Sites

- 16.02.26 - ErcanOPAK comment on WordPress: Use Object Caching with Redis to Speed Up Dynamic Sites

Database queries on every page load are slow. Redis caches objects in memory for instant access. Install Redis Plugin: “Redis Object Cache” by Till Krüss Setup Redis Server: # Ubuntu/Debian sudo apt install redis-server sudo systemctl start redis sudo systemctl enable redis Configure WordPress (wp-config.php): define(‘WP_REDIS_HOST’, ‘127.0.0.1’); define(‘WP_REDIS_PORT’, 6379); define(‘WP_CACHE’, true); Enable in Plugin: Settings […]

Read More
Photoshop

Photoshop: Use Fill Content-Aware with Color Adaptation for Better Results

- 16.02.26 - ErcanOPAK comment on Photoshop: Use Fill Content-Aware with Color Adaptation for Better Results

Regular Content-Aware Fill sometimes creates visible seams. Color Adaptation setting makes fills blend perfectly. Steps: 1. Select area to fill 2. Edit → Content-Aware Fill (not just Fill) 3. In sidebar: Check “Color Adaptation” 4. Adjust sampling brush to exclude unwanted areas 5. Click OK What Color Adaptation Does: Blends colors from surrounding area seamlessly […]

Read More
Photoshop

Photoshop: Use Vanishing Point to Edit Perspective Correctly

- 16.02.26 - ErcanOPAK comment on Photoshop: Use Vanishing Point to Edit Perspective Correctly

Editing objects in perspective manually looks distorted. Vanishing Point maintains correct perspective automatically. Access: Filter → Vanishing Point How to Use: 1. Create Plane tool: Click 4 corners of a perspective surface (wall, floor, etc.) 2. Clone/Stamp/Paint within defined plane 3. Edits automatically match perspective! Use Cases: – Remove text from building wall – Clone […]

Read More
Visual Studio

Visual Studio: Use Peek Definition to View Code Without Opening Files

- 16.02.26 - ErcanOPAK comment on Visual Studio: Use Peek Definition to View Code Without Opening Files

Constantly opening files to check definitions? Peek Definition shows code inline without switching files. Use Peek: Right-click symbol → Peek Definition (or Alt+F12) Features: – Shows definition in popup window – Edit code directly in peek window – Navigate to related definitions – Multiple peeks can be open simultaneously Keyboard Navigation: – Alt+F12: Peek Definition […]

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 (831)
  • Get the First and Last Word from a String or Sentence in SQL (825)
  • 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 @ (573)
  • 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 (519)
  • 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 (831)
  • Get the First and Last Word from a String or Sentence in SQL (825)
  • 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