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

Month: May 2026

AI

AI Prompt: Analyze Log Files and Identify Error Patterns

- 28.05.26 - ErcanOPAK comment on AI Prompt: Analyze Log Files and Identify Error Patterns

๐Ÿ” AI Reads Your Logs So You Don’t Have To Thousand lines of logs. One needle in haystack. AI log analysis finds patterns, clusters errors, suggests fixes. ๐Ÿ“ Log Analysis Prompt Analyze these application logs and: 1. Identify the most frequent errors (top 5) 2. Find patterns in timestamps (does error spike at specific times?) […]

Read More
Docker

Docker: Add Health Checks to Detect Unhealthy Containers

- 28.05.26 - ErcanOPAK comment on Docker: Add Health Checks to Detect Unhealthy Containers

โค๏ธ Is Your Container Actually Working? Container running but app crashed? Health checks test if app is responsive. Automatically restart unhealthy containers. ๐Ÿ“ Dockerfile Healthcheck # Web app HEALTHCHECK –interval=30s –timeout=3s –start-period=5s –retries=3 \ CMD curl -f http://localhost/ || exit 1 # Database HEALTHCHECK –interval=30s –timeout=10s –retries=5 \ CMD pg_isready -U postgres || exit 1 […]

Read More
Kubernetes

Kubernetes: Use Network Policies to Restrict Pod Communication

- 28.05.26 - ErcanOPAK comment on Kubernetes: Use Network Policies to Restrict Pod Communication

๐Ÿ”’ Zero Trust for Pods By default, all pods can talk to all pods. That’s a security risk. Network policies define who can talk to whom. ๐Ÿ“ Deny All Ingress apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: deny-all-ingress spec: podSelector: {} # Applies to all pods policyTypes: – Ingress ingress: [] # Empty = deny all […]

Read More
Wordpress

WordPress: Create Custom URL Structures with Rewrite Rules

- 28.05.26 - ErcanOPAK comment on WordPress: Create Custom URL Structures with Rewrite Rules

๐Ÿ”— Beautiful URLs for Everything Want /events/2024/summer-festival instead of /?post_type=event&event_id=123? Rewrite rules create clean, SEO-friendly URLs. ๐Ÿ“ Basic Rewrite Rule function add_custom_rewrite_rules() { add_rewrite_rule( ‘^events/([0-9]{4})/([^/]+)/?$’, ‘index.php?post_type=event&year=$matches[1]&event_slug=$matches[2]’, ‘top’ ); } add_action(‘init’, ‘add_custom_rewrite_rules’); // Add query vars function add_query_vars($vars) { $vars[] = ‘year’; $vars[] = ‘event_slug’; return $vars; } add_filter(‘query_vars’, ‘add_query_vars’); // Flush rules after adding (visit […]

Read More
Photoshop

Photoshop: Use Adjustment Layers for Non-Destructive Color Correction

- 28.05.26 - ErcanOPAK comment on Photoshop: Use Adjustment Layers for Non-Destructive Color Correction

๐ŸŽจ Edit Colors Without Destroying Pixels Direct color changes = permanent. Adjustment layers sit above your image. Toggle on/off, change settings anytime, never lose original. ๐ŸŒ… Levels Adjust shadows, midtones, highlights. Fix underexposed or washed-out images. ๐ŸŽจ Hue/Saturation Change color cast, boost vibrance, or completely recolor specific ranges. ๐Ÿ“Š Curves Precise tonal control. Professional-grade color […]

Read More
Visual Studio

Visual Studio: Automate Code Formatting with Code Cleanup Profiles

- 28.05.26 - ErcanOPAK comment on Visual Studio: Automate Code Formatting with Code Cleanup Profiles

๐Ÿงน One Click, Whole File Formatted Remove unused usings, sort imports, fix spacing, apply conventions โ€” all automatically. Code Cleanup saves hours of manual formatting. ๐Ÿ”ง Set Up Profile Analyze โ†’ Code Cleanup โ†’ Configure Create profiles: – “Full Cleanup”: Remove/sort usings, format document, apply file header – “Quick Fix”: Only remove usings + format […]

Read More
C#

C#: Use Global Usings and Implicit Usings to Clean Up Files

- 27.05.26 - ErcanOPAK comment on C#: Use Global Usings and Implicit Usings to Clean Up Files

๐Ÿงน Remove Using Statements Forever Every file starts with 10 using statements? Global usings define once for entire project. Implicit usings add common ones automatically. ๐Ÿ“ฆ GlobalUsings.cs File // GlobalUsings.cs global using System; global using System.Collections.Generic; global using System.Linq; global using System.Threading.Tasks; global using Microsoft.Extensions.Logging; global using MyApp.Common; // Global using with alias global using […]

Read More
C#

C#: Use Pattern Matching and Switch Expressions for Cleaner Logic

- 27.05.26 - ErcanOPAK comment on C#: Use Pattern Matching and Switch Expressions for Cleaner Logic

๐ŸŽฏ Replace if-else Chains with Switch Expressions Type checking, property matching, tuple patterns โ€” switch expressions are more readable and less error-prone than long if-else. โŒ Old Way (Verbose) string GetDiscount(User user) { if (user == null) return “0%”; else if (user.Tier == “Gold”) return “20%”; else if (user.Tier == “Silver”) return “10%”; else if […]

Read More
SQL

SQL: Use EXPLAIN ANALYZE to Understand Slow Queries

- 27.05.26 - ErcanOPAK comment on SQL: Use EXPLAIN ANALYZE to Understand Slow Queries

๐Ÿ” Why Is My Query Slow? EXPLAIN ANALYZE shows exactly what the database does: table scans, index usage, join types, row estimates. The only real way to optimize. ๐Ÿ“ Basic Usage — PostgreSQL EXPLAIN ANALYZE SELECT * FROM users WHERE email = ‘alice@example.com’; — MySQL (no ANALYZE, use EXPLAIN only) EXPLAIN SELECT * FROM users […]

Read More
Asp.Net Core

.NET Core: IHostedService vs BackgroundService for Long-Running Tasks

- 27.05.26 - ErcanOPAK comment on .NET Core: IHostedService vs BackgroundService for Long-Running Tasks

โฐ Which One Should You Use? Both run background tasks. IHostedService gives full control. BackgroundService handles stop logic. Choose wisely. ๐Ÿ”ง IHostedService (Full Control) public class MyService : IHostedService { private Timer _timer; public Task StartAsync(CancellationToken ct) { _timer = new Timer(DoWork, null, 0, 1000); return Task.CompletedTask; } public Task StopAsync(CancellationToken ct) { _timer?.Dispose(); return […]

Read More
Git

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

- 27.05.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 the culprit in O(log n) steps. ๐Ÿ”ง Basic Bisect Workflow # Start bisect git bisect start # Mark current commit as bad (bug exists) git bisect bad # Mark a known good commit (no bug) git […]

Read More
Ajax

Ajax: Use Server-Sent Events (SSE) for Real-Time Updates Without WebSockets

- 27.05.26 - ErcanOPAK comment on Ajax: Use Server-Sent Events (SSE) for Real-Time Updates Without WebSockets

๐Ÿ“ก One-Way Real-Time from Server to Client Need server push but WebSockets are overkill? SSE sends updates from server to browser. Stock tickers, notifications, live feeds. ๐Ÿ“ Server-Side (Node.js Example) app.get(‘/events’, (req, res) => { res.writeHead(200, { ‘Content-Type’: ‘text/event-stream’, ‘Cache-Control’: ‘no-cache’, ‘Connection’: ‘keep-alive’ }); // Send data every 5 seconds const interval = setInterval(() => […]

Read More
JavaScript

JavaScript: Use Nullish Coalescing (??) Instead of || for Default Values

- 27.05.26 - ErcanOPAK comment on JavaScript: Use Nullish Coalescing (??) Instead of || for Default Values

?? vs || โ€” The Important Difference `||` treats 0, ”, false as falsy. `??` only checks `null` and `undefined`. Use ?? for default values. โŒ Logical OR (||) Trap const count = userInput || 10; // If userInput = 0 โ†’ count = 10 (WRONG!) const name = userName || ‘Guest’; // If userName […]

Read More
HTML

HTML: Use Details and Summary for Accordion Content Without JavaScript

- 27.05.26 - ErcanOPAK comment on HTML: Use Details and Summary for Accordion Content Without JavaScript

๐Ÿ“‚ Native Accordion, Zero JavaScript <details> and <summary> create expandable/collapsible sections. Works everywhere, no JS, accessible by default. ๐Ÿ“ Basic Usage <details> <summary>Click to expand</summary> <p>This content is hidden until you click the summary.</p> <ul> <li>Can contain any HTML</li> <li>Multiple lines</li> <li>Images, lists, anything!</li> </ul> </details> <details open> <summary>Expanded by default</summary> <p>Add the ‘open’ attribute […]

Read More
CSS

CSS: Use CSS Variables for Theming and Dynamic Styling

- 27.05.26 - ErcanOPAK comment on CSS: Use CSS Variables for Theming and Dynamic Styling

๐ŸŽจ One Variable Change, Whole Site Updates Sass variables compile once. CSS variables update at runtime. Dark mode, dynamic theming, component libraries โ€” finally possible. ๐Ÿ“ฆ Defining and Using Variables /* Define on :root (global) */ :root { –primary-color: #3498db; –secondary-color: #2ecc71; –spacing-unit: 8px; –border-radius: 4px; –font-size-base: 16px; } /* Use variables */ .button { […]

Read More
Windows

Windows 11: Enable Clipboard History to Copy Multiple Items

- 27.05.26 - ErcanOPAK comment on Windows 11: Enable Clipboard History to Copy Multiple Items

๐Ÿ“‹ Copy Once, Paste Many Times Default clipboard only holds one item. Clipboard history saves everything you copy. Access items from hours ago. ๐Ÿ”ง Enable Clipboard History Settings โ†’ System โ†’ Clipboard Or press Win + V โ†’ Turn on โŒจ๏ธ Shortcuts Win + V โ†’ Open clipboard history Win + V, then click โ†’ […]

Read More
AI

AI Prompt: Generate SQL Queries from Plain English Description

- 27.05.26 - ErcanOPAK comment on AI Prompt: Generate SQL Queries from Plain English Description

๐Ÿ—ฃ๏ธ “Show me users who ordered in last 30 days” โ†’ SQL Don’t remember JOIN syntax? AI generates SQL from natural language. Perfect for non-developers or when you’re stuck. ๐Ÿ“ The SQL Generation Prompt Given this database schema: Table: users – id (INT, PRIMARY KEY) – name (VARCHAR) – email (VARCHAR) – created_at (DATETIME) Table: […]

Read More
Docker

Docker: Use Docker Compose Profiles for Dev vs Production Services

- 27.05.26 | 27.05.26 - ErcanOPAK comment on Docker: Use Docker Compose Profiles for Dev vs Production Services

๐ŸŽญ One Compose File, Multiple Environments Don’t duplicate docker-compose.yml. Profiles start only the services you need for each environment. ๐Ÿ“ฆ docker-compose.yml with Profiles version: ‘3.8’ services: app: image: myapp:latest ports: – “8080:8080” profiles: [“prod”, “dev”] # Always start postgres: image: postgres:15 environment: POSTGRES_PASSWORD: secret profiles: [“prod”, “dev”] redis: image: redis:alpine profiles: [“prod”] # Only production […]

Read More
Kubernetes

Kubernetes: Readiness vs Liveness Probes โ€” What’s the Difference?

- 27.05.26 - ErcanOPAK comment on Kubernetes: Readiness vs Liveness Probes โ€” What’s the Difference?

โค๏ธ Is Your App Alive AND Ready? Liveness = restart if dead. Readiness = don’t send traffic until ready. Use both for zero-downtime deployments. ๐Ÿ’“ Liveness Probe livenessProbe: httpGet: path: /healthz port: 8080 initialDelaySeconds: 30 periodSeconds: 10 If fails โ†’ Kubernetes restarts container. โœ… Readiness Probe readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 5 periodSeconds: […]

Read More
Wordpress

WordPress: Replace WP-Cron with Real Cron for Scheduled Tasks

- 27.05.26 - ErcanOPAK comment on WordPress: Replace WP-Cron with Real Cron for Scheduled Tasks

โฐ WP-Cron Runs on Page Views โ€” That’s Bad WP-Cron triggers on visitor traffic. No visitors? Tasks never run. Replace with system cron for reliable scheduling. ๐Ÿ”ง Disable WP-Cron # Add to wp-config.php define(‘DISABLE_WP_CRON’, true); ๐Ÿ“ฆ Set Up System Cron # Every 5 minutes */5 * * * * wget -q -O – https://yoursite.com/wp-cron.php?doing_wp_cron >/dev/null […]

Read More
Photoshop

Photoshop: Master Blending Modes for Non-Destructive Effects

- 27.05.26 - ErcanOPAK comment on Photoshop: Master Blending Modes for Non-Destructive Effects

๐ŸŽจ Multiply, Screen, Overlay โ€” What’s the Difference? Blending modes change how layers interact. Multiply, Screen, Overlay, Soft Light โ€” master these and unlock professional effects. ๐ŸŒ‘ Multiply Darkens image. White becomes transparent. Great for shadows, adding density. Use for: Drop shadows, line art overlay โ˜€๏ธ Screen Lightens image. Black becomes transparent. Perfect for highlights, […]

Read More
Visual Studio

Visual Studio: Use IntelliCode for AI-Powered Code Completion

- 27.05.26 - ErcanOPAK comment on Visual Studio: Use IntelliCode for AI-Powered Code Completion

๐Ÿค– AI Knows What You’re About to Type IntelliCode analyzes your code patterns and suggests completions ranked by AI. GitHub Copilot Lite, built into VS. โœจ What IntelliCode Does Starred completions โ†’ Most likely API calls at top of list Style inference โ†’ Learns your naming conventions (camelCase, PascalCase) Code formatting โ†’ Applies team style […]

Read More
C#

C#: LINQ Performance Tips to Avoid Common Pitfalls

- 26.05.26 - ErcanOPAK comment on C#: LINQ Performance Tips to Avoid Common Pitfalls

โšก LINQ is Beautiful, But Know Its Cost LINQ makes code readable, but hidden performance traps exist. Multiple enumerations, wrong collection types, predicate order โ€” fix them all. โŒ Multiple Enumeration var filtered = items.Where(x => x.IsActive); // Executes query 3 times! var count = filtered.Count(); // Query executes var first = filtered.First(); // Query […]

Read More
C#

C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues

- 26.05.26 - ErcanOPAK comment on C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues

โšก Async All the Way Up Async/await is powerful but dangerous. Deadlocks, thread pool starvation, sync-over-async โ€” avoid common pitfalls with these patterns. โŒ Deadlock Pattern // UI or ASP.NET Context – DEADLOCK! public void Button_Click(object sender, EventArgs e) { var result = GetDataAsync().Result; // ๐Ÿ’€ DEADLOCK } public async Task GetDataAsync() { await Task.Delay(1000); […]

Read More
SQL

SQL: Clustered vs Non-Clustered Indexes Explained

- 26.05.26 - ErcanOPAK comment on SQL: Clustered vs Non-Clustered Indexes Explained

๐Ÿ“š The Phone Book vs The Library Catalog Clustered indexes physically order data (like phone book). Non-clustered indexes point to data (like library catalog). Choose wisely. ๐Ÿ“– Clustered Index Only one per table Physically reorders data Fast for range queries (BETWEEN, >,

Read More
Asp.Net Core

.NET Core: Understand Scoped, Transient, and Singleton Services

- 26.05.26 - ErcanOPAK comment on .NET Core: Understand Scoped, Transient, and Singleton Services

๐Ÿ”„ One Instance vs One Per Request Choosing wrong lifecycle = bugs, memory leaks, or poor performance. Transient, Scoped, Singleton โ€” each has its purpose. ๐ŸŸข Transient services.AddTransient<IMyService, MyService>(); Created every time requested. Best for lightweight, stateless services. ๐ŸŸก Scoped services.AddScoped<IMyService, MyService>(); One instance per HTTP request. Best for DbContext, request-scoped data. ๐Ÿ”ด Singleton services.AddSingleton<IMyService, […]

Read More
Git

Git: Use Git Stash to Temporarily Save Uncommitted Changes

- 26.05.26 - ErcanOPAK comment on Git: Use Git Stash to Temporarily Save Uncommitted Changes

๐Ÿ“ฆ Shelve Your Work in Progress Half-finished feature? Urgent bug on another branch? Git stash saves your uncommitted changes, cleans working directory, restores later. # Save changes to stash git stash # Save with message git stash save “WIP: login feature” # List all stashes git stash list # stash@{0}: On main: WIP: login feature […]

Read More
Ajax

Ajax: Why Axios is Better Than Fetch for HTTP Requests

- 26.05.26 - ErcanOPAK comment on Ajax: Why Axios is Better Than Fetch for HTTP Requests

๐ŸŒ Fetch is Good, Axios is Better Fetch requires response.ok check? No automatic JSON parsing? Axios handles errors, transforms JSON, supports progress, and works in Node.js. โŒ Fetch (More Boilerplate) try { const res = await fetch(url); if (!res.ok) throw new Error(‘HTTP error’); const data = await res.json(); } catch (err) { console.error(err); } โœ… […]

Read More
JavaScript

JavaScript: Use Optional Chaining (?.) to Avoid Cannot Read Property of Undefined

- 26.05.26 - ErcanOPAK comment on JavaScript: Use Optional Chaining (?.) to Avoid Cannot Read Property of Undefined

๐Ÿ”— Stop the Cannot Read Property Error Optional chaining (?.) safely accesses nested properties. No more Cannot read property ‘x’ of undefined. โŒ Old Way (Crash-prone) // ๐Ÿ’ฅ CRASH if user or address is undefined const city = user.address.city; // Verbose fix let city = ‘Unknown’; if (user && user.address) { city = user.address.city; } […]

Read More
HTML

HTML: Use Picture Element and srcset for Responsive Images

- 26.05.26 - ErcanOPAK comment on HTML: Use Picture Element and srcset for Responsive Images

๐Ÿ–ผ๏ธ Serve the Right Image to Every Device Mobile users downloading 4K images? Picture element and srcset serve different images based on screen size, resolution, and format support. ๐Ÿ“ฑ srcset: Different Resolutions <img src=”image-800.jpg” srcset=”image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w, image-1600.jpg 1600w” sizes=”(max-width: 600px) 400px, (max-width: 1200px) 800px, 1200px” alt=”Responsive image”> ๐ŸŽจ Picture: Art Direction […]

Read More
Page 4 of 5
ยซ Previous 1 2 3 4 5 Next ยป

Posts pagination

« Previous 1 2 3 4 5 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)
  • 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 (538)
  • 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 (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