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.
Author: ErcanOPAK
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.
Improve .NET Logging with Structured Log Messages
Structured logs allow smarter querying and cleaner search results. logger.LogInformation(“User {UserId} logged in”, id); They improve observability, diagnostics, and production monitoring.
Boost Async Performance in .NET with ConfigureAwait(false)
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.
Write Cleaner Business Logic Using C# Switch Expressions
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.
EF Core Performance Boost: Use AsNoTracking() When Reading Data
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%.
Use IAsyncEnumerable for Streaming Data in .NET
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.
Why C# Record Types Are Perfect for Modern DTOs
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.
Clean Minimal APIs in .NET – Automatic DTO Binding Explained
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.
Never Write Retry Logic Again – Use Polly in .NET
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.
The One DI Rule You Must Not Break: Avoid Injecting Scoped into Singleton
Mixing Scoped services inside Singletons causes threading issues and hidden bugs. Always match lifetime scopes properly to avoid race conditions and stale state.
Stop Calling ToList() Too Early – Improve LINQ Performance
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.
Build Clean Background Services with IHostedService in .NET
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.
Cleaner .NET APIs Using IEndpointFilter for Validation
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.
EF Core 8 ExecuteUpdate – Batch Updates Without Loops
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.
Every Async Method Should Accept CancellationToken
CancellationToken prevents zombie tasks and ensures graceful shutdown. public Task RunAsync(CancellationToken ct) It is a must-have for cloud-native workloads.
Lightning-Fast Lookups in .NET Using MemoryCache
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.
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 […]
How to get public ip address using Windows PowerShell
You can use the Invoke-WebRequest module in PowerShell: Invoke-WebRequest ifconfig.me/ip
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 […]
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 […]
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 […]
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 […]
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 […]
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 […]
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 […]
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]
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 […]
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) […]
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 […]








