<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Farhad Hemmatzadeh on Medium]]></title>
        <description><![CDATA[Stories by Farhad Hemmatzadeh on Medium]]></description>
        <link>https://medium.com/@f.hemmatzadeh?source=rss-168638433738------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hCdqSmlpzPfJ7vKvuYhdHg.jpeg</url>
            <title>Stories by Farhad Hemmatzadeh on Medium</title>
            <link>https://medium.com/@f.hemmatzadeh?source=rss-168638433738------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:04:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@f.hemmatzadeh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Exception Handling in C#: Understanding the throw Statement and Its Variants]]></title>
            <link>https://medium.com/@f.hemmatzadeh/exception-handling-in-c-understanding-the-throw-statement-and-its-variants-03a52bb962bc?source=rss-168638433738------2</link>
            <guid isPermaLink="false">https://medium.com/p/03a52bb962bc</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Farhad Hemmatzadeh]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 14:48:35 GMT</pubDate>
            <atom:updated>2024-12-03T14:48:35.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDT2fkLAXcDm_zn1bCYJyw.jpeg" /></figure><h3>Introduction</h3><p>Exception handling is a cornerstone of robust software development. In C#, the throw statement allows developers to propagate errors to calling methods. However, how you throw an exception significantly impacts debugging, maintainability, and performance.</p><p>In this article, we’ll explore four common approaches to handling exceptions (throw, throw ex, throw new AggregateException, and ExceptionDispatchInfo.Throw) with real-world examples and best practices to help you use the right technique in different scenarios.</p><h3>Learning Objectives</h3><p>By the end of this article, you will:</p><ol><li>Understand the different ways to rethrow exceptions in C#.</li><li>Learn the pros, cons, and real-world use cases for each approach.</li><li>Recognize best practices for exception handling in various programming scenarios.</li></ol><h3>Prerequisites</h3><p>To follow along, you should have:</p><ol><li>A basic understanding of C# and exception handling.</li><li>Familiarity with the try-catch block and concepts like stack traces.</li><li>Access to a .NET development environment, such as Visual Studio.</li></ol><h3>Getting Started</h3><p>We’ll analyze four approaches to handling exceptions in C#, covering their syntax, usage, and real-world examples.</p><h3>Throw vs throw ex</h3><p>Let’s first discuss the difference between throw and throw ex.</p><h4>Code Example: Using throw</h4><p>The throw statement rethrows the original exception while preserving its stack trace. It’s useful when you need to log an exception or perform some cleanup but still want the caller to handle the error.</p><pre>using System;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        try<br>        {<br>            Me();<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine($&quot;Caught an exception: {ex.Message}&quot;);<br>        }<br>    }<br><br>    static void Me()<br>    {<br>        try<br>        {<br>            throw new InvalidOperationException(&quot;Something went wrong in Me&quot;);<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine(&quot;Logging the exception...&quot;);<br>            throw; // Preserves the original stack trace<br>        }<br>    }<br>}</pre><h4>Output:</h4><pre>Logging the exception...<br>Caught an exception: Something went wrong in Me</pre><p><strong>Best Practice</strong>: Always use throw to preserve the original stack trace unless you have a specific reason to reset it.</p><h4>Code Example: Using throw ex</h4><p>Using throw ex resets the stack trace, making it appear as if the exception was thrown from the throw ex line.</p><pre>using System;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        try<br>        {<br>            Me();<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine($&quot;Caught an exception: {ex.Message}&quot;);<br>        }<br>    }<br><br>    static void Me()<br>    {<br>        try<br>        {<br>            throw new InvalidOperationException(&quot;Something went wrong in Me&quot;);<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine(&quot;Logging the exception...&quot;);<br>            throw ex; // Resets the stack trace<br>        }<br>    }<br>}</pre><h4>Output:</h4><pre>Logging the exception...<br>Caught an exception: Something went wrong in Me</pre><p>However, the stack trace will now point to the throw ex line instead of the original error location.</p><ul><li><strong>Best Practice</strong>: Avoid throw ex unless resetting the stack trace is intentional (e.g., when hiding internal implementation details).</li></ul><h3>Wrapping Exceptions with throw new</h3><p>When you want to provide additional context or aggregate multiple exceptions, you can use throw new. This approach creates a new exception and wraps the original one as an inner exception.</p><h4>Code Example: Wrapping with throw new AggregateException</h4><p>This is particularly useful when working with parallel or asynchronous programming.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Threading.Tasks;<br>class Program<br>{<br>    static async Task Main()<br>    {<br>        try<br>        {<br>            await RunTasks();<br>        }<br>        catch (AggregateException aggEx)<br>        {<br>            Console.WriteLine(&quot;One or more errors occurred:&quot;);<br>            foreach (var ex in aggEx.InnerExceptions)<br>            {<br>                Console.WriteLine($&quot; - {ex.Message}&quot;);<br>            }<br>        }<br>    }<br>    static async Task RunTasks()<br>    {<br>        var tasks = new List&lt;Task&gt;<br>        {<br>            Task.Run(() =&gt; throw new InvalidOperationException(&quot;Task 1 failed&quot;)),<br>            Task.Run(() =&gt; throw new ArgumentException(&quot;Task 2 failed&quot;))<br>        };<br>        try<br>        {<br>            await Task.WhenAll(tasks);<br>        }<br>        catch<br>        {<br>            // Wrap multiple exceptions into an AggregateException<br>            throw new AggregateException(&quot;Errors occurred during task execution&quot;, tasks.Select(t =&gt; t.Exception).Where(e =&gt; e != null));<br>        }<br>    }<br>}</pre><h4>Output:</h4><pre>One or more errors occurred:<br> - Task 1 failed<br> - Task 2 failed</pre><ul><li><strong>Best Practice</strong>: Use AggregateException when working with multiple asynchronous tasks to aggregate and manage exceptions effectively.</li></ul><h3>Preserving Stack Traces with ExceptionDispatchInfo.Throw</h3><p>In advanced scenarios, you might capture an exception for rethrowing later in a different context (e.g., across threads or asynchronous operations). ExceptionDispatchInfo.Throw preserves the original stack trace, even when rethrown in a different context.</p><h4>Code Example: Using ExceptionDispatchInfo.Throw</h4><pre>using System;<br>using System.Runtime.ExceptionServices;<br>using System.Threading.Tasks;<br>class Program<br>{<br>    static async Task Main()<br>    {<br>        try<br>        {<br>            await RunAsyncWithError();<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine($&quot;Caught exception: {ex.Message}&quot;);<br>            Console.WriteLine($&quot;Original stack trace: {ex.StackTrace}&quot;);<br>        }<br>    }<br>    static async Task RunAsyncWithError()<br>    {<br>        ExceptionDispatchInfo capturedException = null;<br>        try<br>        {<br>            await Task.Run(() =&gt; throw new InvalidOperationException(&quot;Error occurred in Task&quot;));<br>        }<br>        catch (Exception ex)<br>        {<br>            capturedException = ExceptionDispatchInfo.Capture(ex); // Capture the exception<br>        }<br>        // Simulate other work<br>        await Task.Delay(1000);<br>        // Rethrow the captured exception<br>        capturedException?.Throw();<br>    }<br>}</pre><h4>Output:</h4><pre>Caught exception: Error occurred in Task<br>Original stack trace: at Program.&lt;RunAsyncWithError&gt;b__0_0()...</pre><ul><li><strong>Best Practice</strong>: Use ExceptionDispatchInfo.Throw for advanced scenarios like asynchronous programming, ensuring the original stack trace is preserved.</li></ul><h3>Final Thoughts/Conclusion</h3><p>Understanding the different ways to handle exceptions in C# is essential for writing robust and maintainable code. Here’s a quick summary:</p><ol><li>Use throw to propagate exceptions while preserving their stack trace.</li><li>Avoid throw ex unless you intentionally need to reset the stack trace.</li><li>Use throw new to wrap exceptions with additional context or to aggregate multiple exceptions.</li><li>Use ExceptionDispatchInfo.Throw for rethrowing exceptions in asynchronous or multi-threaded scenarios while preserving their stack traces.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03a52bb962bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Caching in .NET: When and How to Use Redis, MemoryCache, Memcached, and Hazelcast]]></title>
            <link>https://medium.com/@f.hemmatzadeh/implementing-caching-in-net-when-and-how-to-use-redis-memorycache-memcached-and-hazelcast-3c351b6767a1?source=rss-168638433738------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c351b6767a1</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Farhad Hemmatzadeh]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 09:43:15 GMT</pubDate>
            <atom:updated>2024-11-19T09:43:15.441Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Caching in .NET: When and How to Use Redis, MemoryCache, Memcached, and Hazelcast</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ah8FxRga6-ru79g7JKuzYA.jpeg" /></figure><h3>Introduction</h3><p>Caching plays a critical role in modern .NET applications to improve performance and scalability. Whether your application is a simple monolith or a complex distributed system, choosing the right caching strategy and technology is vital. This article explores <strong>Redis</strong>, <strong>MemoryCache</strong>, <strong>Memcached</strong>, and <strong>Hazelcast</strong>, highlighting when and how to use each.</p><h3>Learning Objectives</h3><p>By the end of this article, you will:</p><ul><li>Understand the importance of caching for performance optimization.</li><li>Learn the differences between in-memory and distributed caching solutions.</li><li>Gain practical knowledge of implementing caching using:</li><li><strong><em>MemoryCache</em></strong></li><li><strong>Redis</strong></li><li><strong>Memcached</strong></li><li><strong>Hazelcast</strong></li><li>Understand use cases and performance considerations for each caching tool.</li></ul><h3>Prerequisites</h3><p>Before proceeding, ensure you have:</p><ul><li>Experience working with <strong>.NET</strong> and <strong>C#</strong>.</li><li>Knowledge of dependency injection and middleware in ASP.NET Core.</li><li>A Redis, Memcached, or Hazelcast server instance (local or cloud-hosted) for testing distributed caching.</li></ul><h3>Getting Started</h3><p>Caching can be categorized into:</p><ol><li><strong>In-Memory Caching</strong>: Local to the application, with no inter-instance sharing.</li><li><strong>Distributed Caching</strong>: Shared across instances, suitable for distributed systems.</li></ol><h3>Sub-Topic 1: Implementing In-Memory Caching with MemoryCache</h3><p>In-memory caching is straightforward to set up and is suitable for applications hosted on a single server.</p><p><strong>Pros</strong>:</p><ol><li>Simple to set up and use.</li><li>Part of the .NET Framework, no additional libraries or services required.</li><li>Fast and efficient for single-server applications.</li><li>Lightweight with minimal overhead.</li></ol><p><strong>Cons</strong>:</p><ol><li>Local to the application, no support for distributed caching.</li><li>Cache data is lost on application restart.</li><li>Limited to the memory of the server hosting the application.</li></ol><h4>Code Examples for In-Memory Caching</h4><pre>using System;<br>using Microsoft.Extensions.Caching.Memory;<br><br>public class ProductService<br>{<br>    private readonly IMemoryCache _cache;<br><br>    public ProductService(IMemoryCache cache)<br>    {<br>        _cache = cache;<br>    }<br><br>    public string GetProductDetails(string productId)<br>    {<br>        if (_cache.TryGetValue(productId, out string productDetails))<br>        {<br>            return productDetails;<br>        }<br><br>        // Simulate fetching product details from a database<br>        productDetails = $&quot;Details of product {productId}&quot;;<br>        _cache.Set(productId, productDetails, TimeSpan.FromMinutes(10));<br><br>        return productDetails;<br>    }<br>}</pre><h3>Sub-Topic 2: Implementing Distributed Caching with Redis</h3><p>Redis provides advanced features like persistence, replication, and support for complex data types, making it a powerful distributed caching solution.</p><p><strong>Pros</strong>:</p><ol><li>Distributed, supports high availability and horizontal scaling.</li><li>Offers advanced data structures (e.g., hash, list, set, sorted set).</li><li>Persistent storage with options for data durability.</li><li>Well-suited for applications requiring caching across multiple instances.</li></ol><p><strong>Cons</strong>:</p><ol><li>Requires a Redis server, adding operational complexity.</li><li>More resource-intensive compared to in-memory solutions.</li><li>Limited support for hierarchical or complex object relationships.</li></ol><h4>Code Examples for Redis Caching</h4><p>Install the Redis NuGet package:</p><pre>dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis</pre><p>Configure Redis in your application:</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Add Redis caching<br>builder.Services.AddStackExchangeRedisCache(options =&gt;<br>{<br>    options.Configuration = &quot;localhost:6379&quot;;<br>    options.InstanceName = &quot;MyApp_&quot;;<br>});<br><br>var app = builder.Build();<br>app.Run();</pre><p>Use Redis caching in a service:</p><pre>using Microsoft.Extensions.Caching.Distributed;<br><br>public class UserService<br>{<br>    private readonly IDistributedCache _cache;<br><br>    public UserService(IDistributedCache cache)<br>    {<br>        _cache = cache;<br>    }<br><br>    public async Task&lt;string&gt; GetUserDetailsAsync(string userId)<br>    {<br>        var cachedData = await _cache.GetStringAsync(userId);<br>        if (cachedData != null)<br>        {<br>            return cachedData;<br>        }<br><br>        // Simulate fetching user data<br>        var userData = $&quot;Details of user {userId}&quot;;<br>        await _cache.SetStringAsync(userId, userData, new DistributedCacheEntryOptions<br>        {<br>            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30)<br>        });<br><br>        return userData;<br>    }<br>}</pre><h4>Output</h4><ul><li>On first call: Stores user details in Redis.</li><li>On subsequent calls: Retrieves data from Redis.</li></ul><h3>Sub-Topic 3: Implementing Distributed Caching with Memcached</h3><p><strong>Memcached</strong> is a lightweight, high-performance distributed caching system. It excels in scenarios where you need a simple key-value store with low overhead.</p><p><strong>Pros</strong>:</p><ol><li>Simple, lightweight, and fast key-value store.</li><li>Excellent for caching small, frequently accessed data.</li><li>Easy to scale horizontally by adding more nodes.</li><li>Efficient memory management with low overhead.</li></ol><p><strong>Cons</strong>:</p><ol><li>No data persistence; cache data is lost on server restart.</li><li>Limited feature set compared to Redis (e.g., lacks advanced data structures).</li><li>Less active community and fewer updates than Redis.</li></ol><h4>Setting Up Memcached</h4><p>Install the NuGet package:</p><pre>dotnet add package EnyimMemcachedCore</pre><p>Configure Memcached:</p><pre>builder.Services.AddEnyimMemcached(options =&gt;<br>{<br>    options.Servers.Add(new Enyim.Caching.Configuration.Server<br>    {<br>        Address = &quot;localhost&quot;,<br>        Port = 11211<br>    });<br>});</pre><p>Use Memcached in your service:</p><pre>using Enyim.Caching;<br><br>public class OrderService<br>{<br>    private readonly IMemcachedClient _memcachedClient;<br><br>    public OrderService(IMemcachedClient memcachedClient)<br>    {<br>        _memcachedClient = memcachedClient;<br>    }<br><br>    public async Task&lt;string&gt; GetOrderDetailsAsync(string orderId)<br>    {<br>        var cachedData = await _memcachedClient.GetAsync&lt;string&gt;(orderId);<br>        if (cachedData != null)<br>        {<br>            return cachedData;<br>        }<br><br>        // Simulate fetching order details<br>        var orderDetails = $&quot;Details of order {orderId}&quot;;<br>        await _memcachedClient.SetAsync(orderId, orderDetails, TimeSpan.FromMinutes(15));<br><br>        return orderDetails;<br>    }<br>}</pre><h4>Output</h4><ul><li>Ideal for lightweight, key-value caching.</li></ul><h3>Sub-Topic 4: Implementing Distributed Caching with Hazelcast</h3><p><strong>Hazelcast</strong> is a distributed in-memory computing platform offering caching with added features like distributed data structures, compute grids, and event streaming.</p><p><strong>Pros</strong>:</p><ol><li>Distributed caching with advanced features like compute grids and event streaming.</li><li>Supports both in-memory and persistent data storage.</li><li>Strong support for distributed data structures and real-time event processing.</li><li>Good integration with Java and .NET ecosystems.</li></ol><p><strong>Cons</strong>:</p><ol><li>More complex to set up and configure compared to Redis or Memcached.</li><li>Higher resource consumption due to its extensive feature set.</li><li>Overkill for simple caching requirements.</li></ol><h4>Setting Up Hazelcast</h4><p>Install the NuGet package:</p><pre>dotnet add package Hazelcast.Net</pre><p>Configure Hazelcast:</p><pre>var options = new HazelcastOptionsBuilder()<br>    .With(args =&gt; args.Networking.Addresses.Add(&quot;127.0.0.1:5701&quot;))<br>    .Build();<br><br>var client = await HazelcastClientFactory.StartNewClientAsync(options);</pre><p>Use Hazelcast in your service:</p><pre>public class SessionService<br>{<br>    private readonly IMap&lt;string, string&gt; _sessionCache;<br><br>    public SessionService(IHazelcastClient client)<br>    {<br>        _sessionCache = client.GetMapAsync&lt;string, string&gt;(&quot;sessionCache&quot;).Result;<br>    }<br><br>    public async Task&lt;string&gt; GetSessionDataAsync(string sessionId)<br>    {<br>        if (await _sessionCache.ContainsKeyAsync(sessionId))<br>        {<br>            return await _sessionCache.GetAsync(sessionId);<br>        }<br><br>        // Simulate fetching session data<br>        var sessionData = $&quot;Data for session {sessionId}&quot;;<br>        await _sessionCache.SetAsync(sessionId, sessionData);<br><br>        return sessionData;<br>    }<br>}</pre><h4>Output</h4><ul><li>Powerful distributed caching with advanced features like compute capabilities and event handling.</li></ul><h3>Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*W3n26gTwNJHzKLNgMUtb0w.png" /></figure><h3>Final Thoughts/Conclusion</h3><p>Choosing the right caching strategy depends on your application’s architecture and requirements:</p><ul><li>Use <strong>MemoryCache</strong> for simple, local caching needs.</li><li>Opt for <strong>Redis</strong> for distributed caching with advanced features.</li><li>Select <strong>Memcached</strong> for lightweight, high-performance distributed caching.</li><li>Leverage <strong>Hazelcast</strong> for caching with additional capabilities like compute grids.</li></ul><p>Proper caching implementation can drastically enhance application performance, reduce database load, and ensure a better user experience.</p><h3>Impressum</h3><p>Written by Farhad Hemmatzadeh, a senior .NET developer specializing in memory management and performance optimization in C# applications. Follow me on <a href="https://www.linkedin.com/in/hemmatzadeh/">LinkedIn </a>or <a href="https://github.com/hemmatzadeh">GitHub </a>for more articles and code samples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c351b6767a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison of Hangfire and Quartz for Background Job Scheduling in .NET]]></title>
            <link>https://medium.com/@f.hemmatzadeh/comparison-of-hangfire-and-quartz-for-background-job-scheduling-in-net-fe876ae4aa4f?source=rss-168638433738------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe876ae4aa4f</guid>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Farhad Hemmatzadeh]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 11:07:50 GMT</pubDate>
            <atom:updated>2024-11-12T11:07:50.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparison of Hangfire and Quartz for Background Job Scheduling in .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*PAmQd3qs-K6KYtneVdW_gg.jpeg" /></figure><p>As a .NET developer, choosing between <strong>Hangfire</strong> and <strong>Quartz.NET</strong> for job scheduling can be crucial for application performance, maintainability, and scalability. Both libraries are powerful, widely-used job scheduling tools, but they serve slightly different use cases and offer unique advantages.</p><p><strong>Hangfire Overview</strong></p><p><strong>Hangfire</strong> is a library primarily designed for background job processing. It integrates seamlessly with .NET applications, allowing developers to schedule jobs easily without the need for complex configurations. Hangfire stores job details in a persistent storage (such as SQL Server, Redis, or MongoDB), which ensures that jobs can be retried and processed even if the application restarts.</p><h4>Pros</h4><ul><li><strong>Easy Setup</strong>: Minimal configuration and user-friendly, allowing jobs to be scheduled with simple method calls.</li><li><strong>Built-In Dashboard</strong>: Provides a detailed dashboard to monitor job execution, retries, success, and failure rates.</li><li><strong>Automatic Retry Mechanism</strong>: Automatically retries failed jobs, which makes it robust for high-availability applications.</li><li><strong>Supports Long-Running Jobs</strong>: Excellent for handling jobs that may need to run over long periods without interference.</li><li><strong>Scalable</strong>: Supports job processing across multiple servers, which makes it ideal for load balancing.</li></ul><h4>Cons</h4><ul><li><strong>Dependent on Persistent Storage</strong>: It requires a database (SQL Server, Redis, etc.) for job storage, which can introduce additional costs and complexity.</li><li><strong>Limited Scheduling Options</strong>: Hangfire’s scheduling functionality is relatively simple compared to Quartz, especially for complex recurrence patterns.</li><li><strong>Limited Fine-Tuning for Resource Management</strong>: Doesn’t offer as many options as Quartz for fine-grained control over thread pools and resource allocation.</li></ul><h4>When to Use Hangfire</h4><ul><li><strong>Microservices and Web Applications</strong>: Hangfire is ideal for applications where jobs need to be scheduled in real time with high reliability, such as sending emails or processing data after a web request.</li><li><strong>Simple Job Requirements</strong>: When the scheduling requirements are straightforward, like daily tasks or tasks triggered based on application events.</li><li><strong>Long-Running Background Jobs</strong>: Suitable for handling time-consuming tasks such as generating reports or processing large datasets that can run independently of the main application.</li></ul><h4>Real-World Example with Hangfire</h4><p>Imagine an eCommerce application where emails are sent to users for various actions, like order confirmations or weekly promotions. With Hangfire, you could schedule a job like this:</p><pre>public class EmailService<br>{<br>    public void SendOrderConfirmationEmail(int orderId)<br>    {<br>        // Code to send email<br>    }<br>}<br><br>// Enqueue a one-time job<br>BackgroundJob.Enqueue(() =&gt; emailService.SendOrderConfirmationEmail(orderId));<br><br>// Schedule a recurring weekly promotional email<br>RecurringJob.AddOrUpdate(&quot;WeeklyPromo&quot;, <br>    () =&gt; emailService.SendPromotionalEmail(), Cron.Weekly);</pre><p>Hangfire will handle retries, persist job data, and offer a dashboard to monitor job completion.</p><h3>Quartz.NET Overview</h3><p><strong>Quartz.NET</strong> is a full-featured, open-source job scheduling library that provides more advanced scheduling options. It supports complex job configurations and offers more flexibility than Hangfire, especially for applications with intricate scheduling needs.</p><h4>Pros</h4><ul><li><strong>Flexible Scheduling</strong>: Offers cron expressions and a rich API for defining complex recurrence rules.</li><li><strong>Fine-Grained Control</strong>: Provides in-depth control over resource allocation, with options to manage thread pools, job priorities, and misfire handling.</li><li><strong>Clustered Setup</strong>: Quartz can be run in a clustered environment, ensuring jobs run once across multiple instances.</li><li><strong>Supports Distributed Jobs</strong>: Suitable for applications that need to schedule jobs across distributed systems.</li></ul><h4>Cons</h4><ul><li><strong>Steeper Learning Curve</strong>: More complex configuration compared to Hangfire, which can be challenging for developers new to job scheduling.</li><li><strong>Limited Monitoring</strong>: Quartz does not include a built-in dashboard for job monitoring, requiring custom development or third-party tools.</li><li><strong>Complex Configurations for Simple Jobs</strong>: May be overkill for applications that only need basic scheduling or background job processing.</li></ul><h4>When to Use Quartz.NET</h4><ul><li><strong>Complex Scheduling Needs</strong>: When your application needs to support intricate or custom scheduling patterns, such as multiple jobs with dependencies or advanced cron expressions.</li><li><strong>Enterprise-Grade Applications</strong>: Suitable for systems that require job execution control over multiple instances or applications that need to balance resource allocation finely.</li><li><strong>Distributed Systems</strong>: Ideal for large-scale systems that need a clustered setup to ensure high availability.</li></ul><h4>Real-World Example with Quartz.NET</h4><p>Consider a finance application where certain calculations need to run at end-of-month or quarterly, requiring complex scheduling rules. With Quartz.NET, you could configure such a job as follows:</p><pre>IJobDetail job = JobBuilder.Create&lt;EndOfMonthCalculationJob&gt;()<br>    .WithIdentity(&quot;EndOfMonthJob&quot;)<br>    .Build();<br><br>ITrigger trigger = TriggerBuilder.Create()<br>    .WithIdentity(&quot;EndOfMonthTrigger&quot;)<br>    .StartNow()<br>    .WithCronSchedule(&quot;0 0 0 L * ?&quot;) // Last day of the month at midnight<br>    .Build();<br><br>IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;<br>scheduler.ScheduleJob(job, trigger);<br>scheduler.Start();</pre><p>This code schedules a job to execute on the last day of each month at midnight, a complex recurrence pattern that Quartz can handle effectively.</p><h3>Side-by-Side Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*V6RwMi04sU4XDG8mosJnqA.png" /></figure><h3>Conclusion: Choosing Between Hangfire and Quartz.NET</h3><ul><li><strong>Choose Hangfire</strong> if your application needs easy-to-set-up, reliable background job processing with basic scheduling requirements and robust monitoring. Hangfire is well-suited for web applications, microservices, and applications where background jobs are lightweight and do not require complex scheduling patterns.</li><li><strong>Choose Quartz.NET</strong> for applications requiring complex job scheduling, advanced resource management, and fine-grained control over job execution. Quartz.NET is a good choice for enterprise-grade applications and systems that need high availability and precision in job execution.</li></ul><p><strong>In Summary:</strong> Hangfire is best for simplicity and basic job scheduling, whereas Quartz.NET is more powerful for complex and enterprise-level job scheduling needs.</p><h3>Impressum</h3><p>Written by Farhad Hemmatzadeh, a senior .NET developer specializing in memory management and performance optimization in C# applications. Follow me on <a href="https://www.linkedin.com/in/hemmatzadeh/">LinkedIn </a>or <a href="https://github.com/hemmatzadeh">GitHub </a>for more articles and code samples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe876ae4aa4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ETag: The Secret to Faster, More Efficient Web Requests]]></title>
            <link>https://medium.com/@f.hemmatzadeh/etag-the-secret-to-faster-more-efficient-web-requests-d504889933b7?source=rss-168638433738------2</link>
            <guid isPermaLink="false">https://medium.com/p/d504889933b7</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Farhad Hemmatzadeh]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 16:47:30 GMT</pubDate>
            <atom:updated>2023-02-22T16:51:19.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCnFluecJYRkw1tGPZ1L3Q.jpeg" /></figure><p>In the world of web applications, it’s important to ensure that users are able to access the latest version of resources such as web pages, images, or data. However, constantly fetching these resources from the server can be a costly and time-consuming process, especially if the resources are large in size or if the user’s network connection is slow.</p><p>To address this issue, web developers have long relied on caching mechanisms that allow web browsers to store a copy of the resource locally so that it can be accessed more quickly in the future. However, caching introduces a new challenge: how can the browser know when a resource has been updated on the server and needs to be fetched again?</p><p>This is where Etag comes in. An Etag, short for “entity tag”, is a mechanism in the HTTP protocol that allows web servers to assign a unique identifier to each version of a resource. When a client, such as a web browser, requests a resource from the server, the server includes the Etag value in the response header. The client then stores this value locally and uses it as a reference in future requests for the same resource.</p><p>When the client makes a subsequent request for the resource, it includes the Etag value in the request header. If the resource on the server has not changed since the client last accessed it, the server simply responds with a “304 Not Modified” status code and no content, indicating that the client can use its locally cached copy of the resource. If the resource has been updated on the server, the server responds with a new version of the resource along with a new Etag value.</p><p>The use of Etag has several benefits for web applications. Firstly, it helps reduce network traffic by allowing clients to use cached versions of resources when they are still up to date. This can significantly improve the performance of web applications, especially for users with slower network connections. Secondly, it allows web servers to optimize their resource delivery by only sending new versions of resources when they are needed, rather than forcing clients to download the entire resource every time. Finally, it ensures that clients always have access to the latest version of a resource, even if they are using a cached version.</p><p>In the context of MVC Core 6 or 7, Etag implementation can be done through custom middleware or by using built-in features such as the Microsoft.AspNetCore.ResponseCaching middleware. Developers can configure their web applications to include Etag values in response headers for selected resources, such as static files or dynamically generated content. They can also customize the behavior of Etag caching by setting expiration times, setting validation methods, or configuring cache dependencies.</p><p>In conclusion, Etag is a powerful mechanism for improving the performance and reliability of web applications by allowing clients to cache resources and efficiently retrieve updated versions when needed. Its implementation in MVC Core 6 or 7 can be a valuable tool for developers to optimize their web applications and provide a better user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*flzJhgSPER9E5kSYmR-Tig.png" /></figure><blockquote>Suppose you are developing an e-commerce website that sells various products to customers. Each product has a details page that displays its name, description, price, and images. You want to ensure that the page loads quickly and efficiently for customers, especially those with slower network connections.</blockquote><blockquote>To achieve this goal, you decide to implement Etag caching for the product details pages. Whenever a customer requests a product details page, the server includes an Etag value in the response header that uniquely identifies the current version of the page. The customer’s web browser stores this value locally and includes it in future requests for the same page.</blockquote><blockquote>If the customer revisits the same product details page at a later time, the browser sends a request to the server that includes the stored Etag value. The server checks the Etag value against the current version of the page. If the page has not changed since the last request, the server sends a “304 Not Modified” response along with the stored Etag value, indicating that the customer can use their locally cached version of the page. This saves time and network bandwidth by avoiding unnecessary data transfers.</blockquote><blockquote>However, if the page has been updated since the last request, the server sends a new version of the page along with a new Etag value. The customer’s browser stores this new Etag value for future requests, ensuring that they always have access to the latest version of the page.</blockquote><blockquote>This implementation of Etag caching allows your e-commerce website to load product details pages quickly and efficiently, while still ensuring that customers always have access to the latest information. It also reduces the load on your web server, as it only needs to send new versions of the page when they have changed.</blockquote><blockquote>In addition, Etag caching can help mitigate some common problems with web caching, such as stale content or inconsistent behavior across different browsers or devices. By uniquely identifying each version of a resource with an Etag value, you can ensure that cached versions are always up-to-date and consistent across different clients.</blockquote><blockquote>Overall, the use of Etag caching is a powerful technique for improving the performance and reliability of web applications, particularly in scenarios where resources are frequently updated or accessed by multiple clients.</blockquote><h3><strong>Benefits of using ETag in web applications</strong></h3><p>There are several benefits of using ETag in web applications, including improved performance, reduced network bandwidth usage, and improved cache validation.</p><p>One of the main benefits of using ETag is improved performance. By using ETag, web servers can detect when a client’s cached version of a resource is still up-to-date with the latest version on the server, and respond with a 304 Not Modified status code. This allows clients to use their cached version of the resource, reducing the amount of data that needs to be transferred over the network and improving the overall performance of the web application.</p><p>Another benefit of using ETag is reduced network bandwidth usage. When a web server responds with a 304 Not Modified status code, it does not include a response body, which means that no additional data needs to be transferred over the network. This can be particularly beneficial in cases where the client is accessing the web application over a slow or limited bandwidth network connection.</p><p>ETag can also improve cache validation in web applications. By using ETag, web servers can ensure that clients are using the most up-to-date version of a resource, even if the resource has been modified in a subtle way, such as a change to a single character in a large text file. This can help prevent issues where clients are using outdated or stale versions of resources, improving the overall reliability and accuracy of the web application.</p><p>In addition, ETag can be used as a means of concurrency control. When a client makes a PUT or POST request to update a resource, it can include an If-Match header in the request that contains the ETag value of the current version of the resource. The server will only update the resource if the ETag values match, ensuring that the client is working with the latest version of the resource. This can help prevent conflicting updates to resources, improving the overall consistency and reliability of the web application.</p><p>Overall, using ETag in web applications can provide a range of benefits, from improved performance and reduced network bandwidth usage to improved cache validation and concurrency control. Developers can use the built-in Response Caching middleware or custom middleware to implement ETag caching in their ASP.NET Core 6 or 7 applications, providing a fast and efficient experience for their users while also improving the reliability and accuracy of their web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*-DZaKoth19tVtL_oKKkoOw.jpeg" /></figure><h3>Pros:</h3><ol><li><strong>Improved Performance:</strong> ETag allows web servers to validate cached resources, which can significantly reduce the amount of data that needs to be transferred over the network. This can result in faster page load times and improved overall performance.</li><li><strong>Reduced Network Bandwidth Usage:</strong> By using ETag, web servers can respond with a 304 Not Modified status code, which means that no additional data needs to be transferred over the network. This can be particularly beneficial in cases where the client is accessing the web application over a slow or limited bandwidth network connection.</li><li><strong>Improved Cache Validation:</strong> ETag can help ensure that clients are using the most up-to-date version of a resource, improving the overall reliability and accuracy of the web application.</li><li><strong>Concurrency Control:</strong> ETag can be used as a means of concurrency control, preventing conflicting updates to resources and improving the overall consistency and reliability of the web application.</li></ol><h3>Cons:</h3><ol><li><strong>Increased Overhead:</strong> ETag adds additional overhead to requests and responses, which can impact performance and increase the amount of data that needs to be transferred over the network.</li><li><strong>Complexity:</strong> Implementing ETag can be complex, particularly in cases where resources are modified frequently or where multiple servers are involved.</li><li><strong>Server-Side Overhead:</strong> ETag requires additional processing on the server side, which can impact server performance and scalability.</li><li><strong>Caching Issues:</strong> ETag caching can sometimes result in issues where clients are using outdated or stale versions of resources, particularly in cases where the ETag is based on the last modified time of the resource.</li></ol><p><em>👉🏽 I will explain how to use Etag in mvc core web API in the next post</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d504889933b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>