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

Asp.Net Core / C#

.NET 9 Rate Limiting — Easy API Protection

- 05.12.25 | 05.12.25 - ErcanOPAK comment on .NET 9 Rate Limiting — Easy API Protection

Rate limiting used to be hard… now it’s literally one line. app.UseRateLimiter(new() { GlobalLimiter = PartitionedRateLimiter.CreateChained( PartitionedRateLimiter.CreateFixedWindow(10, TimeSpan.FromSeconds(5)) ) }); 🔒 Why You Need It 🛡 Stops brute-force 📉 Protects API throughput ⚙ Cloud-native resilience 🌍 Zero-config distributed support (Redis optional) 🧠 Bonus Pair with Minimal APIs for super-light API services.

Read More
Asp.Net Core / C#

Async Streams in C# — Clean, Fast, Real-Time Data

- 05.12.25 | 05.12.25 - ErcanOPAK comment on Async Streams in C# — Clean, Fast, Real-Time Data

🌀 Why Async Streams Shine Async Streams (IAsyncEnumerable<T>) are perfect for streaming data without memory blows. await foreach (var log in service.GetLogsAsync()) { Console.WriteLine(log); } ✨ What They Solve 🔁 Handling live logs 📡 Streamed API responses 🧵 Reducing memory spikes 🌊 Backpressure-friendly async flow 💡 Pro Tip Combine with channels for ultra-responsive pipelines.

Read More
.NET / Asp.Net Core / C#

Improve .NET Logging with Structured Log Messages

- 04.12.25 | 04.12.25 - ErcanOPAK

Structured logs allow smarter querying and cleaner search results. logger.LogInformation(“User {UserId} logged in”, id); They improve observability, diagnostics, and production monitoring.

Read More
.NET / Asp.Net Core / C#

Boost Async Performance in .NET with ConfigureAwait(false)

- 04.12.25 | 04.12.25 - ErcanOPAK

Using ConfigureAwait(false) can significantly reduce context-switching overhead in non-UI .NET applications. This is essential for APIs, background services, and any high-throughput async pipeline. await http.SendAsync(req).ConfigureAwait(false); It lowers CPU usage, avoids deadlocks, and improves overall async performance.

Read More
.NET / Asp.Net Core / C#

Write Cleaner Business Logic Using C# Switch Expressions

- 04.12.25 | 04.12.25 - ErcanOPAK

Switch expressions simplify complex branching logic and make code more readable. var price = plan switch { “free” => 0, “pro” => 19, “biz” => 49, _ => throw new Exception(“Unknown plan”) }; They are ideal for pricing models, rules engines, and state transitions.

Read More
.NET / Asp.Net Core / C#

EF Core Performance Boost: Use AsNoTracking() When Reading Data

- 04.12.25 | 04.12.25 - ErcanOPAK

For read-heavy queries, AsNoTracking() provides massive performance improvements. var users = await ctx.Users.AsNoTracking().ToListAsync(); It avoids adding entities to the change tracker, improving speed by 30–50%.

Read More
.NET / Asp.Net Core / C#

Use IAsyncEnumerable for Streaming Data in .NET

- 04.12.25 | 04.12.25 - ErcanOPAK

IAsyncEnumerable allows true async streaming, reducing memory usage. await foreach (var user in repo.GetAllAsync()) Console.WriteLine(user.Name); Perfect for large datasets and high-throughput APIs.

Read More
.NET / Asp.Net Core / C#

Why C# Record Types Are Perfect for Modern DTOs

- 04.12.25 | 04.12.25 - ErcanOPAK

Records offer immutability, value semantics, and minimal syntax. public record UserDto(int Id, string Name, string Email); They are ideal for APIs, events, and data-transfer layers.

Read More
.NET / Asp.Net Core / C#

Clean Minimal APIs in .NET – Automatic DTO Binding Explained

- 04.12.25 | 04.12.25 - ErcanOPAK

Minimal APIs provide automatic DTO binding, eliminating unnecessary boilerplate. app.MapPost(“/login”, (LoginRequest req) => { return Results.Ok($”Welcome {req.Email}”); }); This improves readability, reduces errors, and works perfectly with endpoint filters.

Read More
.NET / Asp.Net Core / C#

Never Write Retry Logic Again – Use Polly in .NET

- 04.12.25 | 04.12.25 - ErcanOPAK

Polly provides retry, timeout, fallback, and circuit-breaker patterns. var result = await Policy .Handle() .RetryAsync(3) .ExecuteAsync(() => CallApi()); It’s the gold standard for resilience in .NET microservices.

Read More
.NET

The One DI Rule You Must Not Break: Avoid Injecting Scoped into Singleton

- 04.12.25 | 04.12.25 - ErcanOPAK

Mixing Scoped services inside Singletons causes threading issues and hidden bugs. Always match lifetime scopes properly to avoid race conditions and stale state.

Read More
.NET / Asp.Net Core / C# / Entity Framework

Stop Calling ToList() Too Early – Improve LINQ Performance

- 04.12.25 | 04.12.25 - ErcanOPAK

Calling ToList() too early forces premature execution. // Bad var items = db.Users.ToList().Where(…); // Good var items = db.Users.Where(…).ToList();   Let the database handle filtering and execution.

Read More
.NET / Asp.Net Core / C#

Build Clean Background Services with IHostedService in .NET

- 04.12.25 | 04.12.25 - ErcanOPAK

BackgroundService enables clean, scalable background processing. protected override async Task ExecuteAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { await DoWork(); await Task.Delay(1000, ct); } } It works perfectly in cloud-native environments.

Read More
.NET / Asp.Net Core / C#

Cleaner .NET APIs Using IEndpointFilter for Validation

- 04.12.25 | 04.12.25 - ErcanOPAK

Endpoint filters reduce validation noise in Minimal APIs. public class ValidateFilter : IEndpointFilter { public Task<object?> InvokeAsync(EndpointFilterInvocationContext ctx, EndpointFilterDelegate next) { var model = ctx.GetArgument(0); Validator.ValidateObject(model, new()); return next(ctx); } } They keep endpoints clean, reusable, and testable.

Read More
.NET / Asp.Net Core / C#

EF Core 8 ExecuteUpdate – Batch Updates Without Loops

- 04.12.25 | 04.12.25 - ErcanOPAK

ExecuteUpdate allows batch updates without tracking overhead. await ctx.Users .Where(u => u.IsActive == false) .ExecuteUpdateAsync(p => p.SetProperty(x => x.IsDeleted, true));   It’s fast, clean, and ideal for big-data operations.

Read More
.NET / Asp.Net Core / C#

Every Async Method Should Accept CancellationToken

- 04.12.25 | 04.12.25 - ErcanOPAK

CancellationToken prevents zombie tasks and ensures graceful shutdown. public Task RunAsync(CancellationToken ct) It is a must-have for cloud-native workloads.

Read More
.NET / Asp.Net Core / C#

Lightning-Fast Lookups in .NET Using MemoryCache

- 04.12.25 | 04.12.25 - ErcanOPAK

MemoryCache provides a simple and fast in-memory caching solution. var item = cache.GetOrCreate(“users”, entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10); return repo.GetUsers(); }); Ideal for configuration, lookups, and session data.

Read More
Chrome

How to enable automatically picture-in-picture for Google Chrome

- 12.11.25 - ErcanOPAK comment on How to enable automatically picture-in-picture for Google Chrome

From Chrome 134, web apps that play audio or video can automatically enter picture-in-picture mode. This means that music and video players on the web can now seamlessly switch to a mini player window when the user switches tabs, eliminating the need for manual activation. To enable/disable and test this feature immediately, enable/disable the “Auto […]

Read More
Windows

How to get public ip address using Windows PowerShell

- 02.11.25 - ErcanOPAK comment on How to get public ip address using Windows PowerShell

You can use the Invoke-WebRequest module in PowerShell: Invoke-WebRequest ifconfig.me/ip

Read More
Windows

How to Reset Taskbar in Windows 11

- 20.10.24 - ErcanOPAK comment on How to Reset Taskbar in Windows 11

Occasionally and randomly, the taskbar on your Windows 11 PC can freeze. It might stop responding or stop showing certain icons that you need to interact with. If the taskbar isn’t functioning correctly, you’ll want to get it working again. Often, the fix is as simple as restarting Windows Explorer, but you’ll also want to […]

Read More
Windows

Essential Steps to Take After Windows 11 Updates

- 19.10.24 | 19.10.24 - ErcanOPAK comment on Essential Steps to Take After Windows 11 Updates

Old Windows update files can sometimes take up over 15 GB of space, so it’s a good idea to clean up those temporary files. What are temp files? Temporary files, also called temp or tmp files, are created by programs on your computer to hold data while a permanent file is being written or updated. The […]

Read More
SQL

How to list all tables referencing a table by Foreign Key in MS SQL

- 04.10.24 - ErcanOPAK comment on How to list all tables referencing a table by Foreign Key in MS SQL

SELECT DISTINCT schema_name(fk_tab.schema_id) + ‘.’ + fk_tab.name as foreign_table, ‘>-‘ as rel, schema_name(pk_tab.schema_id) + ‘.’ + pk_tab.name as primary_table FROM sys.foreign_keys fk INNER JOIN sys.tables fk_tab on fk_tab.object_id = fk.parent_object_id INNER JOIN sys.tables pk_tab on pk_tab.object_id = fk.referenced_object_id WHERE pk_tab.[name] = ‘Your table’ — enter table name here — and schema_name(pk_tab.schema_id) = ‘Your table schema […]

Read More
Development / JavaScript

How to format date in Javascript

- 09.09.24 - ErcanOPAK comment on How to format date in Javascript

function formatDate(date) { var d = new Date(date), month = ” + (d.getMonth() + 1), day = ” + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = ‘0’ + month; if (day.length < 2) day = ‘0’ + day; return [day, month, year].join(‘.’); } OUTPUT: 19.05.2024 NOTE: If you make the return like […]

Read More
SQL

How to generate a random number for each row in T-SQL

- 26.08.24 - ErcanOPAK comment on How to generate a random number for each row in T-SQL

When called multiple times in a single batch, rand() returns the same number. So it is better to use convert(varbinary,newid()) as the seed argument: SELECT 1.0 + floor(110 * RAND(convert(varbinary, newid()))) AS random_number newid() is guaranteed to return a different value each time it’s called, even within the same batch, so using it as a seed […]

Read More
Git

How to solve ‘Microsoft.TeamFoundation.Git.Contracts.GitCheckoutConflictException’ problem

- 17.08.24 | 16.01.26 - ErcanOPAK comment on How to solve ‘Microsoft.TeamFoundation.Git.Contracts.GitCheckoutConflictException’ problem

You are in the middle of a coding session, you realize you need to switch to a new branch, and suddenly… BAM! Visual Studio throws the dreaded Microsoft.TeamFoundation.Git.Contracts.GitCheckoutConflictException. ❌ GitCheckoutConflictException An exception occurred during the checkout process. Local changes to the following files would be overwritten by checkout: [Your-File-Path.cs] Why Does This Happen? Git is […]

Read More
Liberal Education

Why nautical mile equals 1852 mt

- 28.07.24 | 28.07.24 - ErcanOPAK comment on Why nautical mile equals 1852 mt

In terms of distance, a nautical mile is equal to 1,852 kilometers. People commonly use it to measure distances at sea or in the air. The use of NM, the internationally agreed-upon measure of one nautical mile, which is exactly 1.852 meters, remains in place today.   Calculation:  Consider the equator as a circle, it […]

Read More
SQL

How to Find Day Name From Date in SQL Server

- 27.07.24 | 27.07.24 - ErcanOPAK comment on How to Find Day Name From Date in SQL Server

There are two methods to find a day name from a date in SQL Server: DATENAME() Function FORMAT() Function   Using DATENAME DECLARE @Date DATE = ‘2024-07-27’; SELECT @Date As [TDate], DATENAME(WEEKDAY, @Date) AS [Day_Name];     Using FORMAT DECLARE @Date DATE = ‘2024-07-27’; SELECT @Date As [TDate], FORMAT(@Date, ‘dddd’) AS [Day_Name]      

Read More
SQL

How to make pagination in MS SQL Server

- 01.07.24 - ErcanOPAK comment on How to make pagination in MS SQL Server

In MS SQL Server, we can achieve the pagination functionality by using OFFSET and FETCH clauses with ORDER BY in a SELECT statement. OFFSET: Represents the number of rows to be skipped from the result set. It should be 0 or greater than 0. FETCH: Represents the number of rows to be displayed in the result. Notes: ORDER BY is mandatory for the use OFFSET […]

Read More
SQL

How to update Identity Column in SQL Server

- 16.04.24 - ErcanOPAK comment on How to update Identity Column in SQL Server

— Set Identity insert on so that value can be inserted into this column SET IDENTITY_INSERT YourTable ON GO — Insert the record which you want to update with new value in the identity column INSERT INTO YourTable(IdentityCol, otherCol) VALUES(5, ‘myValue’) GO — Delete the old row of which you have inserted a copy (above) […]

Read More
C#

Easy way to join strings on complex classes

- 06.04.24 - ErcanOPAK comment on Easy way to join strings on complex classes

Let’s say you have a class like that: public class Student { public string Name { get; set; } public string Surname { get; set; } public DateTime DateCreated { get; set; } … } If you want to join the name values of that class then you can use the code below: using System.Linq […]

Read More
Page 60 of 69
« Previous 1 … 55 56 57 58 59 60 61 62 63 64 65 … 69 Next »

Posts navigation

Older posts
Newer posts
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 (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (860)
  • 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 (754)
  • 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 (531)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (489)
  • 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 (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (860)
  • 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 (754)

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