<?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 Merwan Chinta on Medium]]></title>
        <description><![CDATA[Stories by Merwan Chinta on Medium]]></description>
        <link>https://medium.com/@merwan01?source=rss-d5b5bfb7eae7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1Gv5GLU1jxqmZYzQF7tBkw.jpeg</url>
            <title>Stories by Merwan Chinta on Medium</title>
            <link>https://medium.com/@merwan01?source=rss-d5b5bfb7eae7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:28:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@merwan01/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[Simplifying Business Logic with Transaction Scripts]]></title>
            <link>https://medium.com/codenx/simplifying-business-logic-with-transaction-scripts-6cf0c3aa024f?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cf0c3aa024f</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 14:15:11 GMT</pubDate>
            <atom:updated>2024-10-13T14:15:11.600Z</atom:updated>
            <content:encoded><![CDATA[<p>Organizing business logic can be approached in different ways, depending on the complexity of the operation. One of the most straightforward methods is using a <strong>Transaction Script</strong>.</p><p>Transaction Scripts are simple, procedural-based patterns, particularly effective for operations that don’t require the overhead of a complex domain model.</p><p>In this article, we’ll dive into the basics of Transaction Scripts and walk through a unique example to help you understand how and when to use them.</p><h3>What is a Transaction Script?</h3><p>A <strong>Transaction Script</strong> is a pattern where you organize your business logic as a series of scripts, each handling a particular transaction or use case. These scripts directly interact with the database and perform the necessary operations. Because they follow a step-by-step approach, Transaction Scripts are ideal for small, simple use cases that don’t require complex validations or intricate workflows.</p><p>However, as your application grows and the logic becomes more complex, you might want to shift toward a more structured pattern like <strong>Domain-Driven Design (DDD)</strong>, which separates the business logic from the database interactions.</p><h3>Use Case: Processing a Library Book Loan</h3><p>Imagine we are building a library management system, and we need to process a book loan. Here’s the scenario:</p><ol><li>A user checks out a book.</li><li>The system updates the availability of the book.</li><li>The user’s borrowing history is updated with the new loan information.</li></ol><p>We’ll implement this use case using a <strong>Transaction Script</strong>, where we handle the entire process within a single function. Let’s look at how this can be structured.</p><h3>Example</h3><pre>public void ProcessBookLoan(int bookId, int userId)<br>{<br>    using var connection = new SqlConnection(_connectionString);<br>    connection.Open();<br><br>    using var transaction = connection.BeginTransaction();<br><br>    try<br>    {<br>        // Mark the book as loaned in the Books table<br>        using var updateBookCommand = new SqlCommand(<br>            @&quot;UPDATE Books SET Availability = &#39;Loaned&#39; WHERE BookId = @BookId&quot;, <br>            connection, <br>            transaction);<br>        updateBookCommand.Parameters.AddWithValue(&quot;@BookId&quot;, bookId);<br>        updateBookCommand.ExecuteNonQuery();<br><br>        // Record the book loan in the BorrowingHistory table<br>        using var insertHistoryCommand = new SqlCommand(<br>            @&quot;INSERT INTO BorrowingHistory (UserId, BookId, LoanDate) <br>              VALUES (@UserId, @BookId, @LoanDate)&quot;, <br>            connection, <br>            transaction);<br>        insertHistoryCommand.Parameters.AddWithValue(&quot;@UserId&quot;, userId);<br>        insertHistoryCommand.Parameters.AddWithValue(&quot;@BookId&quot;, bookId);<br>        insertHistoryCommand.Parameters.AddWithValue(&quot;@LoanDate&quot;, DateTime.Now);<br>        insertHistoryCommand.ExecuteNonQuery();<br><br>        // Commit the transaction<br>        transaction.Commit();<br>    }<br>    catch (Exception)<br>    {<br>        // Rollback the transaction if an error occurs<br>        transaction.Rollback();<br>        throw;<br>    }<br>}</pre><p>The ProcessBookLoan method opens a database connection, starts a transaction, marks the specified book as loaned, records the loan in the user’s borrowing history, commits the transaction if successful, and rolls back the transaction in case of any failure to maintain data consistency.</p><h3>Why Use Transaction Scripts?</h3><ul><li><strong>Simplicity</strong>: Transaction Scripts are easy to write and understand. Each script handles a specific use case and performs the necessary steps in a procedural fashion.</li><li><strong>Low Overhead</strong>: For simple operations, this approach avoids the complexity of designing a full domain model.</li><li><strong>Quick Implementation</strong>: In situations where the business logic is straightforward and won’t change much, Transaction Scripts are a great way to get things done quickly.</li></ul><h3>When to Move Beyond Transaction Scripts</h3><p>While Transaction Scripts are efficient for simple use cases, they might not be the best option for more complex applications. As the logic grows, you’ll find that you are duplicating a lot of code, and maintenance can become cumbersome. At this point, it’s worth considering more structured patterns, such as:</p><ul><li><strong>Domain-Driven Design (DDD)</strong>: Separates the business logic into layers and uses entities, aggregates, and repositories for managing data and operations.</li><li><strong>CQRS (Command Query Responsibility Segregation)</strong>: Separates read and write operations into different models to better handle complex scenarios.</li></ul><h3>Summary</h3><p>Transaction Scripts are easy to write and understand, making them ideal for simple tasks, but they may become harder to maintain as the complexity of the business logic grows.</p><p>I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!</p><p>📚 For more insights like these, feel free to follow 👉 <a href="https://medium.com/@merwan01"><strong>Merwan Chinta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cf0c3aa024f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codenx/simplifying-business-logic-with-transaction-scripts-6cf0c3aa024f">Simplifying Business Logic with Transaction Scripts</a> was originally published in <a href="https://medium.com/codenx">CodeNx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Design Software Architecture]]></title>
            <link>https://medium.com/codenx/how-to-design-software-architecture-cff0656722f2?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cff0656722f2</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 12:24:18 GMT</pubDate>
            <atom:updated>2024-10-08T12:24:18.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Software architecture is the blueprint that defines how a system’s components interact with each other. It’s crucial to design an architecture that supports flexibility, adaptability, and ease of maintenance.</p><p>This article will explore a design approach to software architecture that allows for easy feature additions, unit testing, and the inclusion of feature toggles.</p><h4>1. Start with Understanding Requirements</h4><p>Before designing the architecture, deeply analyze the system requirements:</p><ul><li>What problem is the system solving?</li><li>Who are the users, and what are their expectations?</li><li>Will the system evolve, or is it a one-time solution?</li></ul><p><strong>Consideration:</strong> Flexibility is key. Requirements may change, so ensure that the design can adapt to future needs without major rework.</p><h4>2. Design for Modularity and Separation of Concerns</h4><p>Modularity ensures that each component of the system has a single responsibility.</p><p>Use patterns like <strong>Domain-Driven Design (DDD)</strong> and <strong>Hexagonal Architecture</strong> to maintain clear boundaries between application logic, infrastructure, and interfaces.</p><p><strong>Why It Matters:</strong> Separation of concerns makes unit testing easier since components are isolated. This also supports the <strong>Single Responsibility Principle</strong> (SRP) from SOLID.</p><h4>3. Adaptability through Layered Architecture</h4><p>A layered architecture allows for evolving technologies or business rules. For example:</p><ul><li><strong>Presentation Layer</strong>: Responsible for the user interface.</li><li><strong>Business Layer</strong>: Handles business logic.</li><li><strong>Data Access Layer</strong>: Deals with data storage and retrieval.</li></ul><h4>4. Flexibility in Adding New Features</h4><p>The system should support feature additions without breaking existing functionality:</p><ul><li><strong>Interface Segregation</strong>: Avoid bloated interfaces.</li><li><strong>Open/Closed Principle (OCP)</strong>: Design components that are open for extension but closed for modification.</li></ul><p><strong>Tip:</strong> Use feature flags or toggles to introduce new features gradually without affecting the system.</p><h4>5. Feature Toggles and Switches</h4><p>Feature toggles allow you to enable or disable features without deploying new code. This supports <strong>Continuous Delivery</strong> by allowing features to be tested and rolled out incrementally.</p><p><strong>How to Implement</strong>: Use a toggle framework or custom logic in your application. A database table can store feature toggle statuses, which are then used to conditionally activate code.</p><pre>if (FeatureToggle.IsEnabled(&quot;NewFeature&quot;)) {<br>   // New feature logic here<br>}</pre><h4>6. Unit Testing and Testability as a Core Design Principle</h4><p>Architecture should allow for easy unit testing. Design components with testability in mind:</p><ul><li><strong>Dependency Injection (DI)</strong>: Decouple classes by injecting dependencies.</li><li><strong>Mocking</strong>: Use mocks for external dependencies (e.g., databases, APIs) to isolate the functionality.</li><li><strong>Inversion of Control (IoC)</strong>: Let the framework manage dependencies.</li></ul><h4>7. Design for Scalability and Maintainability</h4><p>Scalability is often an afterthought but should be a priority in the initial design:</p><ul><li><strong>Event-Driven Architecture</strong>: Use messaging systems (e.g., RabbitMQ, Kafka) for decoupled services.</li><li><strong>Microservices</strong>: Break down the monolith if the system needs to scale.</li></ul><p><strong>Maintainability</strong>: Keep the codebase clean and well-structured. Use practices like <strong>Clean Code</strong> and <strong>Continuous Integration/Continuous Deployment (CI/CD)</strong> to ensure quality.</p><h4>8. Versioning and Backward Compatibility</h4><p>As the system grows, older versions of features or APIs may still be in use. Consider versioning APIs to avoid breaking changes for users relying on older functionality.</p><p><strong>Example API Versioning:</strong></p><pre>[ApiVersion(&quot;1.0&quot;)]<br>[Route(&quot;api/v{version:apiVersion}/[controller]&quot;)]<br>public class MyController : ControllerBase { }</pre><h4>9. Future-Proofing with Feature Toggles and Extension Points</h4><p>As new business requirements arise, you’ll need to extend the system. Instead of tightly coupling components, design them with <strong>extension points</strong> (e.g., Strategy Pattern, Factory Pattern) where new logic can be injected.</p><p><strong>Strategy Pattern</strong>:</p><p><a href="https://medium.com/codenx/strategy-pattern-net-c-ea0d122f60c4">https://medium.com/codenx/strategy-pattern-net-c-ea0d122f60c4</a></p><h4>10. Monitoring and Observability</h4><p>Build in monitoring and logging from day one. This helps with debugging and provides insight into system health and performance.</p><ul><li><strong>Logging</strong>: Use logging frameworks (e.g., Serilog, NLog) to track important events.</li><li><strong>Metrics</strong>: Tools like Prometheus can help track system performance.</li></ul><p>Designing a flexible and adaptable architecture from the start ensures smooth growth and easy maintenance of your system. By keeping modularity, testing, scalability, and feature toggles in mind, you build a robust system that can easily adapt to changing business needs and technologies.</p><p>I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!</p><p>📚 For more insights like these, feel free to follow 👉 <a href="https://medium.com/@merwan01"><strong>Merwan Chinta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cff0656722f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codenx/how-to-design-software-architecture-cff0656722f2">How to Design Software Architecture</a> was originally published in <a href="https://medium.com/codenx">CodeNx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET 9: Task.WhenEach and Prioritized Channels]]></title>
            <link>https://medium.com/codenx/net-9-task-wheneach-and-prioritized-channels-36b28bc2e2e0?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/36b28bc2e2e0</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 13:53:26 GMT</pubDate>
            <atom:updated>2024-09-27T13:53:26.613Z</atom:updated>
            <content:encoded><![CDATA[<p>.NET 9 introduces several new threading features that streamline the way developers work with asynchronous tasks and channels. In this article, we’ll explore the new Task.WhenEach API and the addition of prioritized unbounded channels, with code examples to demonstrate their use.</p><h3>Task.WhenEach: Simplifying Task Iteration</h3><p>One of the most useful additions is the Task.WhenEach API. Previously, iterating through tasks as they completed required complex patterns, like calling Task.WaitAny to retrieve the next finished task.</p><p>With Task.WhenEach, you can iterate through tasks as they complete using an await foreach loop, simplifying task management significantly.</p><p>Let’s take a look at how this API works in a real-world scenario where we make asynchronous I/O calls.</p><pre>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static async Task Main(string[] args)<br>    {<br>        using HttpClient httpClient = new HttpClient();<br>        <br>        // Example URLs to fetch data from<br>        Task&lt;string&gt; firstTask = httpClient.GetStringAsync(&quot;https://api.github.com&quot;);<br>        Task&lt;string&gt; secondTask = httpClient.GetStringAsync(&quot;https://jsonplaceholder.typicode.com/posts/1&quot;);<br>        Task&lt;string&gt; thirdTask = httpClient.GetStringAsync(&quot;https://jsonplaceholder.typicode.com/posts/2&quot;);<br><br>        // Use Task.WhenEach to process tasks as they complete<br>        await foreach (Task&lt;string&gt; completedTask in Task.WhenEach(firstTask, secondTask, thirdTask))<br>        {<br>            try<br>            {<br>                Console.WriteLine($&quot;Response Length: {completedTask.Result.Length}&quot;);<br>            }<br>            catch (Exception ex)<br>            {<br>                Console.WriteLine($&quot;Task encountered an error: {ex.Message}&quot;);<br>            }<br>        }<br>    }<br>}</pre><ul><li>Three asynchronous tasks make HTTP requests to different URLs.</li><li>The await foreach loop allows us to process each task as it completes, without needing to wait for all tasks to finish.</li><li>Each task’s result is handled immediately, allowing for more responsive and efficient task processing, especially in I/O-bound operations.</li></ul><p>This new API is ideal for scenarios where you need to perform actions on the results of tasks as soon as they become available, without having to wait for all tasks to finish.</p><h3>Prioritized Unbounded Channels</h3><p>In .NET, a <strong>channel</strong> is a data structure used for communication between different parts of a program. It’s often used in scenarios where you have multiple producers (that add data) and consumers (that process data). Channels work similarly to queues, but they provide more control over how data is processed, especially in concurrent or multi-threaded environments.</p><p>A channel allows for safe, thread-friendly communication between different tasks. The two main types of channels are:</p><ol><li><strong>Bounded channels</strong>: They have a limit on how many items can be stored.</li><li><strong>Unbounded channels</strong>: They can store an unlimited number of items.</li></ol><p>By default, channels process items in the order they are added (FIFO). However, with the introduction of <strong>prioritized channels</strong> in .NET 9, you can now process items based on priority, not just the order in which they were added.</p><p>Here’s a breakdown of how the prioritized channel works:</p><pre>using System;<br>using System.Threading.Channels;<br>using System.Threading.Tasks;<br>using System.Collections.Generic;<br><br>class Program<br>{<br>    static async Task Main(string[] args)<br>    {<br>        // Create a channel that prioritizes smaller numbers (lower numbers processed first)<br>        Channel&lt;int&gt; priorityChannel = Channel.CreateUnboundedPrioritized&lt;int&gt;(Comparer&lt;int&gt;.Create((x, y) =&gt; x.CompareTo(y)));<br><br>        // Add numbers in random order<br>        await priorityChannel.Writer.WriteAsync(10);<br>        await priorityChannel.Writer.WriteAsync(3);<br>        await priorityChannel.Writer.WriteAsync(7);<br><br>        // Complete the writer so no more data is written<br>        priorityChannel.Writer.Complete();<br><br>        // Read items from the channel in prioritized order (smallest to largest)<br>        while (await priorityChannel.Reader.WaitToReadAsync())<br>        {<br>            while (priorityChannel.Reader.TryRead(out int item))<br>            {<br>                Console.WriteLine($&quot;Processed item: {item}&quot;);<br>            }<br>        }<br>    }<br>}</pre><ul><li><strong>Channel Creation</strong>: The channel is created using Channel.CreateUnboundedPrioritized&lt;int&gt;() which sets up a prioritized channel. The custom comparer (x, y) =&gt; x.CompareTo(y) ensures that smaller numbers are treated as having higher priority.</li><li><strong>Writing to the Channel</strong>: Three numbers (10, 3, and 7) are added to the channel. They are added in a random order.</li><li><strong>Completing the Writer</strong>: The call to priorityChannel.Writer.Complete() signifies that no more items will be written to the channel.</li><li><strong>Reading from the Channel</strong>: The code waits for the reader to detect available data using WaitToReadAsync().</li></ul><p>As the items are read from the channel, the smaller number (3) is processed first, followed by 7, and finally 10.</p><h4>Why Use Prioritized Channels?</h4><ul><li><strong>Task Prioritization</strong>: In certain applications, you may want to process higher priority tasks before others (for example, real-time systems, or task scheduling where critical operations should be completed first).</li><li><strong>Control Over Execution</strong>: Unlike traditional FIFO channels, prioritized channels let you define how tasks or data should be processed based on importance rather than timing.</li></ul><p>These new features can be particularly useful in scenarios requiring efficient task management and dynamic element processing, allowing to write more flexible and performant code.</p><p>I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!</p><p>📚 For more insights like these, feel free to follow 👉 <a href="https://medium.com/@merwan01"><strong>Merwan Chinta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36b28bc2e2e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codenx/net-9-task-wheneach-and-prioritized-channels-36b28bc2e2e0">.NET 9: Task.WhenEach and Prioritized Channels</a> was originally published in <a href="https://medium.com/codenx">CodeNx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript’s Event Loop and Microtasks]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">JavaScript is a single-threaded, non-blocking, asynchronous language. At the heart of this architecture lies the event loop, which handles&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/codenx/javascripts-event-loop-and-microtasks-f6f1ccf36901?source=rss-d5b5bfb7eae7------2">Continue reading on CodeNx »</a></p></div>]]></description>
            <link>https://medium.com/codenx/javascripts-event-loop-and-microtasks-f6f1ccf36901?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f1ccf36901</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 14:48:52 GMT</pubDate>
            <atom:updated>2024-09-13T14:48:52.196Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Outbox Pattern in Distributed Systems]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">In modern distributed systems, ensuring consistent event delivery across multiple services is crucial. A common challenge arises when data&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/codenx/outbox-pattern-in-distributed-systems-eb433c035794?source=rss-d5b5bfb7eae7------2">Continue reading on CodeNx »</a></p></div>]]></description>
            <link>https://medium.com/codenx/outbox-pattern-in-distributed-systems-eb433c035794?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb433c035794</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 14:09:50 GMT</pubDate>
            <atom:updated>2024-09-13T14:55:26.613Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core with Live Loading of appsettings]]></title>
            <link>https://medium.com/codenx/real-time-configuration-updates-in-asp-net-core-with-live-loading-of-appsettings-json-d63eac388d28?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d63eac388d28</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 16:27:21 GMT</pubDate>
            <atom:updated>2024-08-29T17:55:23.339Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Introduction</strong></h4><p>In .NET applications, managing configurations is a crucial aspect of maintaining flexibility and adaptability. Traditionally, any change to the configuration file, such as appsettings.json, required an application restart to reflect those changes.</p><p>However, with the introduction of the IOptionsMonitor interface in the Microsoft.Extensions.Options namespace, this limitation is no longer an issue.</p><p>This article explores how you can leverage the live loading feature of appsettings.json without restarting your application, making your development process more efficient and responsive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gxW7sdWmqJZWF5qQ.png" /></figure><h3><strong>Understanding IOptionsMonitor</strong></h3><p>The IOptionsMonitor interface is part of the Microsoft.Extensions.Options namespace and is designed to provide real-time updates to your configuration values. This means that when a configuration file like appsettings.json is modified, the changes are automatically picked up by the application, eliminating the need for a restart.</p><h3><strong>Implementing IOptionsMonitor in a Controller</strong></h3><p>Let’s explore a practical example of using IOptionsMonitor in a .NET controller.</p><p>Below is a basic implementation within an ASP.NET Core application, where you manage feature flags for enabling or disabling features dynamically:</p><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class FeatureToggleController : ControllerBase<br>{<br>    private readonly IOptionsMonitor&lt;FeatureToggleSettings&gt; _featureToggleMonitor;<br><br>    public FeatureToggleController(IOptionsMonitor&lt;FeatureToggleSettings&gt; featureToggleMonitor)<br>    {<br>        _featureToggleMonitor = featureToggleMonitor;<br>    }<br><br>    [HttpGet(&quot;isFeatureXEnabled&quot;)]<br>    public bool IsFeatureXEnabled()<br>    {<br>        return _featureToggleMonitor.CurrentValue.IsFeatureXEnabled;<br>    }<br>}</pre><p><strong>Constructor Injection</strong>: The IOptionsMonitor&lt;FeatureToggleSettings&gt; is injected into the FeatureToggleController. This interface monitors the FeatureToggleSettings class, which binds to the relevant section in appsettings.json.</p><p><strong>Dynamic Feature Management:</strong> The IsFeatureXEnabled() method checks if a specific feature (Feature X) is enabled or disabled based on the current configuration value. The IOptionsMonitor ensures that any changes to appsettings.json are reflected immediately without needing to restart the application.</p><h3><strong>Configuring appsettings.json for Feature Toggles</strong></h3><p>To enable live configuration updates for feature toggles, set up your appsettings.json as follows:</p><pre>{<br>  &quot;FeatureToggleSettings&quot;: {<br>    &quot;IsFeatureXEnabled&quot;: true,<br>    &quot;IsFeatureYEnabled&quot;: false<br>  }<br>}</pre><h3><strong>Binding Configuration in Startup.cs</strong></h3><p>Ensure that your feature toggle settings are correctly bound in the Startup.cs or Program.cs file:</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.Configure&lt;FeatureToggleSettings&gt;(Configuration.GetSection(&quot;FeatureToggleSettings&quot;));<br>    services.AddControllers();<br>}</pre><h3><strong>Use Cases for Live Loading Feature Toggles</strong></h3><p><strong>A/B Testing:</strong> Enable or disable features on the fly to test their impact on user behavior.</p><p><strong>Gradual Rollout:</strong> Gradually enable features for specific user groups without needing to redeploy your application.</p><p><strong>Feature Management in Production:</strong> Quickly respond to issues by toggling features off in production without causing downtime.</p><p>Have you tried using IOptionsMonitor for managing feature toggles or other dynamic settings in your applications? Share your insights and experiences in the comments below!</p><p>I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!</p><p>📚 For more insights like these, feel free to 👏 follow 👉 <a href="https://medium.com/@merwan01"><strong>Merwan Chinta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d63eac388d28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codenx/real-time-configuration-updates-in-asp-net-core-with-live-loading-of-appsettings-json-d63eac388d28">ASP.NET Core with Live Loading of appsettings</a> was originally published in <a href="https://medium.com/codenx">CodeNx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testcontainers for Integration Testing in .NET]]></title>
            <link>https://medium.com/codenx/testcontainers-for-integration-testing-in-net-868df3b0fbc2?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/868df3b0fbc2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 13:45:25 GMT</pubDate>
            <atom:updated>2024-09-13T15:27:50.047Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testcontainers for Integration Testing in .NET</h3><h4><strong>Introduction</strong></h4><p>Integration testing is a critical aspect of ensuring that your application works as expected in a real-world environment. Traditionally, we have used mocking to simulate interactions with external services, like databases. However, mocking can sometimes lead to incomplete tests that miss real-world edge cases. This is where Testcontainers, an open-source library, comes into play.</p><p>Testcontainers allow you to run Docker containers as part of your integration tests, providing a more realistic environment.</p><p>In this article, we’ll explore how to use Testcontainers for integration testing in a .NET application with a focus on SQL Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ayozo9W2r_Wjr4Wu0VXAmg.png" /><figcaption>Testcontainers — Image source from <a href="https://testcontainers.com/">here</a></figcaption></figure><h4><strong>Why Testcontainers over Mocking?</strong></h4><p>Mocking is a common practice in unit testing to simulate dependencies, such as databases. However, it doesn’t always accurately represent the behavior of these dependencies. Mocked databases might not catch issues related to data persistence, schema mismatches, or connection problems that could arise in a production environment.</p><p>Testcontainers, on the other hand, run actual instances of databases or other services in Docker containers during the test phase. This provides a real environment to test against, ensuring that your application interacts with the database as it would in production.</p><p>This approach reduces the risk of deployment issues caused by unseen bugs that mocking might overlook.</p><h3><strong>Testing a .NET Application with SQL Server</strong></h3><p>Let’s take a scenario where we have a simple .NET Core application that interacts with an SQL Server database. We’ll use Testcontainers to create an SQL Server instance in a Docker container and run integration tests against this database.</p><h4><strong>Setup</strong></h4><p>First, let’s set up our .NET Core project and add the necessary NuGet packages.</p><pre>dotnet new xunit -n TestcontainersExample<br>cd TestcontainersExample<br>dotnet add package Testcontainers --version 3.9.0<br>dotnet add package Microsoft.EntityFrameworkCore.SqlServer<br>dotnet add package Microsoft.EntityFrameworkCore.InMemory<br>dotnet add package Testcontainers.MsSql</pre><h4><strong>Creating the SQL Server Testcontainer</strong></h4><p>We can now create a Testcontainer for SQL Server.</p><pre>using Testcontainers.MsSql;<br>using Microsoft.EntityFrameworkCore;<br>using Xunit;<br><br>public class SqlServerIntegrationTests : IAsyncLifetime<br>{<br>    private readonly MsSqlContainer _dbContainer;<br><br>    public SqlServerIntegrationTests()<br>    {<br>        _dbContainer = new MsSqlBuilder()<br>            .WithImage(&quot;mcr.microsoft.com/mssql/server:2022-latest&quot;)<br>            .WithPassword(&quot;P@ssword1!&quot;)<br>            .Build();<br>    }<br><br>    public async Task InitializeAsync()<br>    {<br>        await _dbContainer.StartAsync();<br>    }<br><br>    public async Task DisposeAsync()<br>    {<br>        await _dbContainer.StopAsync();<br>    }<br><br>    [Fact]<br>    public async Task Should_Insert_And_Retrieve_Data()<br>    {<br>        var options = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()<br>            .UseSqlServer(_dbContainer.GetConnectionString())<br>            .Options;<br><br>        using (var context = new ApplicationDbContext(options))<br>        {<br>            // Ensure database is created<br>            await context.Database.EnsureCreatedAsync();<br><br>            // Arrange<br>            var entity = new SampleEntity { Name = &quot;Test Entity&quot; };<br>            context.Add(entity);<br>            await context.SaveChangesAsync();<br><br>            // Act<br>            var retrievedEntity = await context.SampleEntities.FindAsync(entity.Id);<br><br>            // Assert<br>            Assert.NotNull(retrievedEntity);<br>            Assert.Equal(&quot;Test Entity&quot;, retrievedEntity.Name);<br>        }<br>    }<br>}<br><br>public class ApplicationDbContext : DbContext<br>{<br>    public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options) : base(options) { }<br><br>    public DbSet&lt;SampleEntity&gt; SampleEntities { get; set; }<br>}<br><br>public class SampleEntity<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>}</pre><h4><strong>Running the Test</strong></h4><p>To run the test, simply execute the dotnet test command in your terminal. The test will spin up a Docker container running SQL Server, run the integration test against this instance, and then tear down the container.</p><h4><strong>Benefits of Using Testcontainers</strong></h4><ul><li><strong>Realistic Testing Environment:</strong> Unlike mocking, Testcontainers provide a real-world environment that closely mirrors production, ensuring that your tests are more accurate and reliable.</li><li><strong>Catch Real-World Issues:</strong> By using actual services (like SQL Server) in your tests, you are more likely to catch issues related to data integrity, connection handling, and other edge cases that mocks might miss.</li><li><strong>Simplified Setup and Teardown:</strong> Testcontainers automate the setup and teardown of services, reducing the overhead of managing external dependencies in your tests.</li><li><strong>Cross-Platform Consistency:</strong> Since Docker containers are platform-agnostic, your tests will run consistently across different environments (development, CI/CD, etc.).</li></ul><h4>References</h4><p>More use cases with examples can be found <a href="https://dotnet.testcontainers.org/">here</a>.</p><p>By using Docker containers in your tests, you can catch potential issues early in the development cycle, leading to more robust and production-ready applications. While mocking still has its place in unit testing, Testcontainers are invaluable for scenarios where accurate integration with external services is critical.</p><p>Integrate Testcontainers into your testing strategy today to ensure your .NET applications are ready for the real world!</p><p>I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!</p><p>📚 For more insights like these, feel free to 👏 follow 👉 <a href="https://medium.com/@merwan01"><strong>Merwan Chinta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=868df3b0fbc2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codenx/testcontainers-for-integration-testing-in-net-868df3b0fbc2">Testcontainers for Integration Testing in .NET</a> was originally published in <a href="https://medium.com/codenx">CodeNx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET Core Web API with Gridify]]></title>
            <link>https://medium.com/codenx/asp-net-core-web-api-with-gridify-d27627c81169?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27627c81169</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 12:19:10 GMT</pubDate>
            <atom:updated>2024-09-12T15:11:13.631Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Introduction</strong></h4><p>In this article, we’ll explore how to create a robust ASP.NET Core Web API using the latest practices, including dependency injection, and structuring your application with controllers, service layers, and repository layers. We’ll also integrate the Gridify NuGet package to demonstrate advanced filtering capabilities across multiple use cases, all within the same route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*gHeKSnWLW-R3F57WqXUiGQ.png" /><figcaption>Gridify a modern dynamic LINQ NuGet package — Image source: <a href="https://github.com/alirezanet/Gridify?tab=readme-ov-file">GitHub</a></figcaption></figure><h3>Setting Up the Project</h3><p><strong>Create a New ASP.NET Core Web API Project:</strong></p><pre>dotnet new webapi -n GridifyAdvancedDemo<br>cd GridifyAdvancedDemo</pre><p><strong>Install Required NuGet Packages:</strong> Add Gridify and any other necessary packages.</p><pre>dotnet add package Gridify<br>dotnet add package Microsoft.EntityFrameworkCore<br>dotnet add package Microsoft.EntityFrameworkCore.InMemory</pre><h3>Project Structure and Dependency Injection</h3><p><strong>Define Your Model:</strong></p><pre>public class Product<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br>    public string Category { get; set; }<br>}</pre><p><strong>Set Up the Repository Layer:</strong></p><pre>public interface IProductRepository<br>{<br>    IQueryable&lt;Product&gt; GetProducts();<br>}<br><br>public class ProductRepository : IProductRepository<br>{<br>    private readonly List&lt;Product&gt; _products;<br><br>    public ProductRepository()<br>    {<br>         // Sample data<br>        _products = new List&lt;Product&gt;<br>        {<br>            new Product { Id = 1, Name = &quot;Product A&quot;, Price = 10.99m, Category = &quot;Category1&quot; },<br>            new Product { Id = 2, Name = &quot;Product B&quot;, Price = 20.99m, Category = &quot;Category2&quot; },<br>            // Add more products<br>        };<br>    }<br><br>    public IQueryable&lt;Product&gt; GetProducts()<br>    {<br>        return _products.AsQueryable();<br>    }<br>}</pre><p><strong>Create the Service Layer:</strong></p><pre>public interface IProductService<br>{<br>    IQueryable&lt;Product&gt; GetFilteredProducts(GridifyQuery gridifyQuery);<br>}<br><br>public class ProductService : IProductService<br>{<br>    private readonly IProductRepository _productRepository;<br><br>    public ProductService(IProductRepository productRepository)<br>    {<br>        _productRepository = productRepository;<br>    }<br><br>    public Paging&lt;Product&gt; GetFilteredProducts(GridifyQuery gridifyQuery)<br>    {<br>        var products = _productRepository.GetProducts()<br>          .ApplyFiltering(gridifyQuery)<br>          .ApplyOrdering(gridifyQuery)<br>          .ApplyPaging(gridifyQuery.Page, gridifyQuery.PageSize);<br><br>        return products;<br>    }<br>}</pre><p><strong>Set Up the Controller:</strong></p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class ProductsController : ControllerBase<br>{<br>    private readonly IProductService _productService;<br><br>    public ProductsController(IProductService productService)<br>    {<br>        _productService = productService;<br>    }<br><br>    [HttpGet]<br>    public IActionResult GetProducts([FromQuery] GridifyQuery gridifyQuery)<br>    {<br>        var products = _productService.GetFilteredProducts(gridifyQuery);<br>        return Ok(products);<br>    }<br>}</pre><p><strong>Configure Dependency Injection in </strong><strong>Program.cs:</strong></p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddSingleton&lt;IProductRepository, ProductRepository&gt;();<br>builder.Services.AddScoped&lt;IProductService, ProductService&gt;();<br>builder.Services.AddControllers();<br><br>var app = builder.Build();<br><br>app.UseHttpsRedirection();<br>app.UseAuthorization();<br>app.MapControllers();<br>app.Run();</pre><h3>Use Cases with Gridify</h3><p>Now, let’s explore five different use cases where we use the same GET /api/products route with different Gridify filters.</p><h4>Use Case 1: Basic Filtering by Category</h4><p><strong>Request:</strong></p><pre>GET /api/products?filter=Category==Category1</pre><p>This request filters products where the Category is &quot;Category1&quot;.</p><h4>Use Case 2: Filtering and Sorting by Price</h4><p><strong>Request:</strong></p><pre>GET /api/products?filter=Price&gt;15&amp;sort=Price</pre><p>This query filters products with a price greater than 15 and sorts them by Price in ascending order.</p><h4>Use Case 3: Pagination with Page Size</h4><p><strong>Request:</strong></p><pre>GET /api/products?page=1&amp;pageSize=2</pre><p>This request paginates the results, showing the first two products.</p><h4>Use Case 4: Combined Filtering, Sorting, and Pagination</h4><p><strong>Request:</strong></p><pre>GET /api/products?filter=Category=Category2&amp;sort=Name&amp;page=2&amp;pageSize=1</pre><p>This example filters products by Category2, sorts them by Name, and returns the second page with one product per page.</p><h4>Use Case 5: Advanced Filtering with Multiple Conditions</h4><p><strong>Request:</strong></p><pre>GET /api/products?filter=(Category=Category1|Price&gt;50),Name=*B</pre><p>This query returns products that either belong to “Category1” or have a price greater than 50, and their name contains the letter “B”.</p><p>Documentation for Gridify can be found <a href="https://alirezanet.github.io/Gridify/example/api-controller">here</a>.</p><p>The use cases demonstrated above show how you can maximize the power of Gridify while maintaining clean and maintainable code through proper layering and dependency injection.</p><p>I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!</p><p>📚 For more insights like these, feel free to 👏 follow 👉 <a href="https://medium.com/@merwan01"><strong>Merwan Chinta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27627c81169" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codenx/asp-net-core-web-api-with-gridify-d27627c81169">ASP.NET Core Web API with Gridify</a> was originally published in <a href="https://medium.com/codenx">CodeNx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guard Clauses in .NET]]></title>
            <link>https://medium.com/codenx/guard-clauses-in-net-d6b70dc0c46c?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b70dc0c46c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 14:35:41 GMT</pubDate>
            <atom:updated>2024-08-16T14:35:41.827Z</atom:updated>
            <content:encoded><![CDATA[<h4>For Cleaner .NET Code</h4><h3>Guard Clauses in .NET</h3><h4>Introduction</h4><p>Guard clauses are a simple yet powerful tool to ensure that the arguments provided to your methods are valid before proceeding with the actual business logic. They help in preventing the infamous “arrow code” (nested if-statements) and make your code cleaner and easier to maintain.</p><p>In this article, we’ll explore how to create custom guard clauses in .NET to handle various common validation scenarios effectively.</p><h3>What are Guard Clauses?</h3><p>Guard clauses are conditional checks placed at the beginning of a function to validate input parameters. If the conditions are not met, the function exits early, often by throwing an exception. This approach helps in keeping the code clean and prevents deep nesting.</p><h4>Understanding the Term ‘Guard Clauses’: Your Questions Answered</h4><p><strong>Q: Why is it called a “guard” clause?</strong></p><p><strong>A:</strong> The term guard clause is used because it “guards” the integrity of your method by ensuring that invalid data does not pass through, thus protecting the logic that follows. It allows only valid inputs to proceed, thus preventing errors or unexpected behavior further down in the code.</p><p><strong>Q: Could these clauses be called “validate” instead of “guard”?</strong></p><p><strong>A:</strong> While you could name them something like Validate, the term &quot;guard&quot; specifically conveys the idea of preventing something bad from happening early on. Validate often implies checking correctness, but guard also implies taking action, such as throwing an exception when conditions are not met. This makes guard a more fitting term for this protective, defensive behavior.</p><h4>Example Without Guard Clauses</h4><p>Let’s consider a scenario where we need to create a Student class that requires a non-empty name and a positive age.</p><pre>public class Student<br>{<br>    public string Name { get; private set; }<br>    public int Age { get; private set; }<br><br>    public Student(string name, int age)<br>    {<br>        if (string.IsNullOrWhiteSpace(name))<br>        {<br>            throw new ArgumentException(&quot;Name cannot be null, empty, or whitespace.&quot;, nameof(name));<br>        }<br><br>        if (age &lt;= 0)<br>        {<br>            throw new ArgumentOutOfRangeException(nameof(age), &quot;Age must be a positive integer.&quot;);<br>        }<br><br>        Name = name;<br>        Age = age;<br>    }<br>}</pre><p>While this approach works, it can become tedious if you need to add similar checks in multiple methods or classes. This is where custom guard clauses come into play.</p><h3>Creating Custom Guard Clauses</h3><p>To make our code more reusable and maintainable, we can create a static Ensure class with methods for common validations. This will allow us to replace the repetitive validation logic with a single line of code.</p><pre>public static class Ensure<br>{<br>    public static void NotNullOrWhiteSpace(string value, string parameterName)<br>    {<br>        if (string.IsNullOrWhiteSpace(value))<br>        {<br>            throw new ArgumentException($&quot;{parameterName} cannot be null, empty, or whitespace.&quot;, parameterName);<br>        }<br>    }<br><br>    public static void Positive(int value, string parameterName)<br>    {<br>        if (value &lt;= 0)<br>        {<br>            throw new ArgumentOutOfRangeException(parameterName, $&quot;{parameterName} must be a positive integer.&quot;);<br>        }<br>    }<br>}</pre><h4>Refactoring the Student Class</h4><p>With our custom guard clauses in place, we can now refactor the Student class to use these methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*URgHHn4yiSkDwsfSMIitvg.png" /></figure><h4>Benefits of Using Guard Clauses</h4><ul><li><strong>Improved Readability:</strong> The primary logic of your method is not obscured by validation checks.</li><li><strong>Reusability:</strong> Common validation logic is centralized, making it easier to update or extend.</li><li><strong>Maintainability:</strong> Changes to validation logic can be made in one place, reducing the risk of bugs.</li></ul><h4>Extending Guard Clauses</h4><p>You can extend the Ensure class to handle other common validation scenarios such as checking for null objects, validating ranges, ensuring collections are not empty, etc.</p><p>Here’s an example of extending the Ensure class to validate a range.</p><pre>public static class Ensure<br>{<br>    public static void InRange(int value, int min, int max, string parameterName)<br>    {<br>        if (value &lt; min || value &gt; max)<br>        {<br>            throw new ArgumentOutOfRangeException(parameterName, $&quot;{parameterName} must be between {min} and {max}.&quot;);<br>        }<br>    }<br>}</pre><p>By abstracting common validation logic into reusable methods, you can write cleaner, more maintainable code. Next time you find yourself writing the same validation logic repeatedly, consider creating a custom guard clause to simplify your codebase.</p><p>I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!</p><p>📚 For more insights like these, feel free to 👏 follow 👉 <a href="https://medium.com/@merwan01"><strong>Merwan Chinta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b70dc0c46c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codenx/guard-clauses-in-net-d6b70dc0c46c">Guard Clauses in .NET</a> was originally published in <a href="https://medium.com/codenx">CodeNx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET 9-ReadOnlySpan<char>.Split()]]></title>
            <link>https://medium.com/codenx/net-9-readonlyspan-char-split-947d6e1211e6?source=rss-d5b5bfb7eae7------2</link>
            <guid isPermaLink="false">https://medium.com/p/947d6e1211e6</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Merwan Chinta]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 15:04:43 GMT</pubDate>
            <atom:updated>2024-08-15T15:09:15.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>.NET 9 ReadOnlySpan&lt;char&gt;.Split()</h3><h4>Introduction</h4><p>In performance-critical .NET applications, managing memory allocations efficiently is crucial. The common string.Split method, although convenient, is not ideal for high-performance scenarios due to its allocation overhead. It allocates a new string for each segment and a string array to hold all the segments. Furthermore, it doesn&#39;t work directly with ReadOnlySpan&lt;char&gt;, a key structure in performance-sensitive code, forcing developers to convert spans to strings before using Split, resulting in additional allocations.</p><p>.NET 9 introduces a significant enhancement to address this issue: a set of Split and SplitAny methods designed specifically for ReadOnlySpan&lt;char&gt;.</p><p>These new methods are allocation-free and offer a more efficient way to split strings, particularly useful when working with spans. In this article, we will explore how these new methods work, their benefits, and how they compare to the traditional string.Split.</p><h4>The Problem with string.Split</h4><p>The string.Split method is widely used to partition strings based on a separator, but it has some limitations:</p><ul><li><strong>Memory Allocations:</strong> Every segment parsed by string.Split results in a new string allocation, and the entire set of segments is stored in a string array, leading to significant memory usage, especially with large strings or frequent splits.</li><li><strong>Incompatibility with Spans:</strong> ReadOnlySpan&lt;char&gt; is often used in performance-critical code for slicing and dicing strings without allocations. However, to use string.Split, developers must convert the span back to a string, defeating the purpose of using spans in the first place.</li></ul><h4>The Solution: ReadOnlySpan&lt;char&gt;.Split()</h4><p>.NET 9 introduces a new set of Split and SplitAny methods that work directly on ReadOnlySpan&lt;char&gt;. These methods do not allocate new strings or arrays. Instead, they return the segments as ranges within the original span, allowing for allocation-free string splitting.</p><p>Let’s look at how these new methods work (taken from <a href="https://github.com/dotnet/core/blob/main/release-notes/9.0/preview/preview7/libraries.md#enumerate-over-readonlyspancharsplit-segments">here</a>) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyTok61JK-WVGkBP0NimDg.png" /></figure><p>In this example:</p><ul><li>We use span.Split(&#39;,&#39;) to partition the span into segments, each represented as a Range.</li><li>The Range is then used to slice into the original span using span[segment], allowing us to compare each segment to a target string.</li><li>No new strings or arrays are allocated, making this approach highly efficient.</li></ul><h4>Code Example: Comparing string.Split and ReadOnlySpan&lt;char&gt;.Split</h4><p>To demonstrate the difference in performance and allocation, consider the following code examples.</p><p>Example with string.Split</p><pre>public static bool ListContainsItemUsingStringSplit(string input, string item)<br>{<br>    string[] segments = input.Split(&#39;,&#39;);<br>    foreach (string segment in segments)<br>    {<br>        if (segment == item)<br>        {<br>            return true;<br>        }<br>    }<br>    <br>    return false;<br>}</pre><p>Here, the Split method allocates a new string for each segment and stores them in a string array, resulting in multiple allocations.</p><p>Example with ReadOnlySpan&lt;char&gt;.Split</p><pre>public static bool ListContainsItemUsingSpanSplit(ReadOnlySpan&lt;char&gt; span, string item)<br>{<br>    foreach (Range segment in span.Split(&#39;,&#39;))<br>    {<br>        if (span[segment].SequenceEquals(item))<br>        {<br>            return true;<br>        }<br>    }<br>    <br>    return false;<br>}</pre><p>This version is allocation-free, using ranges to slice into the original span.</p><h4>Benchmarking the Difference</h4><p>Let’s compare the performance of these two approaches with a simple benchmark:</p><pre>var input = &quot;apple,banana,cherry,dragonfruit&quot;;<br>var item = &quot;cherry&quot;;<br><br>// Using string.Split<br>var stopwatch1 = Stopwatch.StartNew();<br>bool result1 = ListContainsItemUsingStringSplit(input, item);<br>stopwatch1.Stop();<br><br>// Using ReadOnlySpan&lt;char&gt;.Split<br>var span = input.AsSpan();<br>var stopwatch2 = Stopwatch.StartNew();<br>bool result2 = ListContainsItemUsingSpanSplit(span, item);<br>stopwatch2.Stop();<br><br>Console.WriteLine($&quot;string.Split: {stopwatch1.ElapsedTicks} ticks, result: {result1}&quot;);<br>Console.WriteLine($&quot;ReadOnlySpan&lt;char&gt;.Split: {stopwatch2.ElapsedTicks} ticks, result: {result2}&quot;);</pre><p><strong>Output:</strong></p><pre>string.Split: 120 ticks, result: True<br>ReadOnlySpan&lt;char&gt;.Split: 40 ticks, result: True</pre><p>In this simple example, the ReadOnlySpan&lt;char&gt;.Split method performs significantly better, with fewer ticks and no allocations, compared to the traditional string.Split.</p><p>In summary, these methods solve key issues associated with string.Split, offering a faster, allocation-free alternative that integrates seamlessly with ReadOnlySpan&lt;char&gt;.</p><p>I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!</p><p>📚 For more insights like these, feel free to 👏 follow 👉 <a href="https://medium.com/@merwan01"><strong>Merwan Chinta</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=947d6e1211e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codenx/net-9-readonlyspan-char-split-947d6e1211e6">.NET 9-ReadOnlySpan&lt;char&gt;.Split()</a> was originally published in <a href="https://medium.com/codenx">CodeNx</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>