<?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: .Net Labs</title>
    <description>The latest articles on Forem by .Net Labs (@devesh_omar_b599bc4be3ee7).</description>
    <link>https://forem.com/devesh_omar_b599bc4be3ee7</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%2F1789482%2F0be0fcce-1cf7-4f61-9990-0e55face305c.png</url>
      <title>Forem: .Net Labs</title>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/devesh_omar_b599bc4be3ee7"/>
    <language>en</language>
    <item>
      <title>Design Application using Clean Architecture</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Wed, 08 Jan 2025 10:22:06 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/design-application-using-clean-architecture-2efj</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/design-application-using-clean-architecture-2efj</guid>
      <description>&lt;p&gt;Clean Architecture, introduced by Robert C. Martin (Uncle Bob), aims to create systems that are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Independent of frameworks&lt;/li&gt;
&lt;li&gt;Testable&lt;/li&gt;
&lt;li&gt;Independent of UI&lt;/li&gt;
&lt;li&gt;Independent of database&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Independent of any external agency&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Clean Architecture emphasizes separating the concerns of different parts of the system and ensuring that each part has a clear responsibility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;.NET clean architecture as a development approach, available in a layered form to reduce dependency.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The architecture consists of several layers, each with a specific role and dependencies that flow in one direction: from the outer layers to the inner layers.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&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%2Fzyagf5739mo4qzwgu7nz.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%2Fzyagf5739mo4qzwgu7nz.png" alt="Image description" width="800" height="490"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Inner most Layer is independent to its outer layer, means inner most layer does not have any references, it builds and stand independently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dependency Rule&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The core principle of Clean Architecture is the Dependency Rule, which states that source code dependencies can only point inward. This means:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Nothing in inner circle can depend on anything in an outer circle.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Data formats and structures should also follow this rule.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Infrastructure Layer and Presentation Layer are outer most layer so these two layers does not depend on each other.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The main four layers of clean architecture consist of below layers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Domain Layer&lt;/li&gt;
&lt;li&gt;Application Layer&lt;/li&gt;
&lt;li&gt;Infrastructure Layer&lt;/li&gt;
&lt;li&gt;Presentation Layer&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I have created project for better understanding, let’s Learn in detail.&lt;/p&gt;

&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%2Fndftkfoixw7n0ac2pbk3.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%2Fndftkfoixw7n0ac2pbk3.png" alt="Image description" width="698" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I have created below Diagram for better understanding.&lt;/p&gt;

&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%2Fbl44vtxl43c0b6qvbnis.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%2Fbl44vtxl43c0b6qvbnis.png" alt="Image description" width="800" height="498"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Points&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;a. Database implementation happens on Infrastructure layer so consider we connected to SQL database and tomorrow if requirement changes then and client says we need to change database to oracle then we can do with impacting other part of application&lt;/p&gt;

&lt;p&gt;b. Similarly, Presentation Layer, today in this example we have used api end point and instead of it we want to use ASP.net MVC or any other UI framework we can use it without impacting rest of application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://coderandprogrammers.blogspot.com/2025/02/design-application-using-clean.html" rel="noopener noreferrer"&gt;Please click here to see complete tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>design</category>
      <category>architecture</category>
      <category>api</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Best practice for Reading Configuration in .Net Core</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Wed, 08 Jan 2025 08:31:24 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/best-practice-for-reading-configuration-in-net-core-d2f</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/best-practice-for-reading-configuration-in-net-core-d2f</guid>
      <description>&lt;p&gt;Every application start with some configurations at it is required to load configurations at time of bootstrap of application.&lt;/p&gt;

&lt;p&gt;Most of time we provide string values in appsetting and we use directly in application, let’s learn about different ways to Read configurations&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reading using IConfiguration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider below appsetings.json.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"ConfigKeySetting": {
   "Key1": "Keyvalue",
   "Key2": "Keyvalu2",
   "Key3": "Keyvalu2"
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;When we run application we found all configuration already loaded by Microsoft.AspNetCore.Builder.WebApplicationBuilder&lt;/em&gt;&lt;/p&gt;

&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%2Fxfn6u9dnm27fptt80dn9.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%2Fxfn6u9dnm27fptt80dn9.png" alt="Image description" width="800" height="380"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We are injecting IConfiguration object and we can read all keys values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public WeatherForecastController(IConfiguration configuration)
        {

            _configuration = configuration;
        }

        [HttpGet(Name = "ReadConnection")]
        public IActionResult Get()
        {
            var key1 = _configuration.GetValue&amp;lt;string&amp;gt;("ConfigKeySetting:Key1");
            var key2 = _configuration.GetValue&amp;lt;string&amp;gt;("ConfigKeySetting:Key2");
            var key3 = _configuration.GetValue&amp;lt;string&amp;gt;("ConfigKeySetting:Key3");

            return Ok(new
            {
                Key1 = key1,
                Key2 = key2,
                Key3 = key3,

            });

        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we run application and call API we can see we able to read all keys&lt;/p&gt;

&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%2Fnyofp7qbyh78df21zwyh.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%2Fnyofp7qbyh78df21zwyh.png" alt="Image description" width="800" height="638"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem with this approach
&lt;/h2&gt;

&lt;p&gt;a. &lt;strong&gt;Default Value Handling&lt;/strong&gt; : Most of time we put all keys into Azure keyvalue and read from there most of time devops person manages all key vaults so in case my mistake if any key get replaced by devops team then application will break because we do not have any default values if key not found.&lt;/p&gt;

&lt;p&gt;We can handle this situation with &lt;strong&gt;Options Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;b. &lt;strong&gt;Real Time Read&lt;/strong&gt;: Most of time we put all keys into Azure keyvalue and read from there most of time devops person manages all key vaults so in case if we update anything from there then it will not possible to get updated keys without restarting application because everything loaded.&lt;/p&gt;

&lt;p&gt;We can read on real time using &lt;strong&gt;Options Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;b.** No Validation**: IConfiguration does not perform any validation over the configuration values, which might be fatal during the application runtime.&lt;/p&gt;

&lt;p&gt;d.** No Type-Safety:** As mentioned earlier, the interface reads configurations as strings that have to be parsed manually. This also increases the chances of configuration-related issues.&lt;/p&gt;

&lt;p&gt;**IConfiguration **is a simple and lightweight approach for loading configurations in ASP.NET Core applications from the appsettings file. However, we need a more robust solution for handling a bit more advanced requirements like Validations, Type-Safety, and Reloading etc&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's learn about Option pattern
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Option Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Options Pattern is used to bind a section of configuration settings to the strongly types options classes and add it to the Asp.Net Core Dependency Injection Service Container as singleton lifetime.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/c-sharp-programming/best-practice-for-reading-configuration-in-net-core-option-pattern-65c97ddf31ac?sk=9390d71b6c6b888e6e2d73eeed714b2f" rel="noopener noreferrer"&gt;Please click here to see complete tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>learning</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Static Lambda in C# 12 : Performance Improvement</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Tue, 07 Jan 2025 10:02:57 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/static-lambda-in-c-12-performance-improvement-15c6</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/static-lambda-in-c-12-performance-improvement-15c6</guid>
      <description>&lt;p&gt;A Static lambda, introduced in C# 12, is a lambda expression that cannot capture any variables from its enclosing scope. This means no closure class is generated, resulting in less memory allocation and potentially better performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let’s work with some examples.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Sorting Collections:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Sorting a list of integers using a static lambda ensures no closures are created, reducing overhead during sorting&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var numbers = new List&amp;lt;int&amp;gt; { 53, 31, 8, 1, 2,100,34,55,11,1 };
numbers.Sort(static (a, b) =&amp;gt; a.CompareTo(b));
foreach (var item in numbers)
{
    Console.WriteLine(item);
}
Console.ReadKey();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result&lt;/p&gt;

&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%2Fsuu7uvwyqb78cfyproc7.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%2Fsuu7uvwyqb78cfyproc7.png" alt="Image description" width="780" height="477"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.  Array Filtering&lt;/strong&gt;&lt;br&gt;
Filtering an array with a static lambda avoids capturing variables, making the filtering operation more efficient.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Console.WriteLine("--------Array Filtering-----------");
var array = new[] { 1, 2, 3, 4, 5 };
var filtered = Array.FindAll(array, static n =&amp;gt; n &amp;gt; 3);
foreach (var item in filtered)
{
    Console.WriteLine(item);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://medium.com/stackademic/static-lambda-in-c-12-performance-improvement-b8e37c66bdb3?sk=33580f2a00286c2e3964648cd8d974e5" rel="noopener noreferrer"&gt;click here to see complete tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>csharp</category>
      <category>dotnet</category>
      <category>programming</category>
    </item>
    <item>
      <title>Builder Pattern in C#: Practical Implementation and Examples</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Tue, 07 Jan 2025 09:59:04 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/builder-pattern-in-c-practical-implementation-and-examples-451n</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/builder-pattern-in-c-practical-implementation-and-examples-451n</guid>
      <description>&lt;p&gt;This pattern can be ideal approach to create complex objects&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The Builder pattern is a creational design pattern that is used to construct complex objects step by step. It allows you to create different representations of an object using the same construction process.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Let’s first understand the problems that exist without using this pattern.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Complex Constructor with Many Parameters&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When creating objects that require many parameters, constructors can become lengthy and hard to read.&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 House
{
    public House(int walls, int doors, int windows, bool hasGarage, bool hasSwimmingPool, bool hasStatues, bool hasGarden)
    {
        // Initialization
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are many problems if constructor have too many parameters&lt;/p&gt;

&lt;p&gt;i) Each time we need to pass n numbers of parameters at time of object creations&lt;/p&gt;

&lt;p&gt;ii) we need to update constructor if we need to pass one more parameter so such constructor difficult to manage&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Constructor Overload Explosion&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Sometimes we need to create overloaded constructor based on parameters, so managing multiple constructors again have some headache.&lt;/p&gt;

&lt;p&gt;To handle different combinations of parameters, multiple constructor overloads are often created, leading to code duplication and increased maintenance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public House(int walls, int doors) { ... }
public House(int walls, int doors, int windows) { ... }
public House(int walls, int doors, int windows, bool hasGarage) { ... }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Readability and Maintainability Issues:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Code that creates instances with many parameters becomes hard to read and maintain.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var house = new House(4, 2, 6, true, false, true, true);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Introduction of Builder pattern to fix those issues&lt;br&gt;
The Builder pattern breaks down the construction of a complex object into simpler steps. Each step builds a part of the product, and the final step assembles the product.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Builder Pattern&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://medium.com/stackademic/builder-pattern-in-c-practical-implementation-and-examples-807f2e0aff5f?sk=78d14f082863e1c0f8ae680bcc45e611" rel="noopener noreferrer"&gt;Click here to see complete tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>designpatterns</category>
      <category>csharp</category>
      <category>coding</category>
    </item>
    <item>
      <title>Dapper vs EF Core: Understanding When to Use Each</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Tue, 07 Jan 2025 09:53:24 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/dapper-vs-ef-core-understanding-when-to-use-each-4fji</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/dapper-vs-ef-core-understanding-when-to-use-each-4fji</guid>
      <description>&lt;p&gt;&lt;em&gt;While designing application we need to understand which we should use and what are use cases, it is very critical to decide based on nature of requirements&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Both Dapper and Entity Framework Core (EF Core) are popular Object-Relational Mapping (ORM) libraries for .NET, but they serve different purposes and have distinct strengths.&lt;/p&gt;

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

&lt;p&gt;Dapper is a micro ORM that focuses on high performance and simplicity. It maps the results of SQL queries to C# objects, but unlike EF Core, it does not provide advanced features such as change tracking or LINQ-based querying.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key points&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;: Dapper is known for its speed. It’s a lightweight library that doesn’t add much overhead, making it great for performance-critical applications where raw speed matters.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Control&lt;/strong&gt;: Dapper gives you direct control over your SQL queries, making it easier for developers to optimize them for specific database scenarios.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code Examples&lt;/strong&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 async Task&amp;lt;Account&amp;gt; GetAccountAsync(Guid accountId)
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            var sql = "SELECT * FROM Accounts WHERE AccountId = @AccountId";
            return await connection.QuerySingleOrDefaultAsync&amp;lt;Account&amp;gt;(sql, new { AccountId = accountId });
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Real-World Use Cases for Dapper:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. High-Performance Data Retrieval&lt;/strong&gt;: If your application needs to handle high-throughput operations, such as querying large datasets or making many database calls, Dapper’s minimal overhead and speed would be ideal.&lt;/p&gt;

&lt;p&gt;Example: Real-time analytics applications that need to query and process large volumes of data in real time, such as financial dashboards or e-commerce websites with heavy traffic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Read-Only Operations:&lt;/strong&gt; When your application only needs to fetch data without performing complex operations, Dapper excels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Building APIs for querying a public catalog (e.g., an online store’s product catalog) where the focus is on retrieving data without the need for full CRUD operations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.Complex SQL Queries&lt;/strong&gt;: When your queries are too complex for LINQ or require very fine-tuned SQL (e.g., custom joins, aggregations), Dapper allows you to write the SQL exactly as needed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Reporting services that need to execute complex SQL queries involving joins, window functions, or other advanced SQL features that EF Core may not easily support.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/stackademic/dapper-vs-ef-core-understanding-when-to-use-each-3dc2258e7680?sk=9ba0a014f96b0373ee1f95e9a30c9837" rel="noopener noreferrer"&gt;Click here to see complete tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>coding</category>
      <category>programming</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Improve Application Performance using “Fire and Forget” in .NET Core</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Mon, 30 Dec 2024 17:28:27 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/improve-application-performance-using-fire-and-forget-in-net-core-28kf</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/improve-application-performance-using-fire-and-forget-in-net-core-28kf</guid>
      <description>&lt;p&gt;Fire and Forget is nothing but it is Executing Task in Background&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deep dive into Task.Run()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By using the fire-and-forget approach appropriately, you can improve the responsiveness and performance of your .NET Core applications while ensuring that important background tasks are performed efficiently.&lt;/p&gt;

&lt;p&gt;In this tutorial we will focus on Task.Run and will learn how we can perform background work with Task.Run&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Task.Run ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Task.Run queues the specified work to run on the thread pool and returns a Task object representing that work. This allows the work to be performed asynchronously without blocking the main thread.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Task.Run Works: Control Flow Diagram&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Task Creation&lt;/strong&gt;: The Task.Run method creates a new Task object.&lt;br&gt;
Queueing Work: The task is queued to the thread pool.&lt;br&gt;
Thread Pool Execution: A thread pool thread picks up the task and executes it.&lt;/p&gt;

&lt;p&gt;Task Completion: The task completes and the Task object is marked as completed, faulted, or canceled, depending on the outcome.&lt;/p&gt;

&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%2Ft6i0ofkky61mf9ssqico.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%2Ft6i0ofkky61mf9ssqico.png" alt="Image description" width="800" height="454"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Task.Run in .NET Core allows you to offload work to a background thread, which can help improve the responsiveness of your application by freeing up the main thread for other tasks&lt;/p&gt;

&lt;p&gt;Below is few Real time use cases where we can use Task.Run&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real Time Examples&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Logging&lt;/strong&gt;&lt;br&gt;
This is perfect use case and each and every application doing logging Let’s understand how we can improve performance&lt;/p&gt;

&lt;p&gt;Suppose after successful database operation we want to log operation results and if we do sequentially then UI will remain block and OfCourse this is not important work from UI user or client, so if we perform Logging in background then that will increase response time.&lt;/p&gt;

&lt;p&gt;Detailed implementation&lt;/p&gt;

&lt;p&gt;Logger Service: we are logging using Task.Run in code 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 interface ILoggingService
{
    void LogInformation(string message);
}

public class LoggingService : ILoggingService
{
    public void LogInformation(string message)
    {
        Task.Run(() =&amp;gt; 
        {
            // Simulate logging operation
            System.IO.File.AppendAllText("log.txt", $"{DateTime.UtcNow}: {message}{Environment.NewLine}");
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Controller&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
    private readonly ILoggingService _loggingService;

    public ExampleController(ILoggingService loggingService)
    {
        _loggingService = loggingService;
    }

    [HttpGet]
    public IActionResult Get()
    {  
         // Reading Work to DB

        ///

        _loggingService.LogInformation("Get method called.");
        return Ok("Hello, world!");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Generating Reports&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/stackademic/improve-application-performance-using-fire-and-forget-in-net-core-2b902a6acb75?sk=02736f1f55a0e484bd2c54a5a9c7d5b7" rel="noopener noreferrer"&gt;Please click here to see complete tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>api</category>
      <category>dotnetcore</category>
      <category>csharp</category>
    </item>
    <item>
      <title>Best practice with CancellationToken in .Net Core</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Mon, 30 Dec 2024 17:21:28 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/best-practice-with-cancellationtoken-in-net-core-34e0</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/best-practice-with-cancellationtoken-in-net-core-34e0</guid>
      <description>&lt;p&gt;In this tutorial we will lean about CancellationToken and how we can use it.&lt;/p&gt;

&lt;p&gt;In earlier days, when we had time taking operations like time consuming DB calls, time consuming HTTP calls we had no option to cancel it.&lt;/p&gt;

&lt;p&gt;Using a CancellationToken in your applications provides several benefits, particularly in improving responsiveness, resource management, and user experience. Here are some key advantages:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Improved Responsiveness&lt;/strong&gt;&lt;br&gt;
User Experience: Applications that can cancel long-running tasks quickly respond to user actions, such as canceling a file upload or download, leading to a better user experience.&lt;br&gt;
Real-Time Adjustments: Users can adjust their actions (e.g., stopping a search operation) without waiting for the current operation to complete.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Resource Management&lt;/strong&gt;&lt;br&gt;
Efficient Use of Resources: Canceling unnecessary operations prevents waste of CPU, memory, and other resources. This is particularly important for server-side applications where resources are shared among many users.&lt;br&gt;
Database Connections: In database operations, using CancellationToken can free up database connections that would otherwise be held by long-running queries.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Scalability&lt;/strong&gt;&lt;br&gt;
Handling High Load: Applications can handle high loads more gracefully by canceling operations that are no longer needed, thus freeing up resources for new incoming requests.&lt;br&gt;
Concurrency Control: Effective cancellation helps manage concurrent tasks, ensuring that resources are allocated to the most critical operations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Error Handling and Stability&lt;/strong&gt;&lt;br&gt;
Graceful Shutdown: When an application needs to shut down or restart, CancellationToken allows for a graceful termination of ongoing operations, reducing the risk of data corruption or inconsistent states.&lt;br&gt;
Preventing Deadlocks: By canceling operations that are taking too long, you can reduce the likelihood of deadlocks and other concurrency issues.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Timeout Implementation&lt;/strong&gt;&lt;br&gt;
Automatic Timeout: Implementing timeouts using CancellationTokenSource.CancelAfter can automatically cancel tasks that exceed a specified duration, ensuring that your application remains responsive.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Task Coordination&lt;/strong&gt;&lt;br&gt;
Cooperative Cancellation: CancellationToken allows for cooperative cancellation, where the operation periodically checks the token to see if cancellation is requested, allowing the operation to clean up and terminate gracefully.&lt;br&gt;
Linked Cancellation Tokens: You can link multiple CancellationTokenSource instances together to cancel multiple operations simultaneously, simplifying the coordination of complex tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Simplified Code Maintenance&lt;/strong&gt;&lt;br&gt;
Standard Pattern: Using CancellationToken establishes a standard pattern for task cancellation, making the code easier to understand and maintain.&lt;br&gt;
Consistent Handling: It provides a consistent way to handle cancellations across different parts of your application, from user-initiated cancellations to automatic timeouts and application shutdowns.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example Use Cases&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Web Applications&lt;/strong&gt;: Cancel database queries, file uploads/downloads, and API calls that are no longer needed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Desktop Applications&lt;/strong&gt;: Allow users to cancel long-running operations like image processing or data analysis.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mobile Applications&lt;/strong&gt;: Improve battery life by canceling background operations when they are no longer needed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cloud Services&lt;/strong&gt;: Efficiently manage resources by canceling operations in response to scaling events or maintenance windows.&lt;/p&gt;

&lt;p&gt;Here’s a simplified example of how CancellationToken can be used to cancel an ongoing operation:&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 LongRunningOperationAsync(CancellationToken cancellationToken)
{
    for (int i = 0; i &amp;lt; 100; i++)
    {
        // Periodically check if cancellation is requested
        cancellationToken.ThrowIfCancellationRequested();

        // Simulate some work
        await Task.Delay(100);
    }
}

public async Task MainAsync()
{
    using var cts = new CancellationTokenSource();

    // Cancel the operation after 2 seconds
    cts.CancelAfter(TimeSpan.FromSeconds(2));

    try
    {
        await LongRunningOperationAsync(cts.Token);
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine("Operation was canceled.");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://medium.com/stackademic/best-practice-with-cancellationtoken-in-net-core-189f593df2f1?sk=8dc7ed3f88773dafcca86c0da78e682a" rel="noopener noreferrer"&gt;Follow this link to see complete tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>dotnet</category>
      <category>csharp</category>
    </item>
    <item>
      <title>How to use Scoped service from Singleton Service in .Net Core</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Mon, 30 Dec 2024 15:00:20 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/how-to-use-scoped-service-from-singleton-service-in-net-core-1kd6</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/how-to-use-scoped-service-from-singleton-service-in-net-core-1kd6</guid>
      <description>&lt;p&gt;We should be very careful about lifetime of objects in .net core.&lt;/p&gt;

&lt;p&gt;Suppose we created Two services one register as Singleton and other as Scoped.&lt;/p&gt;

&lt;p&gt;Code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IScopedService
 {  
 }

 public interface ISingletonService
 {

 }

/// Scope service
 public class ScopedService : IScopedService
 {
     public ScopedService()

     {

     }

 }
/// Singelton Service , here we are injecting scope service object
 public class SingletonService : ISingletonService
 {
     public SingletonService(IScopedService svc)

     {

     }

 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Program.cs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


builder.Services.AddSingleton&amp;lt;ISingletonService, SingletonService&amp;gt;();

builder.Services.AddScoped&amp;lt;IScopedService, ScopedService&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&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%2Fzll9jjfiw5hb245od2aq.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%2Fzll9jjfiw5hb245od2aq.png" alt="Image description" width="800" height="350"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding of code.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;we have created two classes Singelton and Scoped and we have injected scoped inside singleton service.&lt;/p&gt;

&lt;p&gt;When we run application, we will get below error&lt;/p&gt;

&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%2F0k0zipdjkshn13234dac.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%2F0k0zipdjkshn13234dac.png" alt="Image description" width="800" height="404"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding Error&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We have 3 types of service lifetimes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Singleton — they’re created first time they’re request, and every time after that the same instance will be reused&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Scoped — they’re created once per the request (connection)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Transient are created every time you request them from the DI container&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;_Here we are trying to inject a object that will be created on each user scope request so that required to dispose after each and every request. Here Singelton object will never be going to dispose but scoped object is required to dispose, so this is conflict.&lt;br&gt;
_&lt;/p&gt;

&lt;p&gt;As per above explanation we should almost never consume scoped service or transient service from a singleton. You should also avoid consuming transient service from a scoped service.&lt;/p&gt;

&lt;p&gt;What is happening when you consume scoped service from a singleton service is known as a captive dependency. It occurs when a service intended to live for a short(er) amount of time gets held by a service that lives for a more extended amount of time. This almost always suggests that you should change something in your design.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Solution *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If there is need to use Scoped service inside singleton then we need to create scope manually. A new scope can be created by injecting an IServiceScopeFactory into your singleton service. The IServiceScopeFactory has a CreateScope method, which is used for creating new scope instances. IServiceScopeFactory is singelton in itself that’s why it works here.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/c-sharp-programming/how-to-use-scoped-service-from-singleton-service-in-net-core-d4b92fecb52a?sk=21e33a09b64a2d65e0d22a4e6bdad2b5" rel="noopener noreferrer"&gt;Please Click here for complete implementation&lt;/a&gt;&lt;/p&gt;

</description>
      <category>dotnetcore</category>
      <category>dotnet</category>
      <category>api</category>
      <category>programming</category>
    </item>
    <item>
      <title>Fallback Pattern in .NET Core: Handling Service Failures Gracefully</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Mon, 30 Dec 2024 14:50:51 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/fallback-pattern-in-net-core-handling-service-failures-gracefully-2358</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/fallback-pattern-in-net-core-handling-service-failures-gracefully-2358</guid>
      <description>&lt;p&gt;&lt;strong&gt;Fallback pattern is a resilience design pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This pattern ensures that alternative response will reach to client even in case of failing primary API.&lt;/p&gt;

&lt;p&gt;The Fallback pattern is a resilience design pattern used to provide an alternative or backup solution when the primary service or component fails. It helps ensure that the application continues to function and provide some level of service, even if certain parts are not working as expected.&lt;/p&gt;

&lt;p&gt;It ensures service continuity, improves user experience, and provides significant business benefits by reducing the impact of failures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problems Resolved by the Fallback Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Continuity of Operations&lt;/strong&gt;: Ensures critical operations are not interrupted by providing alternative paths for execution.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Service Unavailability&lt;/strong&gt;: When a primary service is down or unavailable, the fallback pattern provides an alternative, ensuring that the application continues to function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Error Handling&lt;/strong&gt;: It allows the system to handle errors gracefully without crashing, maintaining a smooth user experience.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Enhanced User Experience&lt;/strong&gt;: Minimizes disruptions for end-users, maintaining their trust and satisfaction.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&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%2Fhkt3rodsn7gtrkh01yoo.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%2Fhkt3rodsn7gtrkh01yoo.png" alt="Image description" width="800" height="442"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Implementation&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Steps&lt;br&gt;
a. We will create 2 Endpoints Primary and Secondary API&lt;/p&gt;

&lt;p&gt;b. Primary API will throw error&lt;/p&gt;

&lt;p&gt;c. We will implement Fallback Policy into separate Api end point, or we can also create console application client&lt;/p&gt;

&lt;p&gt;d. To implement Fallback we will use polly nuget package and we will configure both end point and will define policy like if API 1 not responding then Request go to API 2 and will respond&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/stackademic/fallback-pattern-in-net-core-handling-service-failures-gracefully-90114a257566?sk=c06983b76554003dd424480c5029c14e" rel="noopener noreferrer"&gt;Click  here for code implementation &lt;/a&gt;&lt;/p&gt;

</description>
      <category>api</category>
      <category>performance</category>
      <category>dotnet</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Fixing Multiple If-Else problem with Chain of Responsibility Pattern</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Mon, 30 Dec 2024 14:43:10 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/fixing-multiple-if-else-problem-with-chain-of-responsibility-pattern-1kmi</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/fixing-multiple-if-else-problem-with-chain-of-responsibility-pattern-1kmi</guid>
      <description>&lt;p&gt;Situation will become unmanageable if we have lot of if else condition in our code, Lets understand problem and then we will see it’s Solution.&lt;/p&gt;

&lt;p&gt;Problem with Multiple If Conditions&lt;br&gt;
Using multiple if-else conditions to handle different cases can lead to code that is hard to read, maintain, and extend. Here’s a simple example using multiple if conditions in a leave management system.&lt;/p&gt;

&lt;p&gt;We will implement below Business Logic for Leave management system&lt;/p&gt;

&lt;p&gt;a. IF Leave &amp;lt; = 3, then Team Lead will approve&lt;/p&gt;

&lt;p&gt;b. IF Leave &amp;lt; =5, then Project Manager will approve&lt;/p&gt;

&lt;p&gt;c. IF Leave &amp;gt; 5, then HR Manager will approve&lt;/p&gt;

&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%2Fs59vtbeu4gt7j77jny28.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%2Fs59vtbeu4gt7j77jny28.png" alt="Image description" width="800" height="313"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Request first go to team lead to check if Request can be handled by Team lead else it will go to Project Manager else request will go to HR manager&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example with Multiple If Conditions&lt;/strong&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 LeaveRequest
{
    public string EmployeeName { get; set; }
    public int NumberOfDays { get; set; }
    public string Reason { get; set; }
}

public class LeaveApprovalService
{
    public void ApproveLeave(LeaveRequest request)
    {
        if (request.NumberOfDays &amp;lt;= 3)
        {
            Console.WriteLine($"Leave request by {request.EmployeeName} for {request.NumberOfDays} days approved by Team Lead.");
        }
        else if (request.NumberOfDays &amp;lt;= 5)
        {
            Console.WriteLine($"Leave request by {request.EmployeeName} for {request.NumberOfDays} days approved by Project Manager.");
        }
        else if (request.NumberOfDays &amp;gt; 5)
        {
            Console.WriteLine($"Leave request by {request.EmployeeName} for {request.NumberOfDays} days approved by HR Manager.");
        }
        else
        {
            Console.WriteLine("Leave request could not be processed.");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Problems in above code&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Maintainability&lt;/strong&gt;: The method becomes harder to maintain as the logic grows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Single Responsibility Principle (SRP)&lt;/strong&gt;: The method does too much by handling all approval levels, violating the single responsibility principle.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Testing *&lt;/em&gt; : Each time we add new condition we need to test end to end to make sure nothing is breaking because we are making changes into existing class because we are breaking SRP.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution with Chain of Responsibility Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/dev-genius/fixing-multiple-if-else-problem-with-chain-of-responsibility-pattern-03c730e870df?sk=a7e8906b64bed5e4c06c3dec3eb0f05f" rel="noopener noreferrer"&gt;Please click here for fixing this problem &lt;/a&gt;&lt;/p&gt;

</description>
      <category>designpatterns</category>
      <category>csharp</category>
      <category>dotnet</category>
      <category>api</category>
    </item>
    <item>
      <title>Optimizing Performance using Efficient LINQ queries</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Sun, 29 Dec 2024 11:48:18 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/optimizing-performance-using-efficient-linq-queries-392f</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/optimizing-performance-using-efficient-linq-queries-392f</guid>
      <description>&lt;p&gt;&lt;em&gt;In efficient SQL or LINQ may results into poor performance because that will lead high cost of reading data and will consume more resources. High consumption of CPU may lead to poor application response and server will not able to serve whatever server can deliver.&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Using Any Instead of Count for Existence Check&lt;/strong&gt;
Problem: Count iterates over the entire collection to count elements.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// BAD code
bool exists = collection.Count(x =&amp;gt; x.IsActive) &amp;gt; 0;

//Efficient Code
bool exists = collection.Any(x =&amp;gt; x.IsActive);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;: Any stops after finding the first matching element, improving performance&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Avoiding ForEach with LINQ&lt;/strong&gt;
&lt;strong&gt;Problem&lt;/strong&gt;: ForEach requires you to materialize the collection (using ToList() or ToArray()), which can have performance implications, especially with large datasets.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Consequence&lt;/strong&gt;: By forcing materialization, you lose the advantages of lazy evaluation in LINQ, leading to unnecessary intermediate collections being created, which can impact performance and memory usage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Poor Code:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var result = numbers.Where(n =&amp;gt; n &amp;gt; 2).ToList().ForEach(n =&amp;gt; Console.WriteLine(n)); // Forces enumeration, breaking lazy evaluation
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Effificent Code&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var result = numbers.Where(n =&amp;gt; n &amp;gt; 2).ToList();  // Materializing to a list, then using ForEach
result.ForEach(n =&amp;gt; Console.WriteLine(n));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;: Use a foreach loop for side effects to avoid unnecessary list creation.&lt;/p&gt;

&lt;p&gt;3.&lt;strong&gt;Efficient Distinct Usage&lt;/strong&gt;&lt;br&gt;
Problem: Using Distinct on large datasets can be slow.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//bad one
var result = collection.Select(x =&amp;gt; x.Name).Distinct().ToList();


//Efficient code
var result = collection.Select(x =&amp;gt; x.Name).ToHashSet();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In LINQ, both ToHashSet() and Distinct() are used to eliminate duplicates from a collection, but they differ in how they operate internally, which affects performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ToHashSet() and Distinct() Comparison&lt;br&gt;
**&lt;br&gt;
**1. ToHashSet()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Description&lt;/strong&gt;: Converts a collection into a HashSet, which automatically removes duplicates because HashSet is a collection that only allows unique elements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;: ToHashSet() is typically faster when removing duplicates because it uses the hashing mechanism to check for uniqueness while building the set. The time complexity is generally O(n), where n is the number of elements in the collection. This is because HashSet has an average time complexity of O(1) for insertion and membership checks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Distinct()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Description&lt;/strong&gt;: Distinct() is a LINQ method that removes duplicates from a collection by comparing the elements using their default equality comparer (or a custom one if provided). It returns a new collection (typically an IEnumerable).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;: Distinct() internally uses a HashSet as well, but since it works on IEnumerable, it has a higher overhead due to the deferred execution and the need to iterate through the collection. The time complexity is also generally O(n), but it can have higher overhead because it requires creating an enumerator and possibly comparing each item in the sequence.&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;Use ToHashSet()&lt;/strong&gt; when you just need to remove duplicates and are working directly with a collection.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Distinct()&lt;/strong&gt; if you're working in the context of a LINQ query with more complex operations.&lt;/p&gt;

&lt;p&gt;Please Read complete list with below Url&lt;/p&gt;

&lt;p&gt;&lt;a href="https://medium.com/dev-genius/optimizing-performance-using-efficient-linq-queries-a32382d07365?sk=62a5195f848f8534e81bb3d2fde0be7d" rel="noopener noreferrer"&gt;Follow this link to know more about performance with Linq&lt;/a&gt;&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>api</category>
      <category>performance</category>
      <category>sql</category>
    </item>
    <item>
      <title>Understanding Network Latency for High performance web-based applications</title>
      <dc:creator>.Net Labs</dc:creator>
      <pubDate>Sun, 29 Dec 2024 11:23:52 +0000</pubDate>
      <link>https://forem.com/devesh_omar_b599bc4be3ee7/understanding-network-latency-for-high-performance-web-based-applications-2kdp</link>
      <guid>https://forem.com/devesh_omar_b599bc4be3ee7/understanding-network-latency-for-high-performance-web-based-applications-2kdp</guid>
      <description>&lt;p&gt;It is crucial to consider Latency for High performance web-based applications&lt;/p&gt;

&lt;p&gt;Network latency is the time it takes for data or a request to go from the source to the destination. Latency in networks is measured in milliseconds. &lt;/p&gt;

&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%2Fu6uqzgrgcme2n5kk0a87.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%2Fu6uqzgrgcme2n5kk0a87.png" alt="Image description" width="800" height="445"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;High latency can significantly affect the performance of networked applications, causing delays and reducing the overall user experience.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Symptoms of Network Latency&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Slow Response Times&lt;/strong&gt;: Web application will take longer time to load&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Timed-out Connections&lt;/strong&gt;: Connections to servers may time out due to delays in data transmission.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;High Ping Times&lt;/strong&gt;: Measured in milliseconds (ms), high ping times indicate delays in communication between devices.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Root Causes of Network Latency
&lt;/h2&gt;

&lt;p&gt;1.** Physical Distance:**&lt;br&gt;
Suppose we have application hosted at United state and all users of applications belongs to Australia. In this case data packets are travelling too much distance which does not make sense here.&lt;/p&gt;

&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%2Faljtd0pjeldfrljwl4v0.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%2Faljtd0pjeldfrljwl4v0.png" alt="Image description" width="800" height="408"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In above example we can see it has high latency due to packet travel too long due to huge physical distance between server and user so we should choose correct server location based on real time usage.&lt;/p&gt;

&lt;p&gt;Here in example below we can see Server and user both are in same country then we will have less latency issues due to less physical distance&lt;/p&gt;

&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%2Fcwa4yo6n5i7uyig3kvjb.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%2Fcwa4yo6n5i7uyig3kvjb.png" alt="Image description" width="800" height="610"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Network Congestion&lt;/strong&gt;: High traffic on the network can cause delays as data packets compete for bandwidth&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Routing and Hops&lt;/strong&gt;: Data passing through multiple routers and switches (hops) can slow down transmission.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&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%2Fdqpe2gbm2317caenc2y1.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%2Fdqpe2gbm2317caenc2y1.png" alt="Image description" width="800" height="345"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this diagram we can see latency will increase due to lot of routers in network path.&lt;/p&gt;

&lt;p&gt;4.** Hardware Limitations**: Outdated or insufficient hardware (e.g., routers, switches) can contribute to latency.&lt;/p&gt;

&lt;p&gt;5.** Network Protocols and Configuration**: Inefficient network protocols or misconfigured network settings can introduce delays.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Server Load&lt;/strong&gt;: Overloaded servers can slow down response times, adding to latency.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  We have multiple Solutions for this so let's discuss
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://medium.com/@devesh.akgec/understanding-network-latency-for-high-performance-web-based-applications-f7a7dc6526b1" rel="noopener noreferrer"&gt;Please Click here to get solutions&lt;/a&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>networking</category>
      <category>performance</category>
      <category>api</category>
    </item>
  </channel>
</rss>
