The SelectMany method in EF Core is a powerful tool used for projecting and flattening collections. It allows you to take a collection of items, extract subcollections or related data, and combine them into a single flattened result.
For example, when working with entities that have a one-to-many or many-to-many relationship, SelectMany helps you navigate and work with related data more efficiently. Instead of dealing with nested lists or loops, it simplifies querying and transforms hierarchical data into a single, easy-to-use collection, making your LINQ queries more concise and expressive.
Apart from SelectMany, I like the way EF Core put the RoleType enum values to string and created a Case-When expression since I'm returning list of strings.
C# Tasks: Listen for multiple cancellation requests.
As we know, using CancellationToken is highly recommended in asynchronous programming, but in some scenarios, you need to care about multiple cancellation tokens.
For example, you can get the CancellationToken request from the HttpContext, but you might need to say:
OK, do your job until the request is canceled, or kill yourself after 5 seconds!
We can easily link multiple tokens using the CancellationTokenSource.CreateLinkedTokenSource method, if any token is canceled, the task will stop.
Have you used LinkedCancellationToken? What do you think about it?
Since we set warnings as error it prevented me to build project and I was like, ok let's update this package but where is it? I did a global search (!) and no project was using the "System.Formats.Asn1"!
So I know maybe one the current packages is using it internally but how would I know? Do I need to go through all of the packages one by one in different projects and explore them using Visual Studio? definitely takes much time.
Thankfully, the .NET 9 saved my day by introducing new command: `dotnet nuget why` which shows the dependency graph for a particular package.
It's very useful to find out how many packages are using internally by other packages!
When it comes to working with HttpContext in ASP.NET, it's essential to remember that HttpContext is 𝐧𝐨𝐭 thread-safe. Attempting to read or modify its properties outside of request processing can lead to a NullReferenceException. Furthermore, once a request is completed and the response is sent back to the user, the HttpContext is no longer available. Consequently, using HttpContext in a background thread is not advisable.
To securely handle background tasks involving HttpContext data, you should follow these best practices:
- 𝐂𝐨𝐩𝐲 𝐭𝐡𝐞 𝐑𝐞𝐪𝐮𝐢𝐫𝐞𝐝 𝐃𝐚𝐭𝐚: During request processing, make a copy of the HttpContext data that you need for your background task. This ensures that you have a snapshot of the data to work with.
- 𝐏𝐚𝐬𝐬 𝐂𝐨𝐩𝐢𝐞𝐝 𝐃𝐚𝐭𝐚 𝐭𝐨 𝐭𝐡𝐞 𝐁𝐚𝐜𝐤𝐠𝐫𝐨𝐮𝐧𝐝 𝐓𝐚𝐬𝐤: Instead of passing the HttpContext itself to a background method, pass the copied data that you obtained during request processing. This separates the background task from the HttpContext, eliminating the risk of thread-related issues.
- 𝐀𝐯𝐨𝐢𝐝 𝐑𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐢𝐧𝐠 𝐇𝐭𝐭𝐩𝐂𝐨𝐧𝐭𝐞𝐱𝐭 𝐃𝐚𝐭𝐚 𝐢𝐧 𝐏𝐚𝐫𝐚𝐥𝐥𝐞𝐥 𝐓𝐚𝐬𝐤𝐬: When dealing with parallel tasks, refrain from directly referencing HttpContext data. Instead, extract and store the necessary data from the HttpContext before initiating parallel tasks.
In summary, never pass the HttpContext into a method that performs background work. Instead, pass the essential data obtained during request processing to ensure the safe and efficient execution of background tasks in ASP.NET applications.
When it comes to working with HTTP requests, knowing about the request method is key to implementing and calling the server correctly.
In this list, I specified whether each of the methods can contain a Body or not and whether it is idempotent.
Idempotent means that any number of repeated, identical requests will leave the resource in the same state. It is an important point to consider when you're trying to design and write your APIs.
Personally, I really like the HEAD method you can do magic with it, I didn't know about the CONNECT method as it's not for use in the REST world! it enables access to websites using TLS (HTTPS). When a client requests an HTTP Proxy server, the server establishes a tunnel for the TCP connection to the desired destination.
xUnit basics: reminding of how IClassFixture works
xUnit has a fantastic feature in which you can share some context for all tests inside a collection (say class here).
Class Fixture is for: 'when you want to create a single test context and share it among all the tests in the class, and have it cleaned up after all the tests in the class have finished.'
In a normal way without using ClassFixture, xUnit will create a class instance per test which makes sense for the sake of test isolation but it's a common use case that you want to instantiate a class/service only once to be reused for all tests, then ClassFixture comes to the picture.
You need to know how xUnit runs the tests otherwise it may cause writing inefficient tests!
Ok, in this example, let's say you have a UserServiceTest containing 3 tests and it makes sense to spin up only 1 datasource (db) for them. but still, the UserServiceTest ctor will be called 3 times.
So what's the point here?
I can see a misunderstanding between using IClassFixture and Class instantiating, this is the rule to be reminded of:
For one collection the IClassFixture runs once and class ctor runs per test.
In C#, switching based on types is a special way of using patterns, where you check if a variable (`x` in this case) is of a certain type (e.g., `x is int`).
For each case in this type-based switch, you specify a type to match and a variable to store the matched value if the match succeeds (referred to as the "pattern" variable). Unlike when dealing with constants, you can use any type without restrictions.
It's worth noting that the order of the case clauses matters when switching based on types, unlike when switching on constants. If you're using `when` conditions within cases, pay attention to the order in which they appear.
When it comes to query optimization, one of the considerations is reducing database roundtrip as we need to avoid unnecessary database calls, if possible.
It is easy to make mistakes when using EntityFramework because you're writing C# code, not SQL thus you may forget how EF will translate this code to SQL and sometimes it will split the code into multiple database queries to gather all the data you need.
One of the common examples is using `Count()` method which is used for getting the number of rows for a specific query and needs a separate database query.
EF core 9 is trying to solve this issue for us and it is nice to see they care about this small correction for our Linq codes.
It can help to have better query performance as instead of calling the database twice we need only one!
As a tip, always check EF-generated SQL queries even if you're not an SQL expert still you can know how it executes your queries.
Saeed Esmaeelinejad
The SelectMany method in EF Core is a powerful tool used for projecting and flattening collections. It allows you to take a collection of items, extract subcollections or related data, and combine them into a single flattened result.
For example, when working with entities that have a one-to-many or many-to-many relationship, SelectMany helps you navigate and work with related data more efficiently. Instead of dealing with nested lists or loops, it simplifies querying and transforms hierarchical data into a single, easy-to-use collection, making your LINQ queries more concise and expressive.
Apart from SelectMany, I like the way EF Core put the RoleType enum values to string and created a Case-When expression since I'm returning list of strings.
Do you use SelectMany with EF Core?
#dotnet #efcore #linqselectmany
4 months ago | [YT] | 25
View 0 replies
Saeed Esmaeelinejad
Use class to map request parameter
It's common for GET requests you will get some data from the query string, especially in search API.
In ASP.NET we have these built-in model binders when working with requests:
- FromQuery
- FromRoute
- FromForm
- FromBody
- FromHeader
When it comes to dashboard API there are lots of filters and as GET request you need to put all those filters usually in the queryString.
It's possible to have a model and map all those param to it using [FromQuery], much cleaner, no?
Just to point out, you can use the model for other bindings as well.
#dotnet #aspnetcore #modelbinding
6 months ago | [YT] | 19
View 2 replies
Saeed Esmaeelinejad
C# Tasks: Listen for multiple cancellation requests.
As we know, using CancellationToken is highly recommended in asynchronous programming, but in some scenarios, you need to care about multiple cancellation tokens.
For example, you can get the CancellationToken request from the HttpContext, but you might need to say:
OK, do your job until the request is canceled, or kill yourself after 5 seconds!
We can easily link multiple tokens using the CancellationTokenSource.CreateLinkedTokenSource method, if any token is canceled, the task will stop.
Have you used LinkedCancellationToken? What do you think about it?
#dotnet #csharp #asynchronousprogramming #cancellationtoken
6 months ago | [YT] | 8
View 0 replies
Saeed Esmaeelinejad
.NET 9: `dotnet nuget why` command
The other day, in out backend API project I got this warning:
"NU1903 Package 'System.Formats.Asn1' 8.0.0 has a known high severity vulnerability, github.com/advisories/GHSA-447r-wph3-92pm"
Since we set warnings as error it prevented me to build project and I was like, ok let's update this package but where is it? I did a global search (!) and no project was using the "System.Formats.Asn1"!
So I know maybe one the current packages is using it internally but how would I know? Do I need to go through all of the packages one by one in different projects and explore them using Visual Studio? definitely takes much time.
Thankfully, the .NET 9 saved my day by introducing new command: `dotnet nuget why` which shows the dependency graph for a particular package.
It's very useful to find out how many packages are using internally by other packages!
Give it a try!
Did you know about this new command in .NET 9?
#net9 #dotnetnugetwhy #cli
8 months ago | [YT] | 13
View 0 replies
Saeed Esmaeelinejad
𝐀𝐒𝐏.𝐍𝐄𝐓: 𝐇𝐭𝐭𝐩𝐂𝐨𝐧𝐭𝐞𝐱𝐭 𝐚𝐜𝐜𝐞𝐬𝐬 𝐟𝐫𝐨𝐦 𝐚 𝐛𝐚𝐜𝐤𝐠𝐫𝐨𝐮𝐧𝐝 𝐭𝐡𝐫𝐞𝐚𝐝?
When it comes to working with HttpContext in ASP.NET, it's essential to remember that HttpContext is 𝐧𝐨𝐭 thread-safe. Attempting to read or modify its properties outside of request processing can lead to a NullReferenceException. Furthermore, once a request is completed and the response is sent back to the user, the HttpContext is no longer available. Consequently, using HttpContext in a background thread is not advisable.
To securely handle background tasks involving HttpContext data, you should follow these best practices:
- 𝐂𝐨𝐩𝐲 𝐭𝐡𝐞 𝐑𝐞𝐪𝐮𝐢𝐫𝐞𝐝 𝐃𝐚𝐭𝐚: During request processing, make a copy of the HttpContext data that you need for your background task. This ensures that you have a snapshot of the data to work with.
- 𝐏𝐚𝐬𝐬 𝐂𝐨𝐩𝐢𝐞𝐝 𝐃𝐚𝐭𝐚 𝐭𝐨 𝐭𝐡𝐞 𝐁𝐚𝐜𝐤𝐠𝐫𝐨𝐮𝐧𝐝 𝐓𝐚𝐬𝐤: Instead of passing the HttpContext itself to a background method, pass the copied data that you obtained during request processing. This separates the background task from the HttpContext, eliminating the risk of thread-related issues.
- 𝐀𝐯𝐨𝐢𝐝 𝐑𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐢𝐧𝐠 𝐇𝐭𝐭𝐩𝐂𝐨𝐧𝐭𝐞𝐱𝐭 𝐃𝐚𝐭𝐚 𝐢𝐧 𝐏𝐚𝐫𝐚𝐥𝐥𝐞𝐥 𝐓𝐚𝐬𝐤𝐬: When dealing with parallel tasks, refrain from directly referencing HttpContext data. Instead, extract and store the necessary data from the HttpContext before initiating parallel tasks.
In summary, never pass the HttpContext into a method that performs background work. Instead, pass the essential data obtained during request processing to ensure the safe and efficient execution of background tasks in ASP.NET applications.
#dotnet #aspnet #httpcontext #backgroundtasks
11 months ago | [YT] | 26
View 0 replies
Saeed Esmaeelinejad
HTTP Request Methods
When it comes to working with HTTP requests, knowing about the request method is key to implementing and calling the server correctly.
In this list, I specified whether each of the methods can contain a Body or not and whether it is idempotent.
Idempotent means that any number of repeated, identical requests will leave the resource in the same state. It is an important point to consider when you're trying to design and write your APIs.
Personally, I really like the HEAD method you can do magic with it, I didn't know about the CONNECT method as it's not for use in the REST world! it enables access to websites using TLS (HTTPS). When a client requests an HTTP Proxy server, the server establishes a tunnel for the TCP connection to the desired destination.
Do you consider idempotency in your API?
#http #requestmethods
11 months ago | [YT] | 10
View 0 replies
Saeed Esmaeelinejad
xUnit basics: reminding of how IClassFixture works
xUnit has a fantastic feature in which you can share some context for all tests inside a collection (say class here).
Class Fixture is for: 'when you want to create a single test context and share it among all the tests in the class, and have it cleaned up after all the tests in the class have finished.'
In a normal way without using ClassFixture, xUnit will create a class instance per test which makes sense for the sake of test isolation but it's a common use case that you want to instantiate a class/service only once to be reused for all tests, then ClassFixture comes to the picture.
You need to know how xUnit runs the tests otherwise it may cause writing inefficient tests!
Ok, in this example, let's say you have a UserServiceTest containing 3 tests and it makes sense to spin up only 1 datasource (db) for them. but still, the UserServiceTest ctor will be called 3 times.
So what's the point here?
I can see a misunderstanding between using IClassFixture and Class instantiating, this is the rule to be reminded of:
For one collection the IClassFixture runs once and class ctor runs per test.
#dotnet #xunit #unittesting #iclassfixture
1 year ago | [YT] | 12
View 2 replies
Saeed Esmaeelinejad
C#: Using Types in Switch Statements
In C#, switching based on types is a special way of using patterns, where you check if a variable (`x` in this case) is of a certain type (e.g., `x is int`).
For each case in this type-based switch, you specify a type to match and a variable to store the matched value if the match succeeds (referred to as the "pattern" variable). Unlike when dealing with constants, you can use any type without restrictions.
It's worth noting that the order of the case clauses matters when switching based on types, unlike when switching on constants. If you're using `when` conditions within cases, pay attention to the order in which they appear.
What do you think about it?
#dotnet #csharp #switchcase
1 year ago | [YT] | 16
View 0 replies
Saeed Esmaeelinejad
EF Core 9: Reducing database roundtrip!
When it comes to query optimization, one of the considerations is reducing database roundtrip as we need to avoid unnecessary database calls, if possible.
It is easy to make mistakes when using EntityFramework because you're writing C# code, not SQL thus you may forget how EF will translate this code to SQL and sometimes it will split the code into multiple database queries to gather all the data you need.
One of the common examples is using `Count()` method which is used for getting the number of rows for a specific query and needs a separate database query.
EF core 9 is trying to solve this issue for us and it is nice to see they care about this small correction for our Linq codes.
It can help to have better query performance as instead of calling the database twice we need only one!
As a tip, always check EF-generated SQL queries even if you're not an SQL expert still you can know how it executes your queries.
What do you think about the new feature?
#dotnet #entityframework #queryoptimization
1 year ago | [YT] | 16
View 0 replies
Saeed Esmaeelinejad
A Comparison about C# For loops: .NET 9 is slower than .NET 8 in some methods
Just out of curiosity, I made this benchmark for checking the performance, and as we know the pure For loops is a winner.
The interesting thing for me was that .NET 9 that was slower than .NET 8 in some methods like ForEach_LinqParallel.
Although these numbers are negligible still fun to know.
I removed some columns from the BenchmarkDotNet result for the sake of design!
You can find the benchmark code here: github.com/sa-es-ir/ForLoopComparison
Let me know your thoughts about .NET 9.
#csharp #dotnet #forloops
1 year ago | [YT] | 14
View 0 replies
Load more