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

C#

C#: Use Raw String Literals for Multi-line Strings and JSON

- 31.05.26 | 31.05.26 - ErcanOPAK comment on C#: Use Raw String Literals for Multi-line Strings and JSON

๐Ÿ“ JSON, SQL, HTML in Your Code โ€” Without Escaping Escaping quotes in strings is painful. Raw string literals (C# 11) allow any quotes, any whitespace. Copy-paste JSON directly! โŒ Old Way (Escaping Hell) string json = “{\n \”name\”: \”Alice\”,\n \”age\”: 30\n}”; โœ… Raw String Literal string json = “”” { “name”: “Alice”, “age”: 30 […]

Read More
C#

C#: Use Required Keyword to Enforce Property Initialization

- 31.05.26 | 31.05.26 - ErcanOPAK comment on C#: Use Required Keyword to Enforce Property Initialization

  โœ… No More Null Reference Warnings NonNullable properties should never be null. But how to enforce? required keyword makes initialization mandatory at compile time. โŒ Before (Runtime Null) public class User { public string Name { get; set; } // Can be null! } var user = new User(); // Name = null user.Name.Length; […]

Read More
SQL

SQL: Use LATERAL Joins to Reference Previous Rows

- 31.05.26 - ErcanOPAK comment on SQL: Use LATERAL Joins to Reference Previous Rows

๐Ÿ”„ Lateral Joins = Subquery That Can Reference Outer Table Normal subqueries run independently. LATERAL subquery runs for each row, can reference columns from outer query. ๐Ÿ“ Without LATERAL (Limited) — Can’t reference outer user_id SELECT u.name, ( SELECT order_date FROM orders WHERE user_id = u.id ORDER BY order_date DESC LIMIT 1 ) as last_order […]

Read More
Asp.Net Core

.NET Core: Add Rate Limiting to Protect Your API from Abuse

- 31.05.26 - ErcanOPAK comment on .NET Core: Add Rate Limiting to Protect Your API from Abuse

๐Ÿ›ก๏ธ Prevent DDoS and Brute Force Rate limiting stops attackers (and misbehaving clients). .NET 7+ has built-in rate limiting. No external libraries needed. ๐Ÿ“ Setup Rate Limiting // Program.cs builder.Services.AddRateLimiter(options => { // Global rate limit options.GlobalLimiter = PartitionedRateLimiter.Create( httpContext => RateLimitPartition.GetFixedWindowLimiter( partitionKey: httpContext.User.Identity?.Name ?? httpContext.Request.Headers.Host.ToString(), factory: partition => new FixedWindowRateLimiterOptions { AutoReplenishment = true, […]

Read More
Git

Git: Use Filter-Branch to Remove Sensitive Data from History

- 31.05.26 - ErcanOPAK comment on Git: Use Filter-Branch to Remove Sensitive Data from History

๐Ÿ”ฅ Committed Secrets? Erase from History .env file committed. Now in Git history forever. git filter-branch rewrites history. Remove sensitive files completely. ๐Ÿ”ง Remove File from History # Backup your repository first! git clone –mirror your-repo repo-backup # Remove .env file from entire history git filter-branch –force –index-filter \ ‘git rm –cached –ignore-unmatch .env’ \ […]

Read More
Ajax

Ajax: Use Compression Streams to Send Large Data Efficiently

- 31.05.26 - ErcanOPAK comment on Ajax: Use Compression Streams to Send Large Data Efficiently

๐Ÿ—œ๏ธ Compress Data Before Sending Send huge JSON? Compress it first. Compression Streams API compresses in browser before upload. Save bandwidth, faster uploads. ๐Ÿ“ Compress and Send async function sendCompressed(data) { // Convert to JSON string const jsonString = JSON.stringify(data); // Compress with GZIP const compressedStream = new Blob([jsonString]) .stream() .pipeThrough(new CompressionStream(‘gzip’)); // Send compressed […]

Read More
JavaScript

JavaScript: Use Temporal API for Modern Date and Time Handling

- 31.05.26 - ErcanOPAK comment on JavaScript: Use Temporal API for Modern Date and Time Handling

๐Ÿ“… Finally, a Good Date API Date object is broken (months are 0-indexed, mutates, timezone issues). Temporal fixes everything. Immutable, timezone-aware, intuitive. ๐Ÿ“ Temporal Basics // Current date/time const now = Temporal.Now.zonedDateTimeISO(); // with timezone const today = Temporal.Now.plainDateISO(); // date only const time = Temporal.Now.plainTimeISO(); // time only // Create dates (months are 1-indexed!) […]

Read More
HTML

HTML: Use Popover API for Native Tooltips and Popups

- 31.05.26 - ErcanOPAK comment on HTML: Use Popover API for Native Tooltips and Popups

๐Ÿ’ฌ No More JavaScript for Tooltips Popover API creates native popups, tooltips, and menus. Light dismiss (click outside closes), top layer, accessible. No more Tippy.js or Popper. ๐Ÿ“ Basic Popover <button popovertarget=”my-popover”>Toggle Popover</button> <div id=”my-popover” popover> <h3>Popover Title</h3> <p>This is a native popover! Click outside to close.</p> <button popovertarget=”my-popover” popovertargetaction=”hide”>Close</button> </div> <!– Manual popover –> […]

Read More
CSS

CSS: Use New Color Functions for Dynamic Theming

- 31.05.26 - ErcanOPAK comment on CSS: Use New Color Functions for Dynamic Theming

๐ŸŽจ Color Manipulation Without Preprocessors Sass had lighten(), darken(), mix(). CSS now has color-mix(), relative colors, and OKLCH. Native color functions! ๐ŸŽจ color-mix() /* Mix two colors */ .hover-effect { background-color: color-mix(in srgb, blue 30%, red); } .brand-gradient { background: color-mix(in oklch, var(–primary) 50%, white); } /* Mix with transparency */ .transparent-blue { background: color-mix(in […]

Read More
Windows

Windows 11: Enable Game Mode for Better Gaming Performance

- 31.05.26 - ErcanOPAK comment on Windows 11: Enable Game Mode for Better Gaming Performance

๐ŸŽฎ Stop Background Processes from Stealing FPS Windows Update, antivirus scans, OneDrive sync โ€” all kill gaming performance. Game Mode prioritizes your game, pauses background tasks. ๐Ÿ”ง Enable Game Mode Settings โ†’ Gaming โ†’ Game Mode โ†’ On Win + G โ†’ Game Bar (check if Game Mode active) Per-game settings: Settings โ†’ Gaming โ†’ […]

Read More
AI

AI Prompt: Generate Meeting Summaries from Transcripts

- 31.05.26 - ErcanOPAK comment on AI Prompt: Generate Meeting Summaries from Transcripts

๐Ÿ“ Never Write Meeting Notes Again Hours of meeting recordings. Who said what? What was decided? AI turns transcripts into actionable summaries. ๐Ÿ“ The Prompt Generate a concise meeting summary from this transcript: [Paste meeting transcript here] Include: 1. One-sentence overview of the meeting purpose 2. Key decisions made (bullet points) 3. Action items with […]

Read More
Docker

Docker: Use Docker Scout to Find Vulnerabilities in Your Images

- 31.05.26 - ErcanOPAK comment on Docker: Use Docker Scout to Find Vulnerabilities in Your Images

๐Ÿ›ก๏ธ Is Your Image Safe? Base images have known vulnerabilities. Docker Scout scans images for CVEs. Shows severity, fix versions, and remediation steps. ๐Ÿ”ง Scan Image # Install Docker Scout (Docker Desktop includes it) docker scout –help # Scan local image docker scout quick myapp:latest # Scan with detailed output docker scout cves myapp:latest # […]

Read More
Kubernetes

Kubernetes: Use VPA to Automatically Adjust CPU/Memory Requests

- 31.05.26 - ErcanOPAK comment on Kubernetes: Use VPA to Automatically Adjust CPU/Memory Requests

๐Ÿ“ˆ HPA Scales Pods. VPA Scales Pod Resources. Guessing CPU/memory requests is hard. Vertical Pod Autoscaler recommends or automatically adjusts resource requests based on actual usage. ๐Ÿ“ Install VPA git clone https://github.com/kubernetes/autoscaler.git cd autoscaler/vertical-pod-autoscaler ./hack/vpa-up.sh kubectl get pods -n kube-system | grep vpa ๐ŸŽฏ VPA Configuration apiVersion: autoscaling.k8s.io/v1 kind: VerticalPodAutoscaler metadata: name: myapp-vpa spec: targetRef: […]

Read More
Wordpress

WordPress: WP_Query Best Practices to Avoid Performance Pitfalls

- 31.05.26 - ErcanOPAK comment on WordPress: WP_Query Best Practices to Avoid Performance Pitfalls

โšก Don’t Let WP_Query Kill Your Database WP_Query is powerful but dangerous. Bad queries = slow site. Learn best practices for performance. ๐Ÿ“ Do’s and Don’ts // โŒ DON’T: Query inside loop while (have_posts()) { the_post(); $related = new WP_Query([‘post_type’ => ‘post’, ‘posts_per_page’ => 5]); // Runs 10 times = 10 extra queries! } // […]

Read More
Photoshop

Photoshop: Use Vanishing Point to Edit in Perspective

- 31.05.26 - ErcanOPAK comment on Photoshop: Use Vanishing Point to Edit in Perspective

๐Ÿข Put a Picture on a Building That Matches Perspective Normal clone stamp doesn’t understand perspective. Vanishing Point lets you paint, clone, and paste in perspective. Perfect for billboards, walls, floors. ๐Ÿ“ How to Use 1. Filter โ†’ Vanishing Point (Ctrl+Alt+V) 2. Click to create plane (4 points) 3. Adjust grid (blue lines should match […]

Read More
Visual Studio

Visual Studio: Press Ctrl + , to Search Anything Instantly

- 31.05.26 - ErcanOPAK comment on Visual Studio: Press Ctrl + , to Search Anything Instantly

๐Ÿ” Find Any File, Type, Member, Symbol Solution Explorer is slow. Ctrl + , (Navigate To) searches everything: files, classes, methods, properties. Type a few letters, press Enter. โŒจ๏ธ How to Use Ctrl + , โ†’ Open search box Type “OrderService” โ†’ Shows matching files, classes, methods โ†“ โ†‘ arrows โ†’ Navigate results Enter โ†’ […]

Read More
C#

C#: Use File-Scoped Namespaces to Remove One Level of Indentation

- 31.05.26 - ErcanOPAK comment on C#: Use File-Scoped Namespaces to Remove One Level of Indentation

๐Ÿ“ Every File Starts with namespace Something { } That’s an extra indentation for no reason. File-scoped namespaces remove the braces. Less code, less indentation. โŒ Old Style namespace MyApp.Services { public class OrderService { public void Process() { // Code indented 3 levels already } } } โœ… File-Scoped namespace MyApp.Services; public class OrderService […]

Read More
C#

C#: Advanced String Interpolation Tricks You Didn’t Know

- 31.05.26 - ErcanOPAK comment on C#: Advanced String Interpolation Tricks You Didn’t Know

โœจ More Than Just ${variable} String interpolation can format numbers, align text, use expressions, and even span multiple lines. Level up your strings. ๐Ÿ“ Formatting Numbers double price = 1234.5678; string formatted = $”Price: {price:C2}”; // $1,234.57 formatted = $”Percent: {0.1234:P1}”; // 12.3% formatted = $”{price:N0}”; // 1,235 formatted = $”{price:F2}”; // 1234.57 formatted = […]

Read More
SQL

SQL: Use CTEs to Write Readable Complex Queries

- 31.05.26 - ErcanOPAK comment on SQL: Use CTEs to Write Readable Complex Queries

๐Ÿ“ Name Your Subqueries Subqueries inside subqueries are unreadable. CTEs (WITH clause) give subqueries names. Your future self will thank you. ๐Ÿ“ Without CTE (Unreadable) SELECT name, total_orders FROM ( SELECT u.name, COUNT(o.id) as total_orders FROM users u JOIN orders o ON u.id = o.user_id WHERE o.status = ‘completed’ GROUP BY u.id, u.name ) order_stats […]

Read More
Asp.Net Core

.NET Core: Add Health Checks to Monitor Your App’s Status

- 31.05.26 - ErcanOPAK comment on .NET Core: Add Health Checks to Monitor Your App’s Status

โค๏ธ Is Your App Really Healthy? App running but database down? Cache not responding? Health checks test dependencies. Perfect for load balancer readiness probes. ๐Ÿ“ Basic Setup // Program.cs builder.Services.AddHealthChecks() .AddDbContextCheck() .AddUrlGroup(new Uri(“https://api.example.com”)) var app = builder.Build(); app.MapHealthChecks(“/health/ready”, new HealthCheckOptions { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); app.MapHealthChecks(“/health/live”, new HealthCheckOptions { Predicate […]

Read More
Git

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

- 31.05.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? Format code? Git hooks automate anything. No more forgotten steps. ๐Ÿ“ Available Hooks .git/hooks/ (create executable files) Client-side: – pre-commit # Run tests before commit (cancel if fails) – prepare-commit-msg # Edit commit message before editor opens – commit-msg # Validate […]

Read More
Ajax

Ajax: Understanding CORS and How to Fix It

- 31.05.26 - ErcanOPAK comment on Ajax: Understanding CORS and How to Fix It

๐ŸŒ “No ‘Access-Control-Allow-Origin’” โ€” The Most Hated Error CORS blocks requests from different origins. Fix it on the server, not on the client. Here’s how. ๐Ÿ“ Server Fixes // Node.js (Express) app.use((req, res, next) => { res.header(‘Access-Control-Allow-Origin’, ‘*’); // Allow all (not for prod) res.header(‘Access-Control-Allow-Methods’, ‘GET, POST, PUT, DELETE’); res.header(‘Access-Control-Allow-Headers’, ‘Content-Type, Authorization’); res.header(‘Access-Control-Allow-Credentials’, ‘true’); if […]

Read More
JavaScript

JavaScript: Use Atomics for Thread-Safe Shared Memory with Web Workers

- 31.05.26 - ErcanOPAK comment on JavaScript: Use Atomics for Thread-Safe Shared Memory with Web Workers

๐Ÿงต Multiple Threads, One Memory Web Workers communicate via message passing. SharedArrayBuffer + Atomics enables shared memory. No copying. True multithreading. ๐Ÿ“ Basic Shared Memory // Main thread const sharedBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * 2); const sharedArray = new Int32Array(sharedBuffer); sharedArray[0] = 0; // Counter const worker = new Worker(‘worker.js’); worker.postMessage(sharedBuffer); // Transfer, not copy! […]

Read More
HTML

HTML: Use Inputmode to Show the Right Mobile Keyboard

- 31.05.26 - ErcanOPAK comment on HTML: Use Inputmode to Show the Right Mobile Keyboard

๐Ÿ“ฑ Number Field Shows Number Keyboard type=’number’ has spinner buttons. type=’tel’ shows number keyboard but no spinner. inputmode controls keyboard without changing validation. ๐Ÿ“ Input Mode Values <!– Numeric keyboard (no spinner) –> <input type=’text’ inputmode=’numeric’ placeholder=’Age’> <!– Decimal keyboard (with dot) –> <input type=’text’ inputmode=’decimal’ placeholder=’Price’> <!– Email keyboard (@ and .com) –> <input […]

Read More
CSS

CSS: Use Accent Color to Style Checkboxes and Radio Buttons

- 31.05.26 - ErcanOPAK comment on CSS: Use Accent Color to Style Checkboxes and Radio Buttons

๐ŸŽจ One Line, Beautiful Checkboxes Customizing checkboxes used to require JavaScript or CSS hacks. accent-color changes their color in one line. ๐Ÿ“ Basic Usage /* Apply to all form controls */ body { accent-color: #3498db; } /* Specific controls */ input[type=’checkbox’] { accent-color: #2ecc71; } input[type=’radio’] { accent-color: #e74c3c; } input[type=’range’] { accent-color: #f39c12; } […]

Read More
Windows

Windows 11: Use Memory Diagnostic Tool to Find Faulty RAM

- 31.05.26 - ErcanOPAK comment on Windows 11: Use Memory Diagnostic Tool to Find Faulty RAM

๐Ÿงช Random Crashes? Test Your RAM PC freezing? Blue screens? Windows Memory Diagnostic tests RAM for errors. Find faulty memory before buying new parts. ๐Ÿ”ง How to Run Method 1: Start โ†’ Windows Memory Diagnostic Method 2: Win + R โ†’ mdsched.exe Method 3: Control Panel โ†’ Administrative Tools โ†’ Windows Memory Diagnostic Choose: – […]

Read More
AI

AI Prompt: Generate Regex Patterns from Examples

- 31.05.26 - ErcanOPAK comment on AI Prompt: Generate Regex Patterns from Examples

๐Ÿ” Regular Expressions Are Hard. AI Makes Them Easy. Need to extract emails? Phone numbers? Dates? AI generates regex from examples. No more regex debugging hell. ๐Ÿ“ The Prompt Generate a regular expression that matches: [Provide examples of what you want to match] Example inputs that SHOULD match: – [example 1] – [example 2] – […]

Read More
Docker

Docker: Use .dockerignore to Speed Up Builds and Reduce Image Size

- 31.05.26 - ErcanOPAK comment on Docker: Use .dockerignore to Speed Up Builds and Reduce Image Size

๐Ÿšซ .git folder in Docker Image? No! Docker sends entire folder to daemon. .dockerignore excludes unnecessary files. Faster builds, smaller images, less clutter. ๐Ÿ“ .dockerignore Example # Git .git/ .gitignore # Node node_modules/ npm-debug.log # .NET bin/ obj/ *.user *.suo # Tests test/ __tests__/ coverage/ # Logs *.log logs/ # Environment .env .env.local .env.*.local # […]

Read More
Kubernetes

Kubernetes: Use Pod Affinity to Schedule Related Pods Together

- 31.05.26 - ErcanOPAK comment on Kubernetes: Use Pod Affinity to Schedule Related Pods Together

๐Ÿ‘ฏ Keep Related Pods Close (or Far Apart) Cache and app should be on same node. Database replicas should be on different nodes. Pod affinity/anti-affinity controls pod placement. ๐Ÿ“ Pod Affinity (Same Node) apiVersion: v1 kind: Pod metadata: name: web-app spec: affinity: podAffinity: requiredDuringSchedulingIgnoredDuringExecution: – labelSelector: matchLabels: app: cache topologyKey: kubernetes.io/hostname containers: – name: app […]

Read More
Wordpress

WordPress: Run Custom SQL Queries with $wpdb Object

- 31.05.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. Faster, more powerful, full control. ๐Ÿ“ 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 5
1 2 3 4 5 Next ยป

Posts pagination

1 2 3 … 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)
  • Add Constraint to SQL Table to ensure email contains @ (580)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (579)
  • 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 (454)

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