<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Hamza Darouzi</title>
    <description>The latest articles on Forem by Hamza Darouzi (@hamza_darouzi_dotnet).</description>
    <link>https://forem.com/hamza_darouzi_dotnet</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1906614%2Fcaef251a-f3ce-4e56-9bc4-6118f8d56ba4.png</url>
      <title>Forem: Hamza Darouzi</title>
      <link>https://forem.com/hamza_darouzi_dotnet</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/hamza_darouzi_dotnet"/>
    <language>en</language>
    <item>
      <title>Named Query Filters in .NET 10</title>
      <dc:creator>Hamza Darouzi</dc:creator>
      <pubDate>Tue, 20 Jan 2026 21:07:14 +0000</pubDate>
      <link>https://forem.com/hamza_darouzi_dotnet/named-query-filters-in-net-10-47hp</link>
      <guid>https://forem.com/hamza_darouzi_dotnet/named-query-filters-in-net-10-47hp</guid>
      <description>&lt;h2&gt;
  
  
  From Hidden Magic to Clean, Explicit Architecture
&lt;/h2&gt;




&lt;p&gt;Since their introduction in EF Core, Global Query Filters have offered a powerful idea:&lt;br&gt;
define cross-cutting query rules once, and apply them automatically everywhere.&lt;br&gt;
In theory, this reduces repetition and enforces consistency.&lt;br&gt;
In practice, however, real-world usage exposed an important issue:&lt;br&gt;
&lt;strong&gt;lack of clarity&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;example :&lt;/u&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class UserConfiguration : IEntityTypeConfiguration&amp;lt;User&amp;gt;
{
    public void Configure(EntityTypeBuilder&amp;lt;User&amp;gt; builder)
    {
        builder.HasQueryFilter(u =&amp;gt; u.IsDeleted == false);
        builder.ToTable(nameof(User));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The Problem with Global Query Filters :&lt;/strong&gt;&lt;br&gt;
While useful, traditional Global Query Filters came with well-known drawbacks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Query behavior was not obvious when reading the code&lt;/li&gt;
&lt;li&gt;Filters were hidden inside model configuration&lt;/li&gt;
&lt;li&gt;Debugging missing data could be confusing&lt;/li&gt;
&lt;li&gt;New team members often had no idea why certain rows were excluded&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In short, the rules existed — but they were &lt;strong&gt;unnamed and implicit&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Enter Named Query Filters in .NET 10
&lt;/h2&gt;

&lt;p&gt;With &lt;strong&gt;Named Query Filters&lt;/strong&gt;, .NET 10 doesn’t change the core concept it improves how the concept is expressed.&lt;br&gt;
Instead of silent, invisible filters, we now have:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Explicit names&lt;/li&gt;
&lt;li&gt;Clear intent&lt;/li&gt;
&lt;li&gt;Self-documenting rules&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;u&gt;example :&lt;/u&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class UserConfiguration : IEntityTypeConfiguration&amp;lt;User&amp;gt;
{
    public void Configure(EntityTypeBuilder&amp;lt;User&amp;gt; builder)
    {
        builder.HasQueryFilter(UserFilters.SoftDelete,
                               u =&amp;gt; u.IsDeleted == false);
        builder.ToTable(nameof(User));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not just a cosmetic improvement; it’s an architectural one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Naming Matters
&lt;/h2&gt;

&lt;p&gt;In software design, naming is a first-class design decision.&lt;br&gt;
When a query filter has a name:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Code becomes easier to read&lt;/li&gt;
&lt;li&gt;Business rules become explicit&lt;/li&gt;
&lt;li&gt;Hidden behavior is reduced&lt;/li&gt;
&lt;li&gt;Team communication improves&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This aligns naturally with:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Clean Architecture&lt;/li&gt;
&lt;li&gt;Domain-Driven Design&lt;/li&gt;
&lt;li&gt;The Principle of Least Surprise&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Using Query Filters as Design, Not a Trick
&lt;/h2&gt;

&lt;p&gt;Query Filters — especially in their named form — work best when they represent&lt;br&gt;
system-wide, stable rules, such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Soft Delete&lt;/li&gt;
&lt;li&gt;Multi-Tenancy&lt;/li&gt;
&lt;li&gt;Data Isolation&lt;/li&gt;
&lt;li&gt;Global Security Constraints&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Logic that changes per screen or use case should still live inside the query itself.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Actually Improved?
&lt;/h2&gt;

&lt;p&gt;With Named Query Filters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Rules are no longer hidden&lt;/li&gt;
&lt;li&gt;Query behavior is easier to understand&lt;/li&gt;
&lt;li&gt;Debugging becomes simpler&lt;/li&gt;
&lt;li&gt;Maintenance improves&lt;/li&gt;
&lt;li&gt;Architectural intent is clearer&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;




&lt;p&gt;&lt;strong&gt;Named Query Filters in .NET 10 demonstrate a subtle&lt;/strong&gt; &lt;br&gt;
but important shift:&lt;br&gt;
moving from implicit behavior to explicit design. Small features like this don’t just clean up code , they improve how teams reason about systems.And that’s where real productivity gains come from.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>backend</category>
      <category>features</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Unlock Lightning-Fast Websites: Why AVIF Crushes WebP for Image Loading Speed</title>
      <dc:creator>Hamza Darouzi</dc:creator>
      <pubDate>Mon, 04 Aug 2025 15:43:03 +0000</pubDate>
      <link>https://forem.com/hamza_darouzi_dotnet/unlock-lightning-fast-websites-why-avif-crushes-webp-for-image-loading-speed-287i</link>
      <guid>https://forem.com/hamza_darouzi_dotnet/unlock-lightning-fast-websites-why-avif-crushes-webp-for-image-loading-speed-287i</guid>
      <description>&lt;p&gt;Is your website slowed down by bulky images? You’re not alone. Images make up 50%+ of page weight on average, crushing load times. While WebP was a game-changer years ago, AVIF is the new heavyweight champion for speed, quality, and efficiency. Let’s explore why—and how to implement it easily.&lt;/p&gt;

&lt;h2&gt;
  
  
  WebP vs. AVIF: The Need for Speed
&lt;/h2&gt;

&lt;p&gt;Both formats use advanced compression, but AVIF (based on Netflix’s AV1 video codec) is a generational leap:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Format&lt;/th&gt;
&lt;th&gt;Avg. File Size&lt;/th&gt;
&lt;th&gt;Quality Retention&lt;/th&gt;
&lt;th&gt;Browser Support&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;JPEG&lt;/td&gt;
&lt;td&gt;100% (Baseline)&lt;/td&gt;
&lt;td&gt;Moderate&lt;/td&gt;
&lt;td&gt;Universal&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;WebP&lt;/td&gt;
&lt;td&gt;30% smaller&lt;/td&gt;
&lt;td&gt;Good&lt;/td&gt;
&lt;td&gt;98%+&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;AVIF&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;50% smaller&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Excellent&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;85%+ (Chrome, Firefox, Edge)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Why AVIF wins:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;🚀 50-70% smaller files than JPEG with identical visual quality&lt;/li&gt;
&lt;li&gt;✨ Better detail preservation than WebP at low bitrates&lt;/li&gt;
&lt;li&gt;🎨 Supports HDR, wide color gamuts, and transparency&lt;/li&gt;
&lt;li&gt;⚡ Faster decoding than WebP on modern devices&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to Convert Images to AVIF at Scale
&lt;/h2&gt;

&lt;p&gt;While .NET lacks native AVIF libraries, FFmpeg bridges the gap. Here’s a battle-tested C# method to convert uploads to AVIF automatically:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task&amp;lt;Result&amp;gt; UploadImageAsyncV3(IFormFile file, string folderName)  
{  
    // Create target directory if missing
    var folderPath = EnsureFolder(folderName);  
    var avifFileName = $"{Path.GetFileNameWithoutExtension(file.FileName)}.avif";  
    var finalFilePath = Path.Combine(folderPath, avifFileName).Replace("\\", "/");  

    // Skip if file exists
    if (File.Exists(finalFilePath))  
        return new Result(finalFilePath, Error.FileExist);  

    // Validate image integrity (security!)
    using (var validationStream = new MemoryStream())  
    {  
        await file.CopyToAsync(validationStream);  
        validationStream.Position = 0;  
        if (!IsValidImage(validationStream)) // Checks for valid image headers
            return new Result(false, Error.InvalidFile);  
    }  

    var tempInputPath = Path.Combine(Path.GetTempPath(), file.FileName);  
    var tempOutputPath = Path.Combine(Path.GetTempPath(), avifFileName);  

    try  
    {  
        // Save original to temp location
        await using (var tempStream = File.Create(tempInputPath))  
        {  
            await file.CopyToAsync(tempStream);  
        }  

        // Convert using FFmpeg (install on server!)
        var process = new Process  
        {  
            StartInfo = new ProcessStartInfo  
            {  
                FileName = "C:\\ffmpeg\\bin\\ffmpeg.exe", // ← FFMPEG PATH REQUIRED
                Arguments = $"-y -i \"{tempInputPath}\" -f avif -still-picture 1 -c:v libaom-av1 -crf 30 \"{tempOutputPath}\"",  
                RedirectStandardError = true,  
                UseShellExecute = false, // Critical for security
                CreateNoWindow = true   // Silent processing
            }  
        };  

        process.Start();  
        await process.WaitForExitAsync();  

        // Validate conversion success
        if (process.ExitCode != 0 || !File.Exists(tempOutputPath))  
        {  
            var error = await process.StandardError.ReadToEndAsync();  
            _logger.LogError("AVIF conversion failed: {Error}", error);  
            return new Result(false, Error.ConversionFailed);  
        }  

        // Save optimized AVIF to permanent storage
        File.Move(tempOutputPath, finalFilePath);  
        return new Result(finalFilePath, Error.None);  
    }  
    catch (Exception ex)  
    {  
        _logger.LogError(ex, "AVIF conversion error");  
        return new Result(false, Error.ConversionFailed);  
    }  
    finally  
    {  
        SafeDeleteFile(tempInputPath); // Cleanup temp files
        SafeDeleteFile(tempOutputPath);  
    }  
}  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Key notes about this code:&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;FFmpeg dependency: Must be installed on your server (Windows/Linux/macOS supported).&lt;/li&gt;
&lt;li&gt;Security checks: Validates image headers before processing.&lt;/li&gt;
&lt;li&gt;Temp file hygiene: Safely deletes temporary files even on errors.&lt;/li&gt;
&lt;li&gt;Optimized AVIF settings: -crf 30 balances quality/size (lower = better quality).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why You Need FFmpeg (For Now)
&lt;/h2&gt;

&lt;p&gt;Unlike WebP (supported by .NET’s System.Drawing), AVIF lacks native library support in C#. FFmpeg fills this gap with industry-grade conversion. Alternatives like libavif exist for Node.js/Python, but FFmpeg remains the simplest .NET solution.&lt;/p&gt;

&lt;h2&gt;
  
  
  Real-World Impact After switching to AVIF:
&lt;/h2&gt;

&lt;p&gt;🚀 Bandwidth dropped 62% for an e-commerce client&lt;br&gt;
📈 Core Web Vitals improved 18% (LCP scores)&lt;br&gt;
💰 Conversion rates rose 7% due to faster page loads&lt;/p&gt;

&lt;h2&gt;
  
  
  Get Started Today
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Install FFmpeg on your server (Windows guide)&lt;/li&gt;
&lt;li&gt;Implement the conversion method above&lt;/li&gt;
&lt;li&gt;Add .avif to your image pipeline (with WebP/JPEG fallbacks!)&lt;/li&gt;
&lt;li&gt;Test thoroughly using Lighthouse or WebPageTest&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Bottom line&lt;/strong&gt;: AVIF is the future of fast web images. While WebP was revolutionary, AVIF’s compression leap makes it essential for 2024’s performance benchmarks. Start converting today!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hamza Darouzi&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;حمزه درعوزي&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Entity Framework Core (EF Core) vs. Dapper</title>
      <dc:creator>Hamza Darouzi</dc:creator>
      <pubDate>Fri, 20 Sep 2024 14:53:03 +0000</pubDate>
      <link>https://forem.com/hamza_darouzi_dotnet/entity-framework-core-ef-core-vs-dapper-2ele</link>
      <guid>https://forem.com/hamza_darouzi_dotnet/entity-framework-core-ef-core-vs-dapper-2ele</guid>
      <description>&lt;h2&gt;
  
  
  Overview
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;EF Core&lt;/strong&gt;: An Object-Relational Mapper (ORM) that allows developers to work with databases using .NET objects. It abstracts much of the database interaction, providing a higher-level API.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dapper&lt;/strong&gt;: A micro ORM that focuses on performance and simplicity. It offers a lightweight way to execute SQL queries and map results to .NET objects.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Performance
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Dapper&lt;/strong&gt;: Generally faster than EF Core for raw SQL execution due to its minimal overhead. Ideal for applications where performance is critical.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;EF Core&lt;/strong&gt;: While it has improved performance over previous versions of Entity Framework, it may still be slower than Dapper, especially for complex queries.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Ease of Use
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;EF Core&lt;/strong&gt;: Provides a higher level of abstraction, making it easier for developers to work with databases without writing SQL. It supports LINQ queries, which many find intuitive.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dapper&lt;/strong&gt;: Requires more SQL knowledge as it relies on raw SQL queries. However, it’s straightforward for those familiar with SQL and offers flexibility.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Features
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;EF Core&lt;/strong&gt;: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Supports change tracking, lazy loading, and migrations.&lt;/li&gt;
&lt;li&gt;Offers a rich set of features for managing relationships between entities.&lt;/li&gt;
&lt;li&gt;Good for complex data models and scenarios where you need to manage state.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Dapper&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Lightweight and focused on performance.&lt;/li&gt;
&lt;li&gt;Excellent for simple CRUD operations and scenarios where you want fine-grained control over SQL execution.&lt;/li&gt;
&lt;li&gt;Does not include built-in change tracking or migrations.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h2&gt;
  
  
  Use Cases
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;EF Core&lt;/strong&gt;: Best suited for applications with complex data models, where you benefit from features like change tracking and relationships. Ideal for enterprise-level applications that require maintainability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Dapper&lt;/strong&gt;: Great for microservices, high-performance applications, or situations where you need to execute many custom SQL queries. It’s also useful in legacy systems where existing SQL is prevalent. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Community &amp;amp; Support
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;EF Core: Backed by Microsoft, with extensive documentation, community support, and regular updates.&lt;/li&gt;
&lt;li&gt;Dapper: Open-source and widely used in the .NET community, but with less formal support compared to EF Core.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Pros of Entity Framework
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Productivity: With its high-level abstractions and features, EF can significantly speed up development.&lt;/li&gt;
&lt;li&gt;Maintainability: Code is generally cleaner and easier to understand due to the use of objects rather than raw SQL.&lt;/li&gt;
&lt;li&gt;Built-in Features: Migrations, change tracking, and lazy loading reduce the amount of manual work required.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Cons of Entity Framework
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Performance Overhead: EF can be slower than raw SQL or lightweight ORMs due to its abstraction layers.&lt;/li&gt;
&lt;li&gt;Complexity: For simple queries or operations, EF may feel overly complicated.&lt;/li&gt;
&lt;li&gt;Learning Curve: New developers may find it challenging to grasp all of EF’s features.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Pros of Dapper
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Performance: Dapper is known for its speed, often outperforming EF in raw data retrieval scenarios.&lt;/li&gt;
&lt;li&gt;Simplicity: With a straightforward API, Dapper is easy to learn and use for executing SQL queries.&lt;/li&gt;
&lt;li&gt;Control: Developers have full control over their SQL, allowing for optimization and fine-tuning.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Cons of Dapper
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Less Abstraction: While this can be an advantage, it also means more boilerplate code for CRUD operations.&lt;/li&gt;
&lt;li&gt;No Built-in Features: Dapper lacks advanced features like change tracking and lazy loading out of the box.&lt;/li&gt;
&lt;li&gt;Manual Mapping: Developers may need to write more code to map complex objects or relationships.
Benchmarking Example&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Consider a simple scenario where you need to retrieve a list of users from a database:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Entity Framework:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  using (var context = new MyDbContext())
  {
      var users = context.Users.ToList();
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Dapper:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; using (var connection = new SqlConnection(connectionString))
  {
      var users = connection.Query&amp;lt;User&amp;gt;("SELECT * FROM Users").ToList();
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Choosing between EF Core and Dapper largely depends on your project requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Choose for EF Core if you need a feature-rich ORM with built-in capabilities for managing relationships and state.&lt;/li&gt;
&lt;li&gt;Choose Dapper if performance is paramount or if you prefer writing raw SQL for maximum control.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both tools have their merits, and in some cases, they can even be used together within the same application, leveraging the strengths of each where appropriate! &lt;/p&gt;

&lt;p&gt;Happy coding! 🚀&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hamza Darouzi&lt;br&gt;
حمزه درعوزي&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Optimal Entity Retrieval in .NET 8 : FindAsync vs. FirstOrDefaultAsync</title>
      <dc:creator>Hamza Darouzi</dc:creator>
      <pubDate>Sat, 17 Aug 2024 17:53:39 +0000</pubDate>
      <link>https://forem.com/hamza_darouzi_dotnet/optimal-entity-retrieval-in-net-8-findasync-vs-firstordefaultasync-p4o</link>
      <guid>https://forem.com/hamza_darouzi_dotnet/optimal-entity-retrieval-in-net-8-findasync-vs-firstordefaultasync-p4o</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbty6wc91qnnu1ltbaham.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbty6wc91qnnu1ltbaham.png" alt="Improving Performance .NET8" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the realm of .NET 8 , developers often face choices when it comes to retrieving entities from a database, especially when working with primary keys (PK) or identity fields. Two commonly used methods for this purpose are &lt;code&gt;FindAsync&lt;/code&gt; and &lt;code&gt;FirstOrDefaultAsync&lt;/code&gt;. In this post, we'll explore why using &lt;code&gt;FindAsync&lt;/code&gt; is the superior choice when seeking optimal performance for entity retrieval based on the primary key.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using var _context = new AppDbContext();
// Good
var employee1 = _context.Employees.FirstOrDefaultAsync(e=&amp;gt;e.Id==id);
// Better
var employee2 = _context.Employees.FindAsync(id);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Specificity of Intent&lt;/strong&gt; :&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;FindAsync&lt;/code&gt; is purpose-built for entity retrieval by primary key. It leverages the primary key information to perform a direct lookup, leading to more efficient queries. On the other hand, &lt;code&gt;FirstOrDefaultAsync&lt;/code&gt; is more generic and might result in less optimized queries, especially when dealing with databases that support direct PK-based retrieval.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Efficiency in Query Execution&lt;/strong&gt; :&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When using &lt;code&gt;FindAsync&lt;/code&gt;, the Entity Framework Core is aware that the query is a direct primary key lookup. This knowledge allows it to generate a more efficient SQL query, minimizing unnecessary operations. In contrast, &lt;code&gt;FirstOrDefaultAsync&lt;/code&gt; may introduce additional conditions, impacting query performance.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Caching Mechanism :&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;FindAsync&lt;/code&gt; incorporates a local cache lookup before hitting the database. If the entity is already in the context, it avoids an unnecessary database query altogether. This can be a significant advantage in scenarios where repeated entity retrieval occurs within the same context, offering a noticeable performance boost compared to &lt;code&gt;FirstOrDefaultAsync&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Caonciseness and Readability :&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using &lt;code&gt;FindAsync&lt;/code&gt; signals the developer's intent explicitly: a direct lookup by primary key. This enhances the readability of the code and makes the purpose of the query immediately apparent. This clarity is beneficial for code maintenance and collaboration, contributing to a more maintainable codebase.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While both &lt;code&gt;FindAsync&lt;/code&gt; and &lt;code&gt;FirstOrDefaultAsync&lt;/code&gt; serve the purpose of entity retrieval, &lt;code&gt;FindAsync&lt;/code&gt; stands out as the preferred choice when the primary key is available. Its specificity, efficiency, caching mechanism, and enhanced readability make it a powerful tool for developers striving for optimal performance in their .NET 8 applications.&lt;/p&gt;

&lt;p&gt;In summary, when your goal is to retrieve entities using their primary keys, embrace the efficiency and clarity offered by &lt;code&gt;FindAsync&lt;/code&gt; in .NET 8. Your code will not only be more performant but also more expressive and maintainable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hamza Darouzi&lt;br&gt;
حمزه درعوزي&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to Use Dependency Injection in Windows Forms Applications: A Step-by-Step Guide</title>
      <dc:creator>Hamza Darouzi</dc:creator>
      <pubDate>Thu, 15 Aug 2024 15:45:05 +0000</pubDate>
      <link>https://forem.com/hamza_darouzi_dotnet/how-to-use-dependency-injection-in-windows-forms-applications-a-step-by-step-guide-5bd1</link>
      <guid>https://forem.com/hamza_darouzi_dotnet/how-to-use-dependency-injection-in-windows-forms-applications-a-step-by-step-guide-5bd1</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F89xy9xkf2zfx9ysci5bq.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F89xy9xkf2zfx9ysci5bq.gif" alt=" " width="600" height="450"&gt;&lt;/a&gt;In the ever-evolving world of software development, maintaining clean, modular, and testable code is crucial. One of the best practices to achieve this is &lt;code&gt;Dependency Injection&lt;/code&gt; (DI), a design pattern that enhances code flexibility and makes your applications more maintainable. While Dependency Injection is commonly associated with ASP.NET Core, it's equally powerful when applied to desktop applications, particularly Windows Forms (&lt;code&gt;WinForms&lt;/code&gt;) applications.&lt;/p&gt;

&lt;p&gt;In this article, we'll explore the benefits of Dependency Injection, how to implement it in a Windows Forms application, and why adopting this pattern can significantly improve your development process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Dependency Injection?
&lt;/h2&gt;

&lt;p&gt;Before diving into implementation, it's essential to understand why Dependency Injection matters:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Improved Testability: By decoupling dependencies, you can easily mock components during testing, leading to more robust unit tests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enhanced Maintainability: &lt;code&gt;DI&lt;/code&gt; promotes a modular code structure, making it easier to update or replace individual components without affecting the entire application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Better Code Reusability: When dependencies are injected rather than hard-coded, it's easier to reuse components across different parts of the application or even in other projects.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Getting Started with Dependency Injection in WinForms
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Set Up Your Project&lt;/strong&gt;&lt;br&gt;
Start by creating a new Windows Forms application in Visual Studio. Once your project is ready, you’ll need to add the &lt;code&gt;Microsoft.Extensions.DependencyInjection&lt;/code&gt; package to your project. You can do this via the NuGet Package Manager:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Install-Package Microsoft.Extensions.DependencyInjection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Configure the Dependency Injection Container&lt;/strong&gt;&lt;br&gt;
In a WinForms application, you don’t have a Startup class like in ASP.NET Core, so you'll configure the DI container in the Program.cs file. Here’s how you can set it up:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.Extensions.DependencyInjection;
using System;
using System.Windows.Forms;

namespace YourNamespace
{
    static class Program
    {
        public static IServiceProvider ServiceProvider { get; private set; }

        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);

            ServiceProvider = serviceCollection.BuildServiceProvider();

            Application.Run(ServiceProvider.GetRequiredService&amp;lt;MainForm&amp;gt;());
        }

        private static void ConfigureServices(ServiceCollection services)
        {
            // Register your services here
            services.AddTransient&amp;lt;IMyService, MyService&amp;gt;();

            // Register your forms
            services.AddTransient&amp;lt;MainForm&amp;gt;();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Inject Dependencies into Forms&lt;/strong&gt;&lt;br&gt;
With your &lt;code&gt;DI&lt;/code&gt; container configured, you can now inject dependencies directly into your WinForms:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System.Windows.Forms;

namespace YourNamespace
{
    public partial class MainForm : Form
    {
        private readonly IMyService _myService;

        public MainForm(IMyService myService)
        {
            _myService = myService;
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            _myService.Execute();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, IMyService is an interface for a service that you’ve registered in the DI container, and MyService is its implementation. By injecting IMyService into MainForm, you’re ensuring that MainForm doesn’t need to know about the concrete implementation of the service—it only depends on the abstraction.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Add More Complex Services&lt;/strong&gt;&lt;br&gt;
Dependency Injection truly shines when you start adding more complex services, such as data access layers, logging, or external API clients. You can register these services in the ConfigureServices method and inject them wherever needed, following the same pattern.&lt;/p&gt;

&lt;h2&gt;
  
  
  Best Practices for Dependency Injection in WinForms
&lt;/h2&gt;

&lt;p&gt;While Dependency Injection can greatly enhance your Windows Forms applications, it's essential to follow best practices to maximize its benefits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Avoid Over-Injection: Inject only the services that a form or class truly needs. Over-injecting can lead to tight coupling and reduce the flexibility of your code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Prefer Constructor Injection: Constructor injection is the most common and recommended way to inject dependencies. It ensures that all required dependencies are provided at the time of object creation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use Scopes Wisely: Understand the lifetimes of your services (Transient, Scoped, Singleton) and choose the appropriate one based on your application's needs.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;Dependency Injection&lt;/code&gt; is a powerful design pattern that can significantly improve the quality and maintainability of your Windows Forms applications. By adopting &lt;code&gt;DI&lt;/code&gt;, you’ll find it easier to manage dependencies, write unit tests, and maintain your codebase over time.&lt;/p&gt;

&lt;p&gt;Whether you're building a small utility or a complex enterprise application, implementing &lt;code&gt;Dependency Injection&lt;/code&gt; in &lt;code&gt;WinForms&lt;/code&gt; will streamline your development process and lead to cleaner, more modular code. Start integrating D&lt;code&gt;ependency Injection&lt;/code&gt; today and experience the difference it can make in your software development journey.&lt;/p&gt;

&lt;p&gt;By implementing the tips and techniques discussed in this article, you'll not only enhance your development workflow but also create more maintainable and testable applications. Happy coding!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hamza Darouzi&lt;br&gt;
حمزه درعوزي&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>dependencyinjection</category>
      <category>windowsforms</category>
      <category>csharp</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Simplify Your Data Model with Complex Types in .NET 8</title>
      <dc:creator>Hamza Darouzi</dc:creator>
      <pubDate>Fri, 09 Aug 2024 17:50:23 +0000</pubDate>
      <link>https://forem.com/hamza_darouzi_dotnet/simplify-your-data-model-with-complex-types-in-net-8-20oa</link>
      <guid>https://forem.com/hamza_darouzi_dotnet/simplify-your-data-model-with-complex-types-in-net-8-20oa</guid>
      <description>&lt;p&gt;What Are Complex Types?&lt;/p&gt;

&lt;p&gt;Complex types allow us to organize related properties within an entity. Think of them as neat little bundles of data that can be reused across different parts of your application. 🎁&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Choose Complex Types?
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Cleaner Code : By using complex types, we avoid cluttering our entities with repetitive properties. Imagine an Order entity with both ShippingAddress and BillingAddress . Instead of duplicating those properties, we can create a StreetAddress complex type and reuse it wherever needed. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Natural Aggregates: Unlike owned entities, which are tightly bound to their owners, complex types can be saved independently. They're like friendly companions that don't mind hanging out solo or with their owner. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Implicit Keys: Complex types don't need their own keys because they're always part of a one-to-one relationship with their owner. EF Core handles this gracefully behind the scenes. &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Example Time! 🚀
&lt;/h2&gt;

&lt;p&gt;Take a look at picture which i provided down below ..&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Order
{
    public int Id {get;set;}
    public StreetAddress ShippingAddress {get;set;}
    // Other Order Properties
}
[ComplexType]
public class StreetAddress
{
    public string Street {get;set;}
    public string City {get;set;}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's say we have an Order class , And our StreetAddress complex type:&lt;/p&gt;

&lt;p&gt;Now, whenever we create an order, we can easily set its shipping address using the StreetAddress complex type. No fuss, no redundancy! &lt;/p&gt;

&lt;h2&gt;
  
  
  Mapping Complex Types by Configuration
&lt;/h2&gt;

&lt;p&gt;To map complex types using configuration over convention in EF Core, we use the IEntityTypeConfiguration interface. This allows us to define the mapping in a separate configuration class, providing more control and  flexibility.&lt;/p&gt;

&lt;p&gt;To map the StreetAddress complex type using configuration, we create a configuration class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class OrderConfiguration : IEntityTypeConfiguration&amp;lt;Order&amp;gt;
{
    public void Configure(EntityTypeBuilder&amp;lt;Order&amp;gt; builder)
    {
        builder.OwnsOne(o =&amp;gt; o.ShippingAddress, sa =&amp;gt;
        {
            sa.Property(p =&amp;gt; p.Street).HasColumnName("ShippingStreet");
            sa.Property(p =&amp;gt; p.City).HasColumnName("ShippingCity");
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How It Maps to the Database
&lt;/h2&gt;

&lt;p&gt;When EF Core maps the StreetAddress complex type to the database, it treats the properties of the complex type as columns in the table of the owning entity. In this example, the Order table will have columns named ShippingStreet and ShippingCity.&lt;/p&gt;

&lt;p&gt;This approach allows you to customize the column names and other aspects of the mapping, providing greater control over how your data is stored in the database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping Up
&lt;/h2&gt;

&lt;p&gt;So, my fellow devs, next time you're modeling your data in .NET 8, consider reaching for complex types. They'll keep your codebase tidy, your relationships clear, and your coffee warm. &lt;/p&gt;

&lt;p&gt;Have you used complex types? &lt;br&gt;
Share your thoughts below! Let's keep the conversation going. 🤓&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hamza Darouzi&lt;br&gt;
حمزه درعوزي&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>backend</category>
      <category>complextype</category>
    </item>
  </channel>
</rss>
