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

Author: ErcanOPAK

C#

C#: Use nameof() Operator to Avoid Magic Strings

- 22.02.26 | 22.02.26 - ErcanOPAK comment on C#: Use nameof() Operator to Avoid Magic Strings

Hardcoded property names break on refactoring. nameof() generates string from code symbol safely. ❌ Magic String (Breaks on Rename): public class User { public string Name { get; set; } } // Later in code: if (propertyName == “Name”) // Typo-prone, breaks if User.Name renamed! ✅ nameof (Refactor-Safe): if (propertyName == nameof(User.Name)) // Compile-time checked! […]

Read More
C#

C#: Use async/await All The Way – Don’t Block

- 22.02.26 | 22.02.26 - ErcanOPAK comment on C#: Use async/await All The Way – Don’t Block

Mixing async and blocking (.Result, .Wait()) causes deadlocks. Go async all the way! ❌ Deadlock Prone: public void DoWork() { var result = GetDataAsync().Result; // DEADLOCK risk! } public async Task GetDataAsync() { return await httpClient.GetFromJsonAsync(url); } ✅ Proper Async: public async Task DoWorkAsync() { var result = await GetDataAsync(); // No blocking! } public […]

Read More
C#

C#: Use using Statement for Automatic Resource Disposal

- 22.02.26 | 22.02.26 - ErcanOPAK comment on C#: Use using Statement for Automatic Resource Disposal

Forgetting to dispose resources causes memory leaks. using statement guarantees disposal even if exception occurs. ❌ Manual Disposal (Risky): var stream = File.OpenRead(“file.txt”); // If exception here, stream never closed! var data = ReadData(stream); stream.Dispose(); ✅ Automatic (Safe): using (var stream = File.OpenRead(“file.txt”)) { var data = ReadData(stream); } // stream.Dispose() called automatically, even on […]

Read More
C#

C#: Use StringBuilder for String Concatenation in Loops

- 22.02.26 | 22.02.26 - ErcanOPAK comment on C#: Use StringBuilder for String Concatenation in Loops

String concatenation in loops creates tons of objects. StringBuilder is 100x faster. ❌ Slow (String Concat): string result = “”; for (int i = 0; i < 10000; i++) { result += i.ToString(); // Creates new string each time! } // 10,000 string objects created = slow + GC pressure ✅ Fast (StringBuilder): var sb […]

Read More
SQL

SQL: Use EXISTS Instead of IN for Better Performance

- 22.02.26 | 22.02.26 - ErcanOPAK comment on SQL: Use EXISTS Instead of IN for Better Performance

IN processes entire subquery. EXISTS stops at first match (faster). Slow (IN): SELECT * FROM Customers WHERE CustomerId IN ( SELECT CustomerId FROM Orders WHERE Total > 1000 ); — Processes ALL matching orders Fast (EXISTS): SELECT * FROM Customers c WHERE EXISTS ( SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId AND o.Total […]

Read More
SQL

SQL: Use UNION ALL Instead of UNION When Duplicates Don’t Matter

- 22.02.26 | 22.02.26 - ErcanOPAK comment on SQL: Use UNION ALL Instead of UNION When Duplicates Don’t Matter

UNION removes duplicates (expensive operation). UNION ALL keeps them (fast). UNION (Slow): SELECT Name FROM ActiveUsers UNION SELECT Name FROM InactiveUsers; — Removes duplicates: Sorts, scans, filters — Slow on large datasets! UNION ALL (Fast): SELECT Name FROM ActiveUsers UNION ALL SELECT Name FROM InactiveUsers; — Keeps duplicates: No sorting or filtering — Much faster! […]

Read More
Asp.Net Core

.NET Core: Use HttpClientFactory to Prevent Socket Exhaustion

- 22.02.26 | 22.02.26 - ErcanOPAK comment on .NET Core: Use HttpClientFactory to Prevent Socket Exhaustion

Creating new HttpClient instances exhausts sockets. HttpClientFactory manages client lifecycle properly. ❌ Wrong: using var client = new HttpClient(); // Socket exhaustion! var response = await client.GetAsync(url); ✅ Right: // Program.cs builder.Services.AddHttpClient(“MyAPI”, client => { client.BaseAddress = new Uri(“https://api.example.com”); }); // Service public class MyService { private readonly IHttpClientFactory _factory; public MyService(IHttpClientFactory factory) { _factory […]

Read More
Asp.Net Core

.NET Core: Use ActionFilters for Cross-Cutting Concerns

- 22.02.26 | 22.02.26 - ErcanOPAK comment on .NET Core: Use ActionFilters for Cross-Cutting Concerns

Logging, validation, auth in every controller is repetitive. ActionFilters apply logic globally or per-controller. Create Filter: public class LoggingFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { // Before action Console.WriteLine($”Executing: {context.ActionDescriptor.DisplayName}”); } public void OnActionExecuted(ActionExecutedContext context) { // After action Console.WriteLine($”Executed: {context.ActionDescriptor.DisplayName}”); } } Apply Globally: builder.Services.AddControllers(options => { options.Filters.Add(); }); Or apply to […]

Read More
Git

Git: Use git commit –amend to Fix Last Commit Without New Commit

- 22.02.26 | 22.02.26 - ErcanOPAK comment on Git: Use git commit –amend to Fix Last Commit Without New Commit

Forgot to add file or typo in commit message? –amend fixes last commit without creating new one. Fix Commit Message: git commit –amend -m “Corrected message” Add Forgotten Files: git add forgotten_file.js git commit –amend –no-edit # Add to last commit, keep message ⚠️ Warning: Never amend commits that are already pushed! Rewrites history = […]

Read More
Git

Git: Use git diff –staged to Review Changes Before Commit

- 22.02.26 | 22.02.26 - ErcanOPAK comment on Git: Use git diff –staged to Review Changes Before Commit

Committing without review leads to mistakes. –staged shows exactly what will be committed. See Staged Changes: git diff –staged # Shows changes that are staged (git add-ed) for commit vs git diff: git diff (no flags) shows unstaged changes only. –staged shows what’s going into the commit. Review Workflow: git add . git diff –staged […]

Read More
Ajax

AJAX: Use Response Type for Automatic Data Parsing

- 22.02.26 | 22.02.26 - ErcanOPAK comment on AJAX: Use Response Type for Automatic Data Parsing

Manually parsing response JSON is error-prone. Set responseType to let fetch handle it. Manual Parsing: const response = await fetch(url); const text = await response.text(); const data = JSON.parse(text); // Error-prone! Automatic: const response = await fetch(url); const data = await response.json(); // Automatic! // Or for blob: const blob = await response.blob(); // Or […]

Read More
JavaScript

JavaScript: Use globalThis for Universal Global Object Access

- 22.02.26 - ErcanOPAK comment on JavaScript: Use globalThis for Universal Global Object Access

Accessing global object is different everywhere: window (browser), global (Node), self (workers). globalThis works everywhere. The Problem: // Browser window.myVar = ‘test’; // Works // Node.js global.myVar = ‘test’; // Works // Web Worker self.myVar = ‘test’; // Works Universal Solution: globalThis.myVar = ‘test’; // Works everywhere! Write once, run in browser, Node, workers, Deno […]

Read More
HTML

HTML5: Use the dialog Element for Native Modal Dialogs

- 22.02.26 | 22.02.26 - ErcanOPAK comment on HTML5: Use the dialog Element for Native Modal Dialogs

Building modals with divs and JavaScript is complex. HTML5 dialog element provides native modal functionality. Basic Usage:   Modal Title   Modal content here Close   Open Modal Features: Automatic backdrop, ESC key closes, focus trap, accessible by default! Styling: dialog::backdrop for backdrop styling. Fully customizable with CSS. Native, accessible, no library needed!

Read More
CSS

CSS: Use :is() and :where() to Simplify Complex Selectors

- 22.02.26 - ErcanOPAK comment on CSS: Use :is() and :where() to Simplify Complex Selectors

Writing the same selector multiple times is verbose. :is() groups them cleanly. Old Way (Verbose): header h1, header h2, header h3, footer h1, footer h2, footer h3 { color: blue; } With :is(): :is(header, footer) :is(h1, h2, h3) { color: blue; } :where() vs :is(): Same syntax, but :where() has 0 specificity (won’t override other […]

Read More
Windows

Windows 11: Use Efficiency Mode to Limit Resource-Hungry Apps

- 22.02.26 - ErcanOPAK comment on Windows 11: Use Efficiency Mode to Limit Resource-Hungry Apps

Chrome eating all your RAM? Efficiency Mode throttles resource usage of specific processes. Enable: Task Manager → Processes tab → Right-click app → Efficiency Mode What It Does: Lowers process priority, reduces CPU usage, limits background activity. App still runs but uses fewer resources. Perfect For: Apps you keep open but rarely use actively (Slack, […]

Read More
Windows

Windows 11: Use Dynamic Refresh Rate for Better Battery Life

- 22.02.26 - ErcanOPAK comment on Windows 11: Use Dynamic Refresh Rate for Better Battery Life

Running 120Hz constantly drains battery. Dynamic Refresh Rate adjusts automatically based on content. Enable: Settings → System → Display → Advanced Display → Choose Refresh Rate → Dynamic How It Works: Scrolling/gaming = 120Hz. Static content = 60Hz. Battery life improves 20-30% on laptops! Requirements: Display that supports variable refresh rate (VRR). Most modern gaming […]

Read More
AI

AI Prompt: Optimize SQL Queries with Execution Plan Analysis

- 22.02.26 - ErcanOPAK comment on AI Prompt: Optimize SQL Queries with Execution Plan Analysis

Slow query but don’t know why? AI analyzes execution plans and suggests optimizations. The Prompt: Optimize this SQL query: [Paste SQL query] Execution plan shows: [Paste execution plan or describe bottleneck] Database: [PostgreSQL/MySQL/SQL Server] Table row counts: [Approximate sizes] Provide: 1. Identified performance issues 2. Optimized query with explanation 3. Index recommendations 4. Query rewrite […]

Read More
AI

AI Prompt: Create Regex Patterns with Explanations

- 22.02.26 - ErcanOPAK comment on AI Prompt: Create Regex Patterns with Explanations

Regex is cryptic. AI writes and explains patterns in plain English. The Prompt: Create a regex pattern for: [Describe what you want to match – e.g., “email addresses”, “phone numbers in format (XXX) XXX-XXXX”, “URLs with optional protocol”] Requirements: – Pattern for [language/tool – e.g., JavaScript, Python, grep] – Explain what each part means – […]

Read More
AI

AI Prompt: Generate Comprehensive Test Cases from Requirements

- 22.02.26 - ErcanOPAK comment on AI Prompt: Generate Comprehensive Test Cases from Requirements

Writing test cases manually is tedious. AI generates comprehensive test scenarios including edge cases. The Prompt: Generate test cases for this feature: [Paste feature requirements/user story] Include: 1. Happy path scenarios 2. Edge cases 3. Error handling scenarios 4. Boundary value tests 5. Negative test cases 6. Security test cases (injection, auth bypass) Format each […]

Read More
Docker

Docker: Use Build Cache Effectively with Layer Ordering

- 22.02.26 - ErcanOPAK comment on Docker: Use Build Cache Effectively with Layer Ordering

Dockerfile layer order dramatically affects build speed. Put changing layers last, stable layers first. Bad (Slow Rebuilds): FROM node:18 COPY . /app RUN npm install Every code change invalidates npm install cache! Good (Fast Rebuilds): FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install # Cached unless package.json changes! COPY . . # Code […]

Read More
Kubernetes

Kubernetes: Use Kustomize for Environment-Specific Configurations

- 22.02.26 - ErcanOPAK comment on Kubernetes: Use Kustomize for Environment-Specific Configurations

Maintaining separate YAML files for dev/staging/prod is messy. Kustomize manages variations without duplication. Base Configuration: # base/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 2 template: spec: containers: – name: app image: myapp:latest Production Override: # overlays/production/kustomization.yaml resources: – ../../base patchesStrategicMerge: – replicas.yaml # Sets replicas: 10 – image.yaml # Sets image: myapp:1.5.3 […]

Read More
Wordpress

WordPress: Use wp_cache API for Object Caching Without Plugin

- 22.02.26 - ErcanOPAK comment on WordPress: Use wp_cache API for Object Caching Without Plugin

Repeated database queries kill performance. wp_cache API provides in-memory object caching natively. Cache Expensive Query: $cache_key = ‘popular_posts’; $posts = wp_cache_get($cache_key); if ($posts === false) { // Cache miss – query database $posts = $wpdb->get_results(“SELECT * FROM wp_posts WHERE …..”); wp_cache_set($cache_key, $posts, ”, 3600); // Cache 1 hour } return $posts; Note: Works with persistent […]

Read More
Wordpress

WordPress: Use Custom Post Statuses Beyond Draft and Published

- 22.02.26 - ErcanOPAK comment on WordPress: Use Custom Post Statuses Beyond Draft and Published

Stuck with just Draft/Published/Scheduled? Register custom post statuses for better editorial workflow. Register Status: register_post_status(‘in_review’, array( ‘label’ => ‘In Review’, ‘public’ => false, ‘show_in_admin_all_list’ => true, ‘show_in_admin_status_list’ => true )); Add to Quick Edit: add_filter(‘display_post_states’, function($states, $post) { if (get_post_status($post->ID) == ‘in_review’) { $states[] = ‘In Review’; } return $states; }, 10, 2); Perfect for […]

Read More
Photoshop

Photoshop: Use Camera Raw Filter for Non-Destructive Raw-Style Editing

- 22.02.26 - ErcanOPAK comment on Photoshop: Use Camera Raw Filter for Non-Destructive Raw-Style Editing

Camera Raw isn’t just for RAW files. Use it as a filter on any layer for powerful non-destructive editing. Apply: Convert layer to Smart Object → Filter → Camera Raw Filter Why Smart Object: Filter becomes editable anytime. Double-click filter name in layers panel to re-adjust settings later! Powerful Controls: Exposure, contrast, highlights, shadows, whites, […]

Read More
Photoshop

Photoshop: Use Curves Adjustment for Professional Color Grading

- 22.02.26 - ErcanOPAK comment on Photoshop: Use Curves Adjustment for Professional Color Grading

Levels are basic. Curves give you surgical precision over color and tone. This is how professionals color grade. Access: Layer → New Adjustment Layer → Curves The RGB Curve: Drag middle upward = brighten midtones. Drag downward = darken. S-curve = increase contrast. Individual Color Channels: Switch from RGB to Red/Green/Blue channels. Pull red curve […]

Read More
Visual Studio

Visual Studio: Use Live Unit Testing to See Test Results While Coding

- 22.02.26 - ErcanOPAK comment on Visual Studio: Use Live Unit Testing to See Test Results While Coding

Running tests manually after every change is slow. Live Unit Testing runs tests automatically as you type and shows results inline. Enable: Test → Live Unit Testing → Start Visual Indicators: Green checkmark = passing tests, Red X = failing tests, Blue dash = not covered by tests. Shows directly in code editor margin! Performance: […]

Read More
C#

C#: Moving from Runtime Reflection to Build-Time Source Generators

- 21.02.26 - ErcanOPAK comment on C#: Moving from Runtime Reflection to Build-Time Source Generators

Reflection is slow and not AOT-friendly. Source Generators allow you to generate code during the build process, making your apps faster and ready for Native AOT (Ahead-of-Time) compilation.

Read More
C#

C#: Professional Dependency Injection – Avoiding Captive Dependencies

- 21.02.26 - ErcanOPAK comment on C#: Professional Dependency Injection – Avoiding Captive Dependencies

A ‘Captive Dependency’ happens when a Singleton service depends on a Scoped service. This can lead to memory leaks and incorrect state. Learn how to use IServiceScopeFactory to handle this correctly.

Read More
C#

C#: Achieving Zero-Allocation Parsing with Span and ReadOnlySpan

- 21.02.26 - ErcanOPAK comment on C#: Achieving Zero-Allocation Parsing with Span and ReadOnlySpan

If you process large strings or byte arrays, Substring() creates new objects on the heap. Span<T> provides a window into the memory without copying it. Impact: Massive reduction in Garbage Collection (GC) pressure for high-traffic apps.

Read More
SQL

SQL: Identifying and Preventing Deadlocks in High-Concurrency Systems

- 21.02.26 - ErcanOPAK comment on SQL: Identifying and Preventing Deadlocks in High-Concurrency Systems

Deadlocks occur when two processes wait for each other to release locks. Learn how to use Extended Events to capture deadlock graphs and rewrite queries to avoid ‘Victim’ status.

Read More
Page 11 of 69
« Previous 1 … 6 7 8 9 10 11 12 13 14 15 16 … 69 Next »

Posts pagination

« Previous 1 … 9 10 11 12 13 … 69 Next »
April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (951)
  • How to add default value for Entity Framework migrations for DateTime and Bool (868)
  • Get the First and Last Word from a String or Sentence in SQL (837)
  • How to select distinct rows in a datatable in C# (806)
  • How to make theater mode the default for Youtube (757)
  • Add Constraint to SQL Table to ensure email contains @ (578)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (564)
  • Average of all values in a column that are not zero in SQL (535)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (491)
  • Find numbers with more than two decimal places in SQL (449)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (951)
  • How to add default value for Entity Framework migrations for DateTime and Bool (868)
  • Get the First and Last Word from a String or Sentence in SQL (837)
  • How to select distinct rows in a datatable in C# (806)
  • How to make theater mode the default for Youtube (757)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com