<?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 Josiah T Mahachi on Medium]]></title>
        <description><![CDATA[Stories by Josiah T Mahachi on Medium]]></description>
        <link>https://medium.com/@josiahmahachi?source=rss-db4379384042------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LGOTa2HRzmv9upnZ</url>
            <title>Stories by Josiah T Mahachi on Medium</title>
            <link>https://medium.com/@josiahmahachi?source=rss-db4379384042------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 15:53:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@josiahmahachi/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[A Clean and Efficient Way to Select Handlers with a Dictionary in C#]]></title>
            <link>https://medium.com/@josiahmahachi/a-clean-and-efficient-way-to-select-handlers-with-a-dictionary-in-c-981e5ae7c066?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/981e5ae7c066</guid>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 22:34:17 GMT</pubDate>
            <atom:updated>2025-02-04T22:34:17.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EhdbENGy6bJyPeag.jpg" /><figcaption>A Clean and Efficient Way to Select Handlers with a Dictionary in C#</figcaption></figure><p>Today, I’d like to share a practical solution I recently implemented in one of my projects where I needed to select the correct “handler” for a specific task. Initially, I wrote a straightforward switch statement to manage the logic. While this worked, it quickly became cumbersome. In this post, I’ll show how I refactored the switch statement into a dictionary-based approach, and why this made the solution more scalable and easier to maintain.</p><h3>The Original switch Approach</h3><p>Let’s look at a simplified version of the original code. Suppose we have a function called ImportCustomerData that takes in the fileType (e.g., &quot;csv&quot; or &quot;excel&quot;) and the file path. Here’s what the switch-based solution might look like:</p><pre>public class CustomerImporter : ICustomerImporter<br>{<br>    public void ImportCustomerData(string fileType, string filePath)<br>    {<br>        switch (fileType.ToLower())<br>        {<br>            case &quot;csv&quot;:<br>                ReadCsv(filePath);<br>                break;<br>            case &quot;excel&quot;:<br>                ReadExcel(filePath);<br>                break;<br>            case &quot;text&quot;:<br>                ReadText(filePath);<br>                break;<br>            case &quot;xml&quot;:<br>                ReadXml(filePath);<br>                break;<br>            case &quot;json&quot;:<br>                ReadJson(filePath);<br>                break;<br>            default:<br>                throw new ArgumentException($&quot;Unsupported file type: {fileType}&quot;);<br>        }<br>    }<br><br>    private void ReadCsv(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading CSV file: {filePath}&quot;);<br>        // Actual CSV parsing logic here...<br>    }<br><br>    private void ReadExcel(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading Excel file: {filePath}&quot;);<br>        // Actual Excel reading logic here...<br>    }<br><br>    private void ReadText(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading Text file: {filePath}&quot;);<br>        // Actual text reading logic here...<br>    }<br><br>    private void ReadXml(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading XML file: {filePath}&quot;);<br>        // Actual XML parsing logic here...<br>    }<br><br>    private void ReadJson(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading JSON file: {filePath}&quot;);<br>        // Actual JSON parsing logic here...<br>    }<br>}</pre><p>This approach is okay for handling a handful of file types, but what happens when you start adding new file formats — like Parquet, AVRO, or specialized proprietary file formats? You’ll have to keep expanding the switch statement, making the class unwieldy over time. Managing these cases becomes tedious, especially if you need to register or deregister new services dynamically.</p><h3>Why Move Away from switch?</h3><ol><li><strong>Maintainability</strong>: A long switch statement can become difficult to read and maintain as new cases are introduced. Each new task type requires a new case inside the switch.</li><li><strong>Open/Closed Principle</strong>: Every time you add a new task handler, you have to modify existing code (the switch statement). This goes against the Open/Closed Principle of software design, which states that software entities should be open for extension, but closed for modification.</li><li><strong>Flexibility</strong>: If you want to dynamically register or configure different handlers (e.g., from configuration files), a switch statement is not flexible enough for that approach.</li></ol><h3>The Dictionary-Based Approach</h3><p>To simplify the process, you can map file types to their respective parsing methods using a dictionary. Each file type can be associated with a delegate (an Action&lt;string&gt; in this case) that references the correct method. Here’s what this approach might look like:</p><pre>using System;<br>using System.Collections.Generic;<br><br>public class CustomerImporter<br>{<br>    private readonly Dictionary&lt;string, Action&lt;string&gt;&gt; _fileHandlers;<br><br>    public CustomerImporter()<br>    {<br>        _fileHandlers = new Dictionary&lt;string, Action&lt;string&gt;&gt;(StringComparer.OrdinalIgnoreCase)<br>        {<br>            { &quot;csv&quot;, ReadCsv },<br>            { &quot;excel&quot;, ReadExcel },<br>            { &quot;text&quot;, ReadText },<br>            { &quot;xml&quot;, ReadXml },<br>            { &quot;json&quot;, ReadJson }<br>        };<br>    }<br><br>    public void ImportCustomerData(string fileType, string filePath)<br>    {<br>        if (_fileHandlers.TryGetValue(fileType, out var handler))<br>        {<br>            handler(filePath);<br>        }<br>        else<br>        {<br>            throw new ArgumentException($&quot;Unsupported file type: {fileType}&quot;);<br>        }<br>    }<br><br>    private void ReadCsv(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading CSV file: {filePath}&quot;);<br>        // Actual CSV parsing logic here...<br>    }<br><br>    private void ReadExcel(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading Excel file: {filePath}&quot;);<br>        // Actual Excel reading logic here...<br>    }<br><br>    private void ReadText(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading Text file: {filePath}&quot;);<br>        // Actual text reading logic here...<br>    }<br><br>    private void ReadXml(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading XML file: {filePath}&quot;);<br>        // Actual XML parsing logic here...<br>    }<br><br>    private void ReadJson(string filePath)<br>    {<br>        Console.WriteLine($&quot;Reading JSON file: {filePath}&quot;);<br>        // Actual JSON parsing logic here...<br>    }<br>}</pre><h3>How This Works</h3><ul><li>In the constructor, we initialize a Dictionary that maps a file type (e.g., &quot;csv&quot;) to its corresponding method (ReadCsv).</li><li>In the ImportCustomerData method, we look up the handler in _fileHandlers using fileType.</li><li>If the key exists, we call the appropriate method to process the file. Otherwise, we throw an ArgumentException for unsupported file types.</li></ul><h3>Benefits of the Dictionary Approach</h3><ol><li><strong>Scalability</strong>: Adding a new task type is as simple as adding a new entry to the dictionary (or even configuring it from an external source). You do not need to expand a switch statement every time.</li><li><strong>Cleaner Code</strong>: The dictionary approach organizes your code in a way that is more readable and maintainable. You avoid large blocks of case statements and keep your handlers neatly separated.</li><li><strong>Flexibility</strong>: It’s straightforward to inject dependencies, configure new handlers, or even remove handlers without modifying core logic. You can also combine it with Dependency Injection frameworks (e.g., using Func&lt;string, IHandler&gt; or similar approaches).</li></ol><p>Refactoring from a switch statement to a dictionary-based approach provided a major boost in maintainability and flexibility for this project. With just a few lines of code, I can now add new file types, remove old ones, or change implementations on the fly, all while keeping my ImportCustomerData method succinct.</p><p><strong>Have you tried this method for handling different file types, or do you have a different pattern in mind?</strong> Share your experiences in the comments below — I’d love to hear how you handle these scenarios.</p><p>Happy coding! 👌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=981e5ae7c066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SOLID Principles]]></title>
            <link>https://medium.com/@josiahmahachi/understanding-solid-principles-0396eeb70f1b?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/0396eeb70f1b</guid>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 22:07:16 GMT</pubDate>
            <atom:updated>2025-02-04T22:07:16.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*Tcz8nyEB1HxzmNBi.png" /><figcaption>Implementing Secure Data Encryption in C# with Azure Key Vault</figcaption></figure><p>Writing maintainable, scalable, and testable code is crucial in software development. The <strong>SOLID</strong> principles — Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion — help achieve these objectives.</p><p>In this blog post, we will take a poorly written encryption utility and refactor it step by step to align with SOLID principles while integrating Azure Key Vault for secure key management for more secure secrets management.</p><h3>The Problem: A Poorly Written Encryption Class</h3><p>Below is an example of a poorly structured encryption utility:</p><pre>using System;<br>using System.Security.Cryptography;<br>using System.Text;<br><br>public class EncryptionUtility<br>{<br>    private readonly string encryptionKey = &quot;MyHardcodedKey&quot;;<br><br>    public string Encrypt(string plainText)<br>    {<br>        byte[] keyBytes = Encoding.UTF8.GetBytes(encryptionKey);<br>        using (Aes aes = Aes.Create())<br>        {<br>            aes.Key = keyBytes;<br>            aes.GenerateIV();<br>            ICryptoTransform encryptor = aes.CreateEncryptor();<br>            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);<br>            byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);<br>            return Convert.ToBase64String(encryptedBytes);<br>        }<br>    }<br><br>    public string Decrypt(string encryptedText)<br>    {<br>        byte[] keyBytes = Encoding.UTF8.GetBytes(encryptionKey);<br>        using (Aes aes = Aes.Create())<br>        {<br>            aes.Key = keyBytes;<br>            ICryptoTransform decryptor = aes.CreateDecryptor();<br>            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);<br>            byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);<br>            return Encoding.UTF8.GetString(decryptedBytes);<br>        }<br>    }<br>}</pre><h3>Issues with the Code:</h3><ol><li>The class is responsible for both encryption and key management.</li><li>The encryption key is embedded in the code, making it insecure. This is also called a <em>magic string</em> in code.</li><li>The class creates dependencies internally, making it hard to test.</li><li>Any changes to the encryption algorithm require modifying the class.</li></ol><h3>Step-by-Step Refactoring to Meet SOLID Principles</h3><p>In the next few steps, we will address the issues we identified above.</p><h3>Step 1: Extract Key Management to Azure Key Vault</h3><p>To eliminate hardcoded keys, we integrate Azure Key Vault:</p><pre>using Azure.Identity;<br>using Azure.Security.KeyVault.Secrets;<br>using System;<br>using System.Threading.Tasks; <br><br>public class KeyVaultService<br>{<br>    private readonly SecretClient _client;<br>    private readonly string _keyName;<br><br>    public KeyVaultService(string vaultUrl, string keyName)<br>    {<br>        _client = new SecretClient(new Uri(vaultUrl), new DefaultAzureCredential());<br>        _keyName = keyName;<br>    }<br><br>    public async Task&lt;string&gt; GetEncryptionKeyAsync()<br>    {<br>        KeyVaultSecret secret = await _client.GetSecretAsync(_keyName);<br>        return secret.Value;<br>    }<br>}</pre><h3>Step 2: Apply Dependency Injection</h3><p>Instead of creating dependencies within the class, we inject them:</p><pre>using System;<br>using System.Security.Cryptography;<br>using System.Text;<br>using System.Threading.Tasks;<br><br>public interface IEncryptionService<br>{<br>    Task&lt;string&gt; EncryptAsync(string plainText);<br>    Task&lt;string&gt; DecryptAsync(string encryptedText);<br>}<br><br>public class EncryptionService : IEncryptionService<br>{<br>    private readonly KeyVaultService _keyVaultService;<br><br>    public EncryptionService(KeyVaultService keyVaultService)<br>    {<br>        _keyVaultService = keyVaultService;<br>    }<br><br>    public async Task&lt;string&gt; EncryptAsync(string plainText)<br>    {<br>        string encryptionKey = await _keyVaultService.GetEncryptionKeyAsync();<br>        byte[] keyBytes = Encoding.UTF8.GetBytes(encryptionKey);<br>        using (Aes aes = Aes.Create())<br>        {<br>            aes.Key = keyBytes;<br>            aes.GenerateIV();<br>            ICryptoTransform encryptor = aes.CreateEncryptor();<br>            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);<br>            byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);<br>            return Convert.ToBase64String(encryptedBytes);<br>        }<br>    } <br><br>    public async Task&lt;string&gt; DecryptAsync(string encryptedText)<br>    {<br>        string encryptionKey = await _keyVaultService.GetEncryptionKeyAsync();<br>        byte[] keyBytes = Encoding.UTF8.GetBytes(encryptionKey);<br>        using (Aes aes = Aes.Create())<br>        {<br>            aes.Key = keyBytes;<br>            ICryptoTransform decryptor = aes.CreateDecryptor();<br>            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);<br>            byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);<br>            return Encoding.UTF8.GetString(decryptedBytes);<br>        }<br>    }<br>}</pre><h3>Step 3: Implement Interface Segregation &amp; Dependency Inversion</h3><p>We separate encryption logic from key management and introduce interfaces:</p><pre>public interface IKeyVaultService<br>{<br>    Task&lt;string&gt; GetEncryptionKeyAsync();<br>}</pre><p>Now, EncryptionService depends on IKeyVaultService instead of a concrete implementation, following the Dependency Inversion Principle.</p><h3>Lastly</h3><p>By refactoring our original encryption utility, we have:</p><ul><li>Removed hardcoded secrets, improving security.</li><li>Followed SOLID principles, making our code more maintainable and testable.</li><li>Integrated Azure Key Vault for secure key management.</li><li>Applied Dependency Injection to make unit testing easier.</li></ul><p>Following these principles in your C# applications will lead to better software design, improved maintainability, and enhanced security. 🚀</p><h3>Next Steps</h3><ul><li>Extend the encryption service to support multiple algorithms.</li><li>Implement logging and error handling.</li><li>Create unit tests for the services.</li></ul><p>Happy coding! 🎯</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0396eeb70f1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Powers of 2 to Store Flags in Entity Framework]]></title>
            <link>https://medium.com/@josiahmahachi/using-powers-of-2-to-store-flags-in-entity-framework-23f7315c36d5?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/23f7315c36d5</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[bitwise-operator]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 20:48:02 GMT</pubDate>
            <atom:updated>2024-12-01T20:48:02.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3lzfmdqlSgpKYaul" /><figcaption>Using Powers of 2 to Store Flags in Entity Framework</figcaption></figure><p>Storing binary data in powers of 2, commonly known as <strong>bitwise flags</strong> or <strong>flag-based enums</strong>, is an elegant way to represent multiple boolean options in a single integer field. This technique is widely used in software development to optimize database storage and streamline queries, especially when working with <strong>Entity Framework (EF)</strong>.</p><p>In this blog post, we’ll explore how this approach works, its implementation in Entity Framework, and why it’s such a powerful technique.</p><blockquote>Bit fields are generally used for lists of elements that might occur in combination, whereas enumeration constants are generally used for lists of mutually exclusive elements. Therefore, bit fields are designed to be combined with a bitwise OR operation to generate unnamed values, whereas enumerated constants are not. Languages vary in their use of bit fields compared to enumeration constants. — <a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-flagsattribute">Microsoft Learn</a></blockquote><h3>What Are Bitwise Flags?</h3><p>Bitwise flags use the properties of binary numbers to represent multiple independent states or options compactly. Each state is assigned a power of 2, allowing unique combinations of states to be represented as a single integer value.</p><p>For example, consider user access rights like Read, Write, and Execute. Instead of using three separate columns or a more complex data structure, we can assign each right a power of 2:</p><ul><li>Read = 1 (binary: 001)</li><li>Write = 2 (binary: 010)</li><li>Execute = 4 (binary: 100)</li></ul><p>By combining these using <strong>bitwise OR (</strong><strong>|)</strong>, we can store multiple flags in one field:</p><ul><li>Read | Write = 3 (binary: 011)</li><li>Read | Execute = 5 (binary: 101)</li></ul><h3>Why Use This Technique in Entity Framework?</h3><p>Entity Framework, as an Object-Relational Mapper (ORM), translates database structures into .NET objects. Using bitwise flags allows you to:</p><ol><li><strong>Reduce Storage Overhead</strong>: Store multiple boolean states in a single integer field.</li><li><strong>Efficient Queries</strong>: Perform fast bitwise operations in both LINQ and SQL.</li><li><strong>Readable Code</strong>: Leverage strongly-typed enums for better code clarity.</li></ol><h3>Implementing Bitwise Flags in Entity Framework</h3><p>Here’s how you can use bitwise flags with EF.</p><h4>Step 1: Define a Flag Enum</h4><p>The [Flags] attribute is a key feature of .NET that indicates an enum is intended to represent a combination of values.</p><pre>[Flags]<br>public enum AccessRights<br>{<br>    None = 0,       // No access<br>    Read = 1 &lt;&lt; 0,  // 1<br>    Write = 1 &lt;&lt; 1, // 2<br>    Execute = 1 &lt;&lt; 2 // 4<br>}</pre><p>Note that this is the same as…</p><pre>[Flags]<br>public enum AccessRights<br>{<br>    None = 0,<br>    Read = 1,<br>    Write = 2,<br>    Execute = 4<br>}</pre><h4>Step 2: Use the Enum in an Entity</h4><p>Create an entity class with a property that uses the enum.</p><pre>public class User<br>{<br>    public int Id { get; set; }<br><br>    // The Rights property will be stored as an integer in the database<br>    public AccessRights Rights { get; set; }<br>}</pre><p>Entity Framework Core will store the numeric value of AccessRights in the database.</p><h4>Step 3: Configure EF to Map the Enum</h4><p>By default, EF Core maps enums to their underlying integer values. To ensure this, you can explicitly configure the property in the DbContext:</p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;User&gt;()<br>        .Property(u =&gt; u.Rights)<br>        .HasConversion&lt;int&gt;(); // Ensure the enum is stored as an integer<br>}</pre><h4>Step 4: Store and Retrieve Flags</h4><p>When adding data, you can combine flags using bitwise OR (|):</p><pre>var user = new User<br>{<br>    Id = 1,<br>    Rights = AccessRights.Read | AccessRights.Write<br>};<br><br>dbContext.Users.Add(user);<br>dbContext.SaveChanges();</pre><p>To retrieve data, use bitwise AND (&amp;) in LINQ queries:</p><pre>var usersWithReadAccess = dbContext.Users<br>    .Where(u =&gt; (u.Rights &amp; AccessRights.Read) == AccessRights.Read)<br>    .ToList();</pre><h3>How It Works in the Database</h3><p>When you save a record, EF Core stores the combined integer value of the flags. For example:</p><ul><li>A user with Read and Write rights will have a value of 3 in the Rights column.</li></ul><p>This approach enables efficient storage and querying:</p><ol><li><strong>Storage</strong>: The database uses a single integer column instead of multiple boolean columns.</li><li><strong>Querying</strong>: SQL supports bitwise operations, making queries fast and efficient.</li></ol><h3>Advantages of Bitwise Flags</h3><ol><li><strong>Compact Representation</strong>: Store multiple boolean values in a single field.</li><li><strong>Efficient Operations</strong>: Perform fast bitwise operations in SQL and LINQ.</li><li><strong>Clean Code</strong>: Strongly-typed enums improve code readability.</li><li><strong>Extensibility</strong>: Easily add new flags by assigning the next power of 2.</li></ol><h3>Potential Pitfalls</h3><p>While this technique is powerful, there are some caveats:</p><ol><li><strong>Limited Use Cases</strong>: Not suitable for scenarios requiring normalized relational data.</li><li><strong>Complex Queries</strong>: Bitwise operations can be harder to read and debug.</li><li><strong>Integer Overflow</strong>: If you need more than 32 flags, you’ll need a long (64-bit) or a custom implementation.</li><li><strong>Migration Challenges</strong>: Adding or renaming flags requires careful handling to avoid breaking existing data.</li></ol><h3>Finally</h3><p>Storing bitwise flags using powers of 2 is an efficient and compact way to manage multiple boolean states in Entity Framework. By leveraging enums and bitwise operations, you can write clean, maintainable code while optimizing database storage and queries.</p><p>This technique is particularly useful for scenarios like access control, feature toggles, and other state combinations. However, like any tool, it should be used judiciously, keeping in mind the trade-offs.</p><p>If you’re working with EF and want to implement a simple yet powerful way to handle multiple states, bitwise flags are an excellent option.</p><h3>Further Reading</h3><ul><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/enumeration-types">Official .NET Documentation: Enums and Flags</a></li><li><a href="https://learn.microsoft.com/en-us/ef/core/">Entity Framework Core Documentation</a></li><li><a href="https://learn.microsoft.com/en-us/sql/t-sql/operators/bitwise-operators-transact-sql">Bitwise Operations in SQL</a></li></ul><p>Happy coding! Let me know in the comments if you’ve used bitwise flags in your projects and what challenges you faced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23f7315c36d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Pattern Matching Examples]]></title>
            <link>https://medium.com/@josiahmahachi/c-pattern-matching-examples-f8162ea76db6?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8162ea76db6</guid>
            <category><![CDATA[tuples]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[linq]]></category>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 00:01:09 GMT</pubDate>
            <atom:updated>2024-10-18T00:01:09.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0FjCaXDZBr1dBGIc.jpg" /><figcaption>Pattern Matching in C# with Examples</figcaption></figure><p>Pattern matching in C# is a powerful feature introduced in C# 7.0 and has been enhanced in later versions. It allows you to test expressions and objects against patterns. These patterns can be types, values, or complex structures, which makes the code more concise and readable.</p><p>Let’s dive into what pattern matching is all about and explore it with a number of examples.</p><h3>Basic Type Pattern Matching</h3><p>One of the most common use cases of pattern matching is to check if an object is of a certain type.</p><pre>if (obj is int number)<br>{<br>    Console.WriteLine($&quot;The number is {number}&quot;);<br>}</pre><p>Here, obj is checked if it&#39;s an int, and if so, the value is assigned to the variable number.</p><h3>Constant Pattern Matching</h3><p>You can also match values using constants.</p><pre>int dayOfWeek = 7;<br><br>string result = dayOfWeek switch<br>{<br>    1 =&gt; &quot;Monday&quot;,<br>    2 =&gt; &quot;Tuesday&quot;,<br>    3 =&gt; &quot;Wednesday&quot;,<br>    4 =&gt; &quot;Thursday&quot;,<br>    5 =&gt; &quot;Friday&quot;,<br>    6 =&gt; &quot;Saturday&quot;,<br>    7 =&gt; &quot;Sunday&quot;,<br>    _ =&gt; &quot;Invalid day&quot;<br>};<br><br>Console.WriteLine(result);</pre><p>This uses the switch expression to match constant values of dayOfWeek.</p><h3>Null Check with Pattern Matching</h3><p>Pattern matching can easily check for null values.</p><pre>string name = null;<br><br>if (name is null)<br>{<br>    Console.WriteLine(&quot;Name is null&quot;);<br>}</pre><h3>Relational Patterns</h3><p>C# 9.0 introduced relational patterns, which allow you to use comparison operators.</p><pre>int age = 25;<br><br>string category = age switch<br>{<br>    &lt; 18 =&gt; &quot;Child&quot;,<br>    &gt;= 18 and &lt; 60 =&gt; &quot;Adult&quot;,<br>    &gt;= 60 =&gt; &quot;Senior&quot;,<br>    _ =&gt; &quot;Unknown&quot;<br>};<br><br>Console.WriteLine(category);</pre><h3>Logical Patterns (and, or, not)</h3><p>You can combine patterns using logical operators.</p><pre>int temperature = 30;<br><br>string weather = temperature switch<br>{<br>    &gt; 0 and &lt; 20 =&gt; &quot;Cold&quot;,<br>    &gt;= 20 and &lt;= 30 =&gt; &quot;Warm&quot;,<br>    &gt; 30 =&gt; &quot;Hot&quot;,<br>    _ =&gt; &quot;Unknown&quot;<br>};<br><br>Console.WriteLine(weather);</pre><h3>Positional Pattern Matching (Tuple)</h3><p>Pattern matching works great with tuples for deconstructing values.</p><pre>(int x, int y) point = (3, 4);<br><br>string result = point switch<br>{<br>    (0, 0) =&gt; &quot;Origin&quot;,<br>    (_, 0) =&gt; &quot;On the X axis&quot;,<br>    (0, _) =&gt; &quot;On the Y axis&quot;,<br>    _ =&gt; &quot;Elsewhere&quot;<br>};<br><br>Console.WriteLine(result);</pre><h3>Pattern Matching with switch Statement</h3><p>Pattern matching can be used inside a switch statement for greater clarity.</p><pre>object shape = new Circle { Radius = 5 };<br><br>switch (shape)<br>{<br>    case Circle c:<br>        Console.WriteLine($&quot;Circle with radius {c.Radius}&quot;);<br>        break;<br>    case Rectangle r:<br>        Console.WriteLine($&quot;Rectangle with dimensions {r.Length} x {r.Breadth}&quot;);<br>        break;<br>    default:<br>        Console.WriteLine(&quot;Unknown shape&quot;);<br>        break;<br>}</pre><h3>Property Pattern Matching</h3><p>You can also match objects based on their properties.</p><pre>var person = new Person { Name = &quot;Alice&quot;, Age = 30 };<br><br>if (person is { Age: &gt; 20, Name: &quot;Alice&quot; })<br>{<br>    Console.WriteLine(&quot;Match found for Alice&quot;);<br>}</pre><h3>Positional Pattern Matching with Records</h3><p>Pattern matching works seamlessly with records, introduced in C# 9.</p><pre>public record Point(int X, int Y);<br><br>var point = new Point(3, 4);<br><br>var location = point switch<br>{<br>    Point(0, 0) =&gt; &quot;Origin&quot;,<br>    Point(_, 0) =&gt; &quot;On the X axis&quot;,<br>    Point(0, _) =&gt; &quot;On the Y axis&quot;,<br>    _ =&gt; &quot;Elsewhere&quot;<br>};<br><br>Console.WriteLine(location);</pre><h3>List Pattern Matching (C# 12 Preview)</h3><p>C# 12 introduces list pattern matching.</p><pre>int[] numbers = { 1, 2, 3 };<br><br>string result = numbers switch<br>{<br>    [1, 2, 3] =&gt; &quot;Matched the exact list&quot;,<br>    [_, _, _] =&gt; &quot;Matched any list with 3 elements&quot;,<br>    _ =&gt; &quot;No match&quot;<br>};<br><br>Console.WriteLine(result);</pre><h3>Pattern Matching with Enums</h3><p>You can match on enum values too.</p><pre>public enum TrafficLight { Red, Yellow, Green }<br><br>TrafficLight light = TrafficLight.Yellow;<br><br>string action = light switch<br>{<br>    TrafficLight.Red =&gt; &quot;Stop&quot;,<br>    TrafficLight.Yellow =&gt; &quot;Caution&quot;,<br>    TrafficLight.Green =&gt; &quot;Go&quot;,<br>    _ =&gt; &quot;Unknown&quot;<br>};<br><br>Console.WriteLine(action);</pre><h3>Type Patterns in switch Expression</h3><p>You can match types directly inside a switch expression.</p><pre>object obj = &quot;Hello, World!&quot;;<br><br>string result = obj switch<br>{<br>    int i =&gt; $&quot;It&#39;s an integer: {i}&quot;,<br>    string s =&gt; $&quot;It&#39;s a string: {s}&quot;,<br>    _ =&gt; &quot;Unknown type&quot;<br>};<br><br>Console.WriteLine(result);</pre><h3>Tuple Deconstruction with Pattern Matching</h3><p>You can use deconstruction within a switch expression to pattern match.</p><pre>var tuple = (5, &quot;Hello&quot;);<br><br>string result = tuple switch<br>{<br>    (5, _) =&gt; &quot;Matched first element&quot;,<br>    (_, &quot;Hello&quot;) =&gt; &quot;Matched second element&quot;,<br>    _ =&gt; &quot;No match&quot;<br>};<br><br>Console.WriteLine(result);</pre><h3>Pattern Matching with when Clause</h3><p>The when clause provides additional filtering for matches.</p><pre>int number = 10;<br><br>string result = number switch<br>{<br>    int n when n % 2 == 0 =&gt; &quot;Even number&quot;,<br>    int n when n % 2 != 0 =&gt; &quot;Odd number&quot;,<br>    _ =&gt; &quot;Unknown&quot;<br>};<br><br>Console.WriteLine(result);</pre><h3>Pattern Matching with is not</h3><p>You can reverse pattern checks using is not.</p><pre>object obj = 42;<br><br>if (obj is not string)<br>{<br>    Console.WriteLine(&quot;It&#39;s not a string&quot;);<br>}</pre><h3>Nested Property Pattern Matching</h3><p>You can match objects based on nested property values.</p><pre>var person = new Person { Address = new Address { City = &quot;New York&quot; } };<br><br>if (person is { Address.City: &quot;New York&quot; })<br>{<br>    Console.WriteLine(&quot;Person is from New York&quot;);<br>}</pre><h3>Combining Type Patterns with Relational Patterns</h3><p>Type and relational patterns can be combined.</p><pre>object obj = 42;<br><br>string result = obj switch<br>{<br>    int n when n &gt; 0 =&gt; &quot;Positive number&quot;,<br>    int n when n &lt; 0 =&gt; &quot;Negative number&quot;,<br>    _ =&gt; &quot;Not an integer&quot;<br>};<br><br>Console.WriteLine(result);</pre><h3>Pattern Matching with Arrays</h3><p>Arrays can be matched using patterns as well.</p><pre>int[] numbers = { 1, 2, 3 };<br><br>if (numbers is [1, 2, 3])<br>{<br>    Console.WriteLine(&quot;Matched exact array&quot;);<br>}</pre><h3>Pattern Matching with Discards (_)</h3><p>Discards (_) can be used when you don&#39;t care about a value.</p><pre>(int x, int y) point = (3, 4);<br><br>if (point is (_, 4))<br>{<br>    Console.WriteLine(&quot;Y is 4&quot;);<br>}</pre><h3>Pattern Matching with Custom Types</h3><p>You can extend pattern matching to work with custom types by implementing the Deconstruct method.</p><pre>public class Point<br>{<br>    public int X { get; }<br>    public int Y { get; }<br><br>    public Point(int x, int y)<br>    {<br>        X = x;<br>        Y = y;<br>    }<br><br>    public void Deconstruct(out int x, out int y)<br>    {<br>        x = X;<br>        y = Y;<br>    }<br>}<br><br>var point = new Point(3, 4);<br><br>if (point is (3, _))<br>{<br>    Console.WriteLine(&quot;X is 3&quot;);<br>}</pre><h3>Pattern Matching with Immutable Types</h3><p>Pattern matching works great with immutable types like structs or records.</p><pre>public record Temperature(float Degrees);<br><br>Temperature temp = new Temperature(36.5f);<br><br>string status = temp switch<br>{<br>    { Degrees: &lt; 35 } =&gt; &quot;Hypothermia&quot;,<br>    { Degrees: &gt;= 35 and &lt; 37.5 } =&gt; &quot;Normal&quot;,<br>    { Degrees: &gt;= 37.5 } =&gt; &quot;Fever&quot;,<br>    _ =&gt; &quot;Unknown&quot;<br>};<br><br>Console.WriteLine(status);</pre><h3>Pattern Matching with ExpandoObject (Dynamic Objects)</h3><p>Pattern matching can be used even with dynamic objects like ExpandoObject.</p><pre>dynamic obj = new System.Dynamic.ExpandoObject();<br>obj.Name = &quot;John&quot;;<br><br>if (obj is { Name: &quot;John&quot; })<br>{<br>    Console.WriteLine(&quot;Matched John in dynamic object.&quot;);<br>}</pre><h3>Deeply Nested Property Matching</h3><p>Pattern matching allows you to check deeply nested object properties.</p><pre>var person = new Person<br>{<br>    Name = &quot;Alice&quot;,<br>    Address = new Address { City = &quot;London&quot;, PostalCode = &quot;SW1A 1AA&quot; }<br>};<br><br>if (person is { Address: { City: &quot;London&quot;, PostalCode: &quot;SW1A 1AA&quot; } })<br>{<br>    Console.WriteLine(&quot;Person lives in London with the specified postal code.&quot;);<br>}</pre><h3>Pattern Matching with Interfaces</h3><p>You can pattern match against interface implementations.</p><pre>public interface IShape { }<br>public class Square : IShape { public int SideLength { get; set; } }<br><br>IShape shape = new Square { SideLength = 5 };<br><br>if (shape is Square { SideLength: &gt; 0 })<br>{<br>    Console.WriteLine(&quot;It&#39;s a square with a positive side length.&quot;);<br>}</pre><h3>Pattern Matching in LINQ Queries</h3><p>Pattern matching can be used in LINQ queries to filter or project data.</p><pre>var shapes = new object[] { new Circle { Radius = 5 }, new Square { SideLength = 10 } };<br><br>var circles = shapes<br>    .Where(s =&gt; s is Circle { Radius: &gt; 0 })<br>    .Cast&lt;Circle&gt;()<br>    .ToList();<br><br>circles.ForEach(c =&gt; Console.WriteLine($&quot;Circle with radius {c.Radius}&quot;));</pre><h3>Pattern Matching for Error Handling</h3><p>You can apply pattern matching to handle exceptions in a cleaner way.</p><pre>try<br>{<br>    throw new ArgumentNullException();<br>}<br>catch (Exception ex) when (ex is ArgumentNullException)<br>{<br>    Console.WriteLine(&quot;Caught ArgumentNullException.&quot;);<br>}<br>catch (Exception ex) when (ex is InvalidOperationException)<br>{<br>    Console.WriteLine(&quot;Caught InvalidOperationException.&quot;);<br>}</pre><h3>Advanced List Pattern Matching (C# 12 Preview)</h3><p>Pattern matching in lists can be extended with complex conditions.</p><pre>int[] numbers = { 1, 2, 3, 4, 5 };<br><br>string result = numbers switch<br>{<br>    [1, 2, ..] =&gt; &quot;Starts with 1 and 2&quot;,<br>    [.., 4, 5] =&gt; &quot;Ends with 4 and 5&quot;,<br>    _ =&gt; &quot;No match&quot;<br>};<br><br>Console.WriteLine(result);</pre><p>These are lots of code examples but you can read more on Microsoft’s website:</p><ul><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching">Pattern matching overview</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns">Pattern matching — the is and switch expressions, and operators and, or and not in patterns</a></li><li><a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2019/may/csharp-8-0-pattern-matching-in-csharp-8-0">Pattern Matching in C# 8.0</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8162ea76db6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entity Inheritance in Entity Framework]]></title>
            <link>https://medium.com/@josiahmahachi/entity-inheritance-in-entity-framework-d17f1b928b94?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/d17f1b928b94</guid>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 00:24:46 GMT</pubDate>
            <atom:updated>2024-10-14T00:24:46.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*erY35a9Qtv0M-spA.jpg" /><figcaption>Mastering Inheritance in Entity Framework: A Practical Guide to TPH and TPT with Discriminators</figcaption></figure><p>I recently had the opportunity to implement both <strong>Table-Per-Hierarchy (TPH)</strong> and <strong>Table-Per-Type (TPT)</strong> inheritance strategies in Entity Framework while working on a project involving complex domain models. To effectively handle these models, I used <strong>discriminators</strong> to manage the differences between various entity types within a shared structure. This experience gave me deeper insights into the strengths and limitations of each approach, particularly when it comes to performance, database integrity, and maintainability.</p><p>In this blog, I’ll walk through the practical uses of TPH and TPT, showcasing examples of where each design works best and some cases where they can be problematic. Understanding these strategies can help you make more informed decisions when modeling inheritance in your applications.</p><p>More information on this topic may be found on <a href="https://learn.microsoft.com/en-us/ef/core/modeling/inheritance">Microsoft’s Learn website</a>.</p><h3>Understanding TPH and TPT</h3><h4>Table-Per-Hierarchy (TPH)</h4><p>In TPH, all entities in an inheritance hierarchy are stored in a single table. A discriminator column is used to differentiate between the types.</p><p><strong>Example</strong>: Imagine an application that tracks various types of vehicles: Car, Truck, and Bicycle. All these types inherit from a base class Vehicle. In TPH, a single table named Vehicles will store all the data, with a discriminator column indicating whether a record is a Car, Truck, or Bicycle.</p><h4>Table-Per-Type (TPT)</h4><p>In TPT, each entity type in an inheritance hierarchy is stored in its own table. The base class’s properties are stored in a table, and derived classes have separate tables that contain their specific properties, linked via a foreign key.</p><p><strong>Example</strong>: In the same vehicle tracking application, Vehicle properties would be stored in a Vehicles table, and each derived type (Car, Truck, Bicycle) would have its own table storing specific properties, with a foreign key pointing to the Vehicles table.</p><h3>TPH: Good and Poor Design Examples</h3><h4>Good Design: Minimal Variation Between Entities</h4><p>Consider an application that tracks different types of electronic devices:</p><ul><li><strong>Base Class</strong>: Device</li><li><strong>Derived Classes</strong>: Smartphone, Tablet, Laptop</li></ul><p>All devices have common properties like Brand, Model, and OperatingSystem, and only a few additional properties that differ among types.</p><pre>public class Device<br>{<br>    public int Id { get; set; }<br>    public string Brand { get; set; }<br>    public string Model { get; set; }<br>    public string OperatingSystem { get; set; }<br>}<br><br>public class Smartphone : Device<br>{<br>    public int NumberOfCameras { get; set; }<br>}<br><br>public class Tablet : Device<br>{<br>    public bool HasStylus { get; set; }<br>}<br><br>public class Laptop : Device<br>{<br>    public decimal ScreenSize { get; set; }<br>}<br><br>public class DeviceConfiguration : IEntityTypeConfiguration&lt;Device&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Device&gt; builder)<br>    {<br>        builder.HasDiscriminator&lt;string&gt;(&quot;DeviceType&quot;) // Discriminator<br>               .HasValue&lt;Smartphone&gt;(&quot;Smartphone&quot;)<br>               .HasValue&lt;Tablet&gt;(&quot;Tablet&quot;)<br>               .HasValue&lt;Laptop&gt;(&quot;Laptop&quot;);<br><br>        builder.HasIndex(&quot;DeviceType&quot;); // Indexing the discriminator<br>    }<br>}</pre><p><strong>Why This Works</strong>:</p><ul><li><strong>Simplicity</strong>: The entities have many shared properties, making a single table with a discriminator efficient.</li><li><strong>Query Performance</strong>: Indexed discriminators can improve query performance.</li><li><strong>Maintenance</strong>: Adding new device types is straightforward, requiring minimal schema changes.</li></ul><h4>Poor Design: Significant Variation Between Entities</h4><p>Now consider a scenario where we track various Vehicle types:</p><ul><li><strong>Base Class</strong>: Vehicle</li><li><strong>Derived Classes</strong>: Car, Truck, Bicycle</li></ul><p>Each type has very different properties, leading to a sparse table with many nullable columns.</p><pre>public class Vehicle<br>{<br>    public int Id { get; set; }<br>    public string Make { get; set; }<br>    public string Model { get; set; }<br>}<br><br>public class Car : Vehicle<br>{<br>    public int NumberOfDoors { get; set; }<br>    public decimal EngineCapacity { get; set; }<br>}<br><br>public class Truck : Vehicle<br>{<br>    public decimal PayloadCapacity { get; set; }<br>    public int NumberOfAxles { get; set; }<br>}<br><br>public class Bicycle : Vehicle<br>{<br>    public string Brand { get; set; }<br>    public string Type { get; set; }<br>    public int GearCount { get; set; }<br>}<br><br>public class VehicleConfiguration : IEntityTypeConfiguration&lt;Vehicle&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Vehicle&gt; builder)<br>    {<br>        builder.HasDiscriminator&lt;string&gt;(&quot;VehicleType&quot;) // Discriminator<br>               .HasValue&lt;Car&gt;(&quot;Car&quot;)<br>               .HasValue&lt;Truck&gt;(&quot;Truck&quot;)<br>               .HasValue&lt;Bicycle&gt;(&quot;Bicycle&quot;);<br><br>        builder.HasIndex(&quot;VehicleType&quot;); // Indexing the discriminator<br>    }<br>}</pre><p><strong>Why This Fails</strong>:</p><ul><li><strong>Sparse Data</strong>: The Vehicles table has many columns that are NULL for most records, leading to inefficiency.</li><li><strong>Poor Performance</strong>: The large table with many unused columns can slow down queries and increase storage requirements.</li><li><strong>Complex Maintenance</strong>: Modifying or adding new vehicle types can complicate the table structure further.</li></ul><h3>TPT: Good and Poor Design Examples</h3><h4>Good Design: Significant Variation Between Entities</h4><p>Returning to the Vehicle scenario:</p><ul><li><strong>Base Class</strong>: Vehicle</li><li><strong>Derived Classes</strong>: Car, Truck, Bicycle</li></ul><p>Each type has distinct properties, making TPT a better fit.</p><pre>public class Vehicle<br>{<br>    public int Id { get; set; }<br>    public string Make { get; set; }<br>    public string Model { get; set; }<br>}<br><br>public class Car : Vehicle<br>{<br>    public int NumberOfDoors { get; set; }<br>    public decimal EngineCapacity { get; set; }<br>}<br><br>public class Truck : Vehicle<br>{<br>    public decimal PayloadCapacity { get; set; }<br>    public int NumberOfAxles { get; set; }<br>}<br><br>public class Bicycle : Vehicle<br>{<br>    public string Brand { get; set; }<br>    public string Type { get; set; }<br>    public int GearCount { get; set; }<br>}<br><br>public class VehicleConfiguration : IEntityTypeConfiguration&lt;Vehicle&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Vehicle&gt; builder)<br>    {<br>        builder.ToTable(&quot;Vehicles&quot;);<br>    }<br>}<br><br>public class CarConfiguration : IEntityTypeConfiguration&lt;Car&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Car&gt; builder)<br>    {<br>        builder.ToTable(&quot;Cars&quot;);<br>        builder.Property(c =&gt; c.NumberOfDoors).IsRequired();<br>        builder.Property(c =&gt; c.EngineCapacity).IsRequired();<br>    }<br>}<br><br>public class TruckConfiguration : IEntityTypeConfiguration&lt;Truck&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Truck&gt; builder)<br>    {<br>        builder.ToTable(&quot;Trucks&quot;);<br>        builder.Property(t =&gt; t.PayloadCapacity).IsRequired();<br>        builder.Property(t =&gt; t.NumberOfAxles).IsRequired();<br>    }<br>}<br><br>public class BicycleConfiguration : IEntityTypeConfiguration&lt;Bicycle&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Bicycle&gt; builder)<br>    {<br>        builder.ToTable(&quot;Bicycles&quot;);<br>        builder.Property(b =&gt; b.Brand).IsRequired();<br>        builder.Property(b =&gt; b.Type).IsRequired();<br>        builder.Property(b =&gt; b.GearCount).IsRequired();<br>    }<br>}</pre><p><strong>Why This Works</strong>:</p><ul><li><strong>Data Integrity</strong>: Each type has its own table, enforcing specific constraints and improving data integrity.</li><li><strong>Efficient Storage</strong>: No wasted space due to NULL values. Each table stores only relevant properties.</li><li><strong>Clear Schema</strong>: The schema reflects the domain model accurately, making it easier to understand and maintain.</li></ul><h4>Poor Design: Minimal Variation Between Entities</h4><p>Now, let’s revisit the Device scenario with TPT:</p><pre>public class Device<br>{<br>    public int Id { get; set; }<br>    public string Brand { get; set; }<br>    public string Model { get; set; }<br>    public string OperatingSystem { get; set; }<br>}<br><br>public class Smartphone : Device<br>{<br>    public int NumberOfCameras { get; set; }<br>}<br><br>public class Tablet : Device<br>{<br>    public bool HasStylus { get; set; }<br>}<br><br>public class Laptop : Device<br>{<br>    public decimal ScreenSize { get; set; }<br>}<br><br>public class DeviceConfiguration : IEntityTypeConfiguration&lt;Device&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Device&gt; builder)<br>    {<br>        builder.ToTable(&quot;Devices&quot;);<br>    }<br>}<br><br>public class SmartphoneConfiguration : IEntityTypeConfiguration&lt;Smartphone&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Smartphone&gt; builder)<br>    {<br>        builder.ToTable(&quot;Smartphones&quot;);<br>        builder.Property(s =&gt; s.NumberOfCameras).IsRequired();<br>    }<br>}<br><br>public class TabletConfiguration : IEntityTypeConfiguration&lt;Tablet&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Tablet&gt; builder)<br>    {<br>        builder.ToTable(&quot;Tablets&quot;);<br>        builder.Property(t =&gt; t.HasStylus).IsRequired();<br>    }<br>}<br><br>public class LaptopConfiguration : IEntityTypeConfiguration&lt;Laptop&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Laptop&gt; builder)<br>    {<br>        builder.ToTable(&quot;Laptops&quot;);<br>        builder.Property(l =&gt; l.ScreenSize).IsRequired();<br>    }<br>}</pre><p><strong>Why This Fails</strong>:</p><ul><li><strong>Complex Queries</strong>: Retrieving a list of devices requires joins across multiple tables, complicating the queries and potentially impacting performance.</li><li><strong>Overhead</strong>: Each derived type requires its own table and joins, adding unnecessary complexity when most properties are shared.</li><li><strong>Maintenance</strong>: Adding new device types or modifying properties across multiple tables can be cumbersome.</li></ul><h3>Pros and Cons of TPH and TPT</h3><h4>TPH Pros:</h4><ul><li><strong>Simpler Schema</strong>: One table for the entire hierarchy.</li><li><strong>Performance</strong>: No joins are needed to retrieve all fields, leading to potentially faster reads.</li><li><strong>Ease of Maintenance</strong>: Adding new types is straightforward.</li></ul><h4>TPH Cons:</h4><ul><li><strong>Sparse Data</strong>: Can lead to many nullable columns, wasting space.</li><li><strong>Data Integrity</strong>: Hard to enforce type-specific constraints.</li><li><strong>Performance Issues</strong>: Large tables with many columns can degrade performance.</li></ul><h4>TPT Pros:</h4><ul><li><strong>Data Integrity</strong>: Each table enforces its own constraints, improving data consistency.</li><li><strong>Efficient Storage</strong>: No unused columns, leading to more compact and efficient tables.</li><li><strong>Clearer Schema</strong>: The database schema closely mirrors the object model, making it easier to understand.</li></ul><h4>TPT Cons:</h4><ul><li><strong>Complexity</strong>: More tables and potential for complex joins.</li><li><strong>Query Performance</strong>: Joins are required to retrieve complete data, which can impact performance.</li><li><strong>Maintenance Overhead</strong>: Adding new types or modifying existing ones can be more cumbersome.</li></ul><h3>Conclusion</h3><p>The choice between TPH and TPT in Entity Framework depends on your specific application needs. If your entities share many properties, and you prioritise simplicity and performance, TPH might be the better choice. However, if your entities have significant differences, and you need to enforce data integrity and clarity in your schema, TPT is likely the better option. By carefully evaluating the pros and cons of each approach, you can make an informed decision that best suits your application’s requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d17f1b928b94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Feature Flags in ASP.NET]]></title>
            <link>https://medium.com/@josiahmahachi/implementing-feature-flags-in-asp-net-c56e647cf79e?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/c56e647cf79e</guid>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 00:22:05 GMT</pubDate>
            <atom:updated>2024-10-17T00:20:20.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arS-aJAXKvcEea6-gGtqAQ.png" /><figcaption>Implementing Feature Flags in ASP.NET: A Practical Guide for Blazor UI and Controllers</figcaption></figure><p>Feature flags, also known as feature toggles, are a nifty mechanism in modern software development, enabling devs to deploy new features gradually, test features in production environments, and control feature access dynamically.</p><p>I recently discovered that ASP.NET provides robust support for implementing feature flags, especially with the Microsoft.FeatureManagement.AspNetCore package. This blog post will guide you through setting up and using feature flags in an ASP.NET application.</p><p>If you need more information, read through <a href="https://learn.microsoft.com/en-us/azure/azure-app-configuration/use-feature-flags-dotnet-core">this article</a> on the Microsoft Learn website, and be as impressed as I was.</p><blockquote>I will be quick, though, to offer a disclaimer and state that feature flags have their own complexity, and usually <a href="https://learn.microsoft.com/en-us/training/modules/implement-blue-green-deployment-feature-toggles/5-describe-feature-toggle-maintenance">increase your technical debt</a>.</blockquote><h3>Why Use Feature Flags?</h3><p>Feature flags offer several benefits in software development, such as:</p><ul><li><strong>Incremental Deployment</strong>: Deploy features to a subset of users before rolling them out to everyone.</li><li><strong>A/B Testing</strong>: Test different versions of a feature to gather feedback and metrics.</li><li><strong>Risk Mitigation</strong>: Quickly disable a feature if it causes issues in production without rolling back the entire deployment.</li><li><strong>Continuous Integration</strong>: Keep code in the main branch clean while working on features behind flags.</li></ul><h3>Setting Up Feature Flags in ASP.NET</h3><p>To begin, you need to install the Microsoft.FeatureManagement.AspNetCore NuGet package in your ASP.NET project. This package allows easy management of feature flags within an ASP.NET Core application.</p><pre>dotnet add package Microsoft.FeatureManagement.AspNetCore</pre><p>Once installed, configure the feature flags in appsettings.json:</p><pre>{<br>  &quot;FeatureManagement&quot;: {<br>    &quot;NewFeature&quot;: true,<br>    &quot;BetaFeature&quot;: false<br>  }<br>}</pre><h3>Configuration in Startup.cs or Program.cs</h3><p>In Startup.cs or Program.cs, ensure that the feature management services are registered by adding the following lines:</p><pre>using Microsoft.FeatureManagement;</pre><pre>public class Startup<br>{<br>    public void ConfigureServices(IServiceCollection services)<br>    {<br>        services.AddFeatureManagement();<br>        services.AddControllersWithViews();<br>        services.AddRazorPages();<br>    }</pre><pre>    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>    {<br>        // other configurations<br>        app.UseRouting();<br>        app.UseEndpoints(endpoints =&gt;<br>        {<br>            endpoints.MapControllers();<br>            endpoints.MapBlazorHub();<br>        });<br>    }<br>}</pre><h3>Using Feature Flags in Blazor UI</h3><p>In a Blazor application, you may want to display different UI components based on the state of a feature flag. This can be done by injecting the IFeatureManager service into your Blazor components and checking the feature flag&#39;s status.</p><p>Here’s an example of how to toggle UI components in a Blazor page based on a feature flag:</p><pre>@page &quot;/featureflag&quot;<br>@inject IFeatureManager FeatureManager</pre><pre>@if (isFeatureEnabled)<br>{<br>    &lt;h3&gt;New Feature is Enabled!&lt;/h3&gt;<br>    &lt;p&gt;This is the new feature content visible only when the flag is on.&lt;/p&gt;<br>}<br>else<br>{<br>    &lt;h3&gt;New Feature is Disabled&lt;/h3&gt;<br>    &lt;p&gt;This is the fallback content for when the feature flag is off.&lt;/p&gt;<br>}<br>@code {<br>    private bool isFeatureEnabled;<br>    protected override async Task OnInitializedAsync()<br>    {<br>        isFeatureEnabled = await FeatureManager.IsEnabledAsync(&quot;NewFeature&quot;);<br>    }<br>}</pre><p>In the above example, the UI adjusts dynamically based on the value of the NewFeature flag. If the flag is enabled, the new content is shown; otherwise, the fallback content appears.</p><h3>Using Feature Flags in Controllers</h3><p>In ASP.NET Core MVC or API controllers, feature flags can be used to control logic flow or responses based on feature availability. You can inject IFeatureManager directly into your controller to determine the status of specific features.</p><p>Here’s an example of using a feature flag in a controller action:</p><pre>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.FeatureManagement;<br><br>public class FeatureController : Controller<br>{<br>    private readonly IFeatureManager _featureManager;<br>    public FeatureController(IFeatureManager featureManager)<br>    {<br>        _featureManager = featureManager;<br>    }<br>    [HttpGet(&quot;/feature&quot;)]<br>    public async Task&lt;IActionResult&gt; GetFeature()<br>    {<br>        if (await _featureManager.IsEnabledAsync(&quot;NewFeature&quot;))<br>        {<br>            return Ok(&quot;New Feature is enabled!&quot;);<br>        }<br>        return Ok(&quot;New Feature is disabled.&quot;);<br>    }<br>}</pre><p>Here, the controller checks whether the NewFeature flag is enabled and returns a different response accordingly. This allows you to alter the behaviour of your application based on feature toggles without modifying the underlying code logic extensively.</p><h3>Dynamic Feature Flag Evaluation</h3><p>ASP.NET’s feature management system supports dynamic feature flag evaluation based on custom conditions, such as user roles, specific request parameters, or environment variables. For example, you can create a custom feature filter to enable a feature only for administrators:</p><pre>public class AdminFeatureFilter : IFeatureFilter<br>{<br>    public Task&lt;bool&gt; EvaluateAsync(FeatureFilterEvaluationContext context)<br>    {<br>        // Check if the user is in the Admin role<br>        var isAdmin = // your logic to check if user is admin;<br>        return Task.FromResult(isAdmin);<br>    }<br>}</pre><p>You can then apply this custom filter to a feature in your appsettings.json:</p><pre>{<br>  &quot;FeatureManagement&quot;: {<br>    &quot;NewFeature&quot;: {<br>      &quot;EnabledFor&quot;: [<br>        {<br>          &quot;Name&quot;: &quot;AdminFeatureFilter&quot;<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>I have only but touched on a few features of the Feature Flags in C#. I will not go through all of them, including adding feature flag evaluation to your middleware. Find more information <a href="https://learn.microsoft.com/en-us/azure/azure-app-configuration/use-feature-flags-dotnet-core">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c56e647cf79e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Deployment Strategies for Modern Applications]]></title>
            <link>https://medium.com/@josiahmahachi/exploring-deployment-strategies-for-modern-applications-c8dd48878868?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8dd48878868</guid>
            <category><![CDATA[canary-deployments]]></category>
            <category><![CDATA[feature-flags]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 23:18:24 GMT</pubDate>
            <atom:updated>2024-10-17T01:20:59.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ch4UnvYEPuPil6uw46OSpA.jpeg" /><figcaption>Exploring the Most Effective Deployment Strategies for Modern Applications</figcaption></figure><p>In today’s fast-paced digital environment, deploying software updates efficiently and safely is critical to maintaining uptime and ensuring a seamless user experience. Whether it’s rolling out a new feature, patching bugs, or updating system architecture, selecting the right deployment strategy can make or break the process. My boss recently sent the above image to us in a WhatsApp group and I thought I’d write something about it. This blog, I explore the most popular deployment strategies, highlighting their strengths and ideal use cases.</p><h3>1. Blue/Green Deployment</h3><p><strong>Blue/Green Deployment</strong> is a widely adopted strategy that minimises downtime and simplifies rollback procedures. The process involves maintaining two identical environments — referred to as <em>Blue</em> (the current active environment) and <em>Green</em> (the environment where the new version is deployed).</p><ul><li><strong>Process</strong>: The new version of the application is deployed to the Green environment while Blue continues to handle production traffic. Once the new version is tested and verified, traffic is switched from Blue to Green. If the new version encounters issues, the process can easily be reversed by switching traffic back to the Blue environment.</li><li><strong>Best for</strong>: Systems requiring zero downtime, large-scale applications, and scenarios where rollback needs to be instantaneous.</li><li><strong>Advantages</strong>: Seamless cutover, simplified rollback, and minimal impact on users.</li></ul><p>Another way to think about Blue/Green deployments is when you have a production and staging environments. When you deploy to staging, and all is well, you can essentially swap staging to be the new production. If things don’t go so well, you can quickly “swap” them around again.</p><h3>2. Canary Deployment</h3><p><strong>Canary Deployment</strong> allows for a gradual rollout of new versions by directing a small percentage of users (the “canary” group) to the updated system while the majority continue using the existing version.</p><ul><li><strong>Process</strong>: Initially, a small fraction of users are routed to the new version. Their interactions are closely monitored for performance and errors. If the system performs as expected, traffic is incrementally increased until the entire user base is using the new version.</li><li><strong>Best for</strong>: Systems where stability is critical, especially when new features may introduce risk or require validation under real-world conditions.</li><li><strong>Advantages</strong>: Controlled exposure to risk, ability to monitor and gather feedback, and safer incremental rollouts.</li></ul><p>Canary releases can be implemented using a combination of <a href="https://medium.com/@josiahmahachi/implementing-feature-flags-in-asp-net-c56e647cf79e">feature toggles</a>, traffic routing, and deployment slots.</p><h3>3. A/B Testing</h3><p>While not purely a deployment strategy, <strong>A/B Testing</strong> is a powerful technique for evaluating the effectiveness of new features by splitting users into groups, with each group interacting with different versions of the software.</p><ul><li><strong>Process</strong>: Users are divided into two or more segments, each receiving a distinct version of the application (e.g., Version A or Version B). Performance metrics and user feedback are collected to determine which version performs better in terms of engagement, usability, or other key performance indicators.</li><li><strong>Best for</strong>: Experimenting with new features, validating user preferences, and optimising user experience.</li><li><strong>Advantages</strong>: Data-driven decision-making, real-time comparison of features, and the ability to quickly validate assumptions.</li></ul><h3>4. Feature Flagging</h3><p><strong>Feature Flags</strong> offer a high level of control by allowing specific features to be turned on or off without requiring a redeployment. We recently implemented Feature Flags to turn of some features in production which had not been fully tested. Find my Feature Flag blog <a href="https://medium.com/@josiahmahachi/implementing-feature-flags-in-asp-net-c56e647cf79e">here</a>.</p><ul><li><strong>Process</strong>: New features are deployed behind a flag or toggle. A feature flag allows developers to enable the feature for a select group of users, such as beta testers, and collect feedback before releasing it to the broader audience. If issues arise, the feature can be quickly disabled without needing to roll back the entire deployment.</li><li><strong>Best for</strong>: Continuous deployment environments, where quick toggling of features is needed, or when testing new functionality in production.</li><li><strong>Advantages</strong>: Rapid response to issues, flexibility in feature rollout, and reduced need for redeployment.</li></ul><h3>5. Rolling Deployment</h3><p><strong>Rolling Deployment</strong> is an incremental approach where the new version is gradually rolled out across servers or clusters over time, ensuring that the system remains available throughout the process.</p><ul><li><strong>Process</strong>: The deployment occurs in stages, with each stage replacing a subset of servers running the old version with the new version. This method ensures that a portion of the system remains available on the old version while the new version is tested in production.</li><li><strong>Best for</strong>: Large distributed systems, cloud-native applications, and environments where avoiding full downtime is crucial.</li><li><strong>Advantages</strong>: Minimises risk by limiting the scope of change at any given time, reduces downtime, and allows for a phased transition.</li></ul><h3>Choosing the Right Strategy</h3><p>Each deployment strategy has its own strengths and trade-offs. Understanding the nature of your application, its users, and the operational environment is essential to selecting the best approach:</p><ul><li><strong>Blue/Green Deployment</strong> is ideal for systems requiring high availability and instant rollback.</li><li><strong>Canary Deployment</strong> offers a safer way to test updates with real users while limiting exposure.</li><li><strong>A/B Testing</strong> is suited for optimising user experience and validating changes through data-driven insights.</li><li><strong>Feature Flags</strong> give you the flexibility to manage feature rollouts and handle production issues dynamically.</li><li><strong>Rolling Deployment</strong> is highly effective for large-scale systems where downtime is not an option.</li></ul><p>In a world where users expect continuous delivery of new features and improvements without disruption, adopting the appropriate deployment strategy is key to maintaining both innovation and reliability.</p><p>By leveraging these strategies, development teams can ensure smoother rollouts, minimise risk, and respond quickly to unforeseen issues — all while enhancing the overall user experience. The choice of strategy should always align with the business needs, technical architecture, and risk tolerance of the organisation.</p><p>Until the next one, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8dd48878868" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Transactions in .NET: A Guide to TransactionScope and Distributed Transactions]]></title>
            <link>https://medium.com/@josiahmahachi/understanding-transactions-in-net-a-guide-to-transactionscope-and-distributed-transactions-4c84564d2857?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c84564d2857</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[acid]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 17:41:46 GMT</pubDate>
            <atom:updated>2024-10-10T17:41:46.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Transactions in .NET: A Guide to TransactionScope and Distributed Transactions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HuUmixpCALNDUU-v.jpeg" /><figcaption>Understanding Transactions in .NET: A Guide to TransactionScope and Distributed Transactions</figcaption></figure><p>In the world of software development, <strong>transactions</strong> play a crucial role in maintaining <strong>data integrity and consistency</strong> across different operations, especially in systems dealing with multiple resources, such as databases and external services. When working in a .NET environment, as developers , we often rely on the TransactionScope class to manage transactions efficiently. This post will explore why transactions are essential, when to use them, the potential pitfalls you may encounter, and the settings required for distributed transactions. We will also walk through an example that demonstrates the use of transactions across different repositories.</p><h3>Why Transactions Are Important</h3><p>A <strong>transaction</strong> is a sequence of operations performed as a single logical unit of work. It ensures the <strong>ACID</strong> properties — Atomicity, Consistency, Isolation, and Durability — which guarantee that:</p><ul><li><strong>Atomicity:</strong> Either all operations in a transaction complete successfully, or none do. There are no partial results.</li><li><strong>Consistency:</strong> The system moves from one valid state to another, ensuring that constraints (such as database constraints) are maintained.</li><li><strong>Isolation:</strong> Transactions are isolated from one another until they are completed.</li><li><strong>Durability:</strong> Once a transaction is committed, its results are permanent, even in the event of a system crash.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*Dpd1lXhN37853M29.png" /><figcaption>ACID Properties</figcaption></figure><p>Transactions are particularly critical in multi-step processes where failure in one step could lead to an inconsistent or erroneous state across the system. Without transactions, systems are prone to <strong>data corruption, partial updates, and inconsistencies</strong>, especially when dealing with multiple data sources or services.</p><h3>When to Use Transactions</h3><p>You should use transactions in any scenario where you need to guarantee that multiple operations either succeed or fail together. Common use cases include:</p><ul><li><strong>Financial Systems:</strong> Transferring funds between accounts where both the debit and credit must succeed.</li><li><strong>Order Management Systems:</strong> Updating inventory, order status, and customer information atomically.</li><li><strong>Batch Processing:</strong> Executing multiple database insertions, updates, or deletions as part of a larger batch.</li></ul><p>Transactions are also essential when:</p><ol><li><strong>Multiple Databases</strong> are involved.</li><li><strong>External APIs or Services</strong> need to be updated atomically with the database.</li><li><strong>Complex Workflows</strong> where failure at any stage should trigger a rollback of all operations.</li></ol><h3>TransactionScope in .NET</h3><p>In .NET, the TransactionScope class provides a simple way to handle transactions. It ensures that all the code within its scope is part of a single transaction. Here&#39;s a basic example:</p><pre>using (TransactionScope scope = new TransactionScope())<br>{<br>    // Perform database operations<br>    repository1.SaveChanges();<br><br>    // Perform operations in another database or service<br>    repository2.SaveChanges();<br><br>    // Commit the transaction<br>    scope.Complete();<br>}</pre><p>The transaction will automatically roll back if scope.Complete() is not called, or if an exception occurs. This ensures atomicity and consistency. Microsoft strongly suggests that scope.Complete() be the last statement in the transaction.</p><h3>Distributed Transactions: A Special Case</h3><p>When dealing with multiple transactional resources, such as different databases or services, a <strong>distributed transaction</strong> is required. The TransactionScope class in .NET can automatically escalate to a distributed transaction, which is managed by the <strong>Microsoft Distributed Transaction Coordinator (MSDTC)</strong>.</p><p>A typical use case for a distributed transaction involves updating data in multiple databases. Here’s an example:</p><pre>using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))<br>{<br>    // Update database A<br>    await repositoryA.SaveChangesAsync();<br><br>    // Update database B (or call an external service)<br>    await repositoryB.SaveChangesAsync();<br><br>    // Commit the transaction<br>    scope.Complete();<br>}</pre><h4>Required Settings for Distributed Transactions</h4><p>For distributed transactions to work correctly, both the local and remote systems must be configured properly:</p><p><strong>1. Ensure Distributed Transaction Coordinator (DTC) is configured on both servers:</strong></p><ul><li>Open the “Component Services” from the Administrative Tools. Expand “Component Services” -&gt; “Computers” -&gt; “My Computer” -&gt; “Distributed Transaction Coordinator” -&gt; “Local DTC”.</li><li>Right-click “Local DTC” and select “Properties”.</li><li>Go to the “Security” tab and ensure that “Network DTC Access”, “Allow Inbound”, and “Allow Outbound” are checked.</li><li>Ensure “Mutual Authentication Required” or “No Authentication Required” is selected based on your network security configuration. Restart the DTC service if you make any changes.</li><li>Configure firewalls to allow DTC traffic.</li></ul><p><strong>2. Static Ports</strong>: If your network security policies require it, you can configure MSDTC to use a static port by adding the HKEY_LOCAL_MACHINE\Software\Microsoft\MSDTC\ServerTcpPort registry key.</p><p><strong>3. SQL Server Permissions</strong>: Ensure that the service account accessing the databases has the required permissions, such as SELECT, UPDATE, DELETE, and INSERT.</p><p>Without these settings, distributed transactions may fail with communication issues, or you may encounter errors like System.Runtime.InteropServices.COMException: The MSDTC transaction manager was unable to pull the transaction.</p><h3>Potential Pitfalls</h3><p>While transactions provide a robust mechanism to ensure consistency, they can introduce certain challenges:</p><ul><li><strong>Performance Overhead</strong>: Transactions, especially distributed ones, add overhead because they require locking of resources and coordination between multiple systems. This can lead to slower performance, particularly in high-latency environments.</li><li><strong>Deadlocks</strong>: Improper transaction management can lead to deadlocks, where two or more transactions wait indefinitely for each other to release locks.</li><li><strong>Escalation to Distributed Transactions</strong>: In some cases, simple transactions may be escalated to distributed transactions unnecessarily, which could impact performance.</li><li><strong>MSDTC Configuration Issues</strong>: Configuring MSDTC across multiple servers can be tricky. Communication problems between MSDTC services often lead to runtime failures that are difficult to diagnose.</li></ul><h3>Conclusion</h3><p>Transactions are an essential tool for ensuring the consistency and integrity of operations in .NET applications, particularly when dealing with multiple resources or complex workflows. By using TransactionScope, developers can ensure that all operations within a scope are treated as a single atomic unit. However, when working with distributed resources, it is crucial to configure MSDTC properly and be aware of the potential performance impacts.</p><p>Understanding when and how to use transactions, as well as the necessary configurations, will help ensure the reliability and efficiency of your application.</p><p>For further reading, check out the official documentation on <a href="https://learn.microsoft.com/en-us/dotnet/framework/data/transactions/implementing-an-implicit-transaction-using-transaction-scope">TransactionScope</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c84564d2857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Search Queries in ASP.NET & Typescript]]></title>
            <link>https://medium.com/@josiahmahachi/dynamic-search-queries-in-asp-net-typescript-9449c3b8e323?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/9449c3b8e323</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 12:24:08 GMT</pubDate>
            <atom:updated>2024-01-28T12:24:08.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oXH3gxeeOd3r4KOcOW-wXQ.jpeg" /><figcaption>Building Dynamic Search Queries in ASP.NET with Angular</figcaption></figure><p>Angular is probably still my favourite SPA. I use it a lot with ASP.NET when building admin portals and when learning new tricks. One of the things I often find myself doing is searching for data. In this blog, I am going to assume you are already familiar with both ASP.NET and Angular. I’m also going to abstract a lot of detail so that my point is clear.</p><p>Let us imagine we need to search for documents submitted by different organisations and that we have built a UI which looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gay965DBUiMqoFHAxMyG9g.png" /><figcaption>Search documents form.</figcaption></figure><p>Typically, when the page loads, we would also fetch the records to show initially without using a filter. In this case, we also want to search for matching records whenever any of the form controls’ value changes.</p><pre>  private initForms = () =&gt; {<br>    this.searchForm = this.formBuilder.group({<br>      organisationId: [&quot;&quot;, []],<br>      typeId: [&quot;&quot;, []],<br>      periodId: [&quot;&quot;, []],<br>      startDate: [&quot;&quot;, []],<br>      endDate: [&quot;&quot;, []],<br>    });<br><br>    this.submitted = false;<br>  }<br>  <br>  public onSearchSubmit = () =&gt; {<br>    this.submitted = true;<br><br>    if (this.searchForm.invalid) return;<br><br>    this.submissionService.search(this.searchForm)<br>      .subscribe((data) =&gt; {<br>        this.submissions = data;<br>      })<br>  }</pre><pre>&lt;form [formGroup]=&quot;searchForm&quot; (ngSubmit)=&quot;onSearchSubmit()&quot;&gt;<br>    &lt;div class=&quot;row&quot;&gt;<br>        &lt;div class=&quot;col-xl-8 col-md-6&quot;&gt;<br>            &lt;div class=&quot;row&quot;&gt;<br>                &lt;div class=&quot;col-xl-4 col-md-4 col-sm-12&quot;&gt;<br>                    &lt;div class=&quot;card card-animate&quot;&gt;<br>                        &lt;div class=&quot;card-body&quot;&gt;<br>                            &lt;div class=&quot;d-flex align-items-center&quot;&gt;<br>                                &lt;div class=&quot;flex-grow-1 overflow-hidden&quot;&gt;<br>                                    &lt;p class=&quot;text-uppercase fw-medium text-muted text-truncate mb-0&quot;&gt;<br>                                        Organisation<br>                                    &lt;/p&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;form-group mt-4&quot;&gt;<br>                                &lt;select class=&quot;form-control&quot; id=&quot;organisationId&quot; name=&quot;organisationId&quot; formControlName=&quot;organisationId&quot;<br>                                    (change)=&quot;onSearchSubmit()&quot;&gt;<br>                                    &lt;option value=&quot;&quot;&gt;All&lt;/option&gt;<br>                                    &lt;option *ngFor=&quot;let organisation of organisations&quot; [value]=&quot;organisation.id&quot;&gt;<br>                                        {{organisation.name}}<br>                                    &lt;/option&gt;<br>                                &lt;/select&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;col-xl-4 col-md-4 col-sm-12&quot;&gt;<br>                    &lt;div class=&quot;card card-animate&quot;&gt;<br>                        &lt;div class=&quot;card-body&quot;&gt;<br>                            &lt;div class=&quot;d-flex align-items-center&quot;&gt;<br>                                &lt;div class=&quot;flex-grow-1 overflow-hidden&quot;&gt;<br>                                    &lt;p class=&quot;text-uppercase fw-medium text-muted text-truncate mb-0&quot;&gt;<br>                                        Document Type<br>                                    &lt;/p&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;form-group mt-4&quot;&gt;<br>                                &lt;select class=&quot;form-control&quot; id=&quot;typeId&quot; name=&quot;typeId&quot; formControlName=&quot;typeId&quot;<br>                                    (change)=&quot;onSearchSubmit()&quot;&gt;<br>                                    &lt;option value=&quot;&quot;&gt;All&lt;/option&gt;<br>                                    &lt;option *ngFor=&quot;let type of types&quot; [value]=&quot;type.id&quot;&gt;<br>                                        {{type.name}}<br>                                    &lt;/option&gt;<br>                                &lt;/select&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;col-xl-4 col-md-4 col-sm-12&quot;&gt;<br>                    &lt;div class=&quot;card card-animate&quot;&gt;<br>                        &lt;div class=&quot;card-body&quot;&gt;<br>                            &lt;div class=&quot;d-flex align-items-center&quot;&gt;<br>                                &lt;div class=&quot;flex-grow-1 overflow-hidden&quot;&gt;<br>                                    &lt;p class=&quot;text-uppercase fw-medium text-muted text-truncate mb-0&quot;&gt;<br>                                        Financial Year<br>                                    &lt;/p&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div class=&quot;form-group mt-4&quot;&gt;<br>                                &lt;select class=&quot;form-control&quot; id=&quot;periodId&quot; name=&quot;periodId&quot; formControlName=&quot;periodId&quot;<br>                                    (change)=&quot;onSearchSubmit()&quot;&gt;<br>                                    &lt;option value=&quot;&quot;&gt;All&lt;/option&gt;<br>                                    &lt;option *ngFor=&quot;let period of periods&quot; [value]=&quot;period.id&quot;&gt;<br>                                        {{period.name}}<br>                                    &lt;/option&gt;<br>                                &lt;/select&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;col-xl-4 col-md-6&quot;&gt;<br>            &lt;div class=&quot;card card-animate&quot;&gt;<br>                &lt;div class=&quot;card-body&quot;&gt;<br>                    &lt;div class=&quot;d-flex align-items-center&quot;&gt;<br>                        &lt;div class=&quot;flex-grow-1 overflow-hidden&quot;&gt;<br>                            &lt;p class=&quot;text-uppercase fw-medium text-muted text-truncate mb-0&quot;&gt;<br>                                Date Submitted<br>                            &lt;/p&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;row&quot;&gt;<br>                        &lt;div class=&quot;col-md-6 col-sm-12 mt-4&quot;&gt;<br>                            &lt;div class=&quot;form-group&quot;&gt;<br>                                &lt;input class=&quot;form-control&quot; type=&quot;date&quot; id=&quot;startDate&quot; name=&quot;startDate&quot; formControlName=&quot;startDate&quot; (change)=&quot;onSearchSubmit()&quot;&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                        &lt;div class=&quot;col-md-6 col-sm-12 mt-4&quot;&gt;<br>                            &lt;div class=&quot;form-group&quot;&gt;<br>                                &lt;input class=&quot;form-control&quot; type=&quot;date&quot; id=&quot;endDate&quot; name=&quot;endDate&quot; formControlName=&quot;endDate&quot; (change)=&quot;onSearchSubmit()&quot;&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/form&gt;</pre><p>In the SubmissionsService, we have the following code which calls a handy helper method:</p><pre>export class SubmissionService extends ApiService&lt;Submission&gt; {<br>  constructor(<br>    private http: HttpClient,<br>  ) {<br>    super(http, &quot;Submissions&quot;);<br>  }<br><br>  public search = (form: UntypedFormGroup): Observable&lt;Submission[]&gt; =&gt; {<br>    const queryString = convertFormToQueryString(form)<br>    return this.getUrl(`Search?${queryString}`)<br>  }<br>}</pre><pre>import { UntypedFormGroup } from &#39;@angular/forms&#39;;<br><br>export const convertFormToQueryString = (form: UntypedFormGroup): string =&gt; {<br>    let queryString = &#39;&#39;;<br>    Object.keys(form.controls).forEach((key, index) =&gt; {<br>        const value = form.controls[key].value;<br>        if (value !== null &amp;&amp; value !== undefined &amp;&amp; value !== &#39;&#39;) {<br>            const encoded = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;<br>            queryString += (queryString === &#39;&#39;) ? encoded : `&amp;${encoded}`;<br>        }<br>    });<br>    return queryString;<br>}</pre><blockquote>Please note that I have an ApiService, which is responsible for all the calls to the API. It abstracts the http functionality from the SubmissionService.</blockquote><p>Depending on the values of the form, convertFormToQueryString returns a “query string” which we can then append to our URL. The API endpoint then accepts zero or more query string parameters in a nifty way:</p><pre>[HttpGet(&quot;Search&quot;)]<br>public async Task&lt;ActionResult&lt;IEnumerable&lt;SubmissionDto&gt;&gt;&gt; Search([FromQuery] SubmissionSearchParams query)<br>{<br>    try<br>    {<br>        var submissions = await _service.GetAllAsync(query);<br>        var result = _mapper.Map&lt;IEnumerable&lt;SubmissionDto&gt;&gt;(submissions);<br><br>        return Ok(result);<br>    }<br>    catch (Exception ex)<br>    {<br>        _logger.LogError(ex.Message, ex);<br><br>        return BadRequest();<br>    }<br>}</pre><p>Take note of the [FromQuery] SubmissionSearchParams query. The [FromQuery] attribute essentially maps all query parameters to the POCO SubmissionSearchParams:</p><pre>public class SubmissionSearchParams<br>{<br>    public int? OrganisationId { get; set; }<br>    public int? TypeId { get; set; }<br>    public int? PeriodId { get; set; }<br>    public DateTime? StartDate { get; set; }<br>    public DateTime? EndDate { get; set; }<br>}</pre><p>All the properties of this class are optional. The GetAllAsync method, then accepts a parameter, and using the repository pattern, get all matching records:</p><pre>public async Task&lt;IEnumerable&lt;Submission&gt;&gt; GetAllAsync(SubmissionSearchParams query)<br>{<br>    var submissions = await _repository.GetWhereAsync(query.ToPredicate());<br><br>    return submissions;<br>}</pre><p>The repository function is defined as:</p><pre>public async virtual Task&lt;IEnumerable&lt;T&gt;&gt; GetWhereAsync&lt;T&gt;(Expression&lt;Func&lt;T, bool&gt;&gt; predicate, params Expression&lt;Func&lt;T, object&gt;&gt;[] includes) where T : EntityBase<br>{<br>    IQueryable&lt;T&gt; query = _dbContext.Set&lt;T&gt;().Where(x =&gt; x.IsDeleted == false);<br><br>    foreach (var include in includes)<br>    {<br>        query = query.Include(include);<br>    }<br><br>    return await query.Where(predicate).ToListAsync();<br>}</pre><p>If you have a keen eye, you may have already noticed that I am calling .ToPredicate() function on the SubmissionSearchParams. You may have notices also that GetWhereAsync&lt;T&gt; expects a type parameter which I am not passing. ToPredicate() function is a helper function that I created to convert the value of SubmissionSearchParams into a series of where statements (predicate), which I can then pass to the GetWhereAsync&lt;T&gt;().</p><p>Since I am not returning a generic type from the ToPredicate() function, there is no more need to pass a type parameter to GetWhereAsync&lt;T&gt;().</p><p>The complete class now looks like this:</p><pre>public class SubmissionSearchParams<br>{<br>    public int? OrganisationId { get; set; }<br>    public int? TypeId { get; set; }<br>    public int? PeriodId { get; set; }<br>    public DateTime? StartDate { get; set; }<br>    public DateTime? EndDate { get; set; }<br><br>    public Expression&lt;Func&lt;Submission, bool&gt;&gt; ToPredicate()<br>    {<br>        Expression&lt;Func&lt;Submission, bool&gt;&gt; predicate = e =&gt; true;<br><br>        if (OrganisationId.HasValue)<br>        {<br>            predicate = predicate.And(e =&gt; e.OrganisationId == OrganisationId.Value);<br>        }<br><br>        if (TypeId.HasValue)<br>        {<br>            predicate = predicate.And(e =&gt; e.SubmissionTypeDocumentId == TypeId.Value);<br>        }<br><br>        if (PeriodId.HasValue)<br>        {<br>            predicate = predicate.And(e =&gt; e.PeriodId == PeriodId.Value);<br>        }<br><br>        if (StartDate.HasValue)<br>        {<br>            predicate = predicate.And(e =&gt; e.SubmissionDate &gt;= StartDate.Value);<br>        }<br><br>        if (EndDate.HasValue)<br>        {<br>            predicate = predicate.And(e =&gt; e.SubmissionDate &lt;= EndDate.Value);<br>        }<br><br>        return predicate;<br>    }<br>}</pre><p>Essentially, when any of the properties have a value, I am chaining where conditions. You will also notice that there is an And() function. This is an extension I created. If you would prefer to use a Or() instead, then you can follow the same method.</p><pre>public static class PredicateExtensions<br>{<br>    public static Expression&lt;Func&lt;T, bool&gt;&gt; And&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second)<br>    {<br>        var invokedExpr = Expression.Invoke(second, first.Parameters.Cast&lt;Expression&gt;());<br>        return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(Expression.AndAlso(first.Body, invokedExpr), first.Parameters);<br>    }<br>}</pre><p>That wraps this blog post.</p><p>If you liked this blog, please give it a clap and consider following me. I try to write short articles on topics I think will be beneficial to other developers. I am also on <a href="https://twitter.com/jmahachi">X.com</a> and <a href="https://www.linkedin.com/in/jmahachi/">LinkedIn</a>.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9449c3b8e323" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Discriminated Unions: An Example]]></title>
            <link>https://medium.com/@josiahmahachi/typescript-discriminated-unions-an-example-e67a27315dea?source=rss-db4379384042------2</link>
            <guid isPermaLink="false">https://medium.com/p/e67a27315dea</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Josiah T Mahachi]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 06:55:35 GMT</pubDate>
            <atom:updated>2024-01-26T06:55:35.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*HCnAFeVY-ATZ2YAD9koL1w.jpeg" /><figcaption>TypeScript Discriminated Unions</figcaption></figure><p>Recently, I <a href="https://medium.com/@josiahmahachi/understanding-typescript-discriminated-unions-12ec394b11b9">posted a blog</a> on TypeScript Discriminated Unions. I thought I would do a follow up with another example.</p><p>Let’s consider that we are creating a Notification component in React Native that can handle two types of notifications: &#39;alert&#39; and &#39;toast&#39;. It will have children prop which will allow us to pass any React element as the content of the notification. For &#39;toast&#39; notifications, additional toast options will be required.</p><p>Let’s start by defining basic types for the props. This first option does not use TypeScript Discriminated Unions:</p><pre>type ToastOptions = {<br>    duration: number;<br>    position: &#39;top&#39; | &#39;bottom&#39;;<br>};<br><br>type NotificationProps = {<br>    type: &#39;alert&#39; | &#39;toast&#39;;<br>    toastOptions?: ToastOptions;<br>    children: React.ReactNode;<br>};</pre><p>…and the Notification component:</p><pre>import React from &#39;react&#39;;<br>import { View, StyleSheet, Text, Alert } from &#39;react-native&#39;;<br><br>const Notification: React.FC&lt;NotificationProps&gt; = ({ type, toastOptions, children }) =&gt; {<br>    if (type === &#39;toast&#39; &amp;&amp; !toastOptions) {<br>        throw new Error(&quot;Toast options must be provided for &#39;toast&#39; type notifications&quot;);<br>    }<br><br>    const renderToast = () =&gt; (<br>        &lt;View style={[styles.toast, toastOptions?.position === &#39;top&#39; ? { top: 20 } : { bottom: 20 }]}&gt;<br>            {children}<br>        &lt;/View&gt;<br>    );<br><br>    const renderAlert = () =&gt; {<br>        Alert.alert(<br>            &quot;Alert&quot;,<br>            &quot;Alert content&quot;,<br>            [{ text: &quot;OK&quot;, onPress: () =&gt; console.log(&quot;OK Pressed&quot;) }],<br>            { cancelable: false }<br>        );<br><br>        return null;<br>    };<br><br>    return type === &#39;toast&#39; ? renderToast() : renderAlert();<br>};<br><br>const styles = StyleSheet.create({<br>    toast: {<br>        position: &#39;absolute&#39;,<br>        left: 0,<br>        right: 0,<br>        padding: 10,<br>        backgroundColor: &#39;lightgrey&#39;,<br>        justifyContent: &#39;center&#39;,<br>        alignItems: &#39;center&#39;,<br>        zIndex: 1000,<br>    },<br>});<br><br>export default Notification;</pre><p>…and to use this component:</p><pre>import React from &#39;react&#39;;<br>import { SafeAreaView, Text } from &#39;react-native&#39;;<br>import Notification from &#39;./Notification&#39;;<br><br>const App = () =&gt; {<br>    return (<br>        &lt;SafeAreaView style={{ flex: 1 }}&gt;<br>            {/* Alert Notification */}<br>            &lt;Notification type=&quot;alert&quot;&gt;<br>                &lt;Text&gt;Alert Message&lt;/Text&gt;<br>            &lt;/Notification&gt;<br><br>            {/* Toast Notification */}<br>            &lt;Notification type=&quot;toast&quot; toastOptions={{ duration: 3000, position: &#39;bottom&#39; }}&gt;<br>                &lt;Text&gt;Toast Message&lt;/Text&gt;<br>            &lt;/Notification&gt;<br>        &lt;/SafeAreaView&gt;<br>    );<br>};<br><br>export default App;</pre><p>In this example, TypeScript does not force you to provide toastOptions if the type is “toast”, and it does not scream at you either during compile time if you provide them for an “alert” type notification. This is where TypeScript Discriminated Unions come in. Now, let’s refactor the code.</p><p>We’ll define the props in a way that enforces the provision of toast options only when the notification type is “toast”. This is where discriminated unions come in handy, ensuring the correct props are passed based on the notification type:</p><pre>type BaseNotificationProps = {<br>    children: React.ReactNode;<br>};<br><br>type AlertNotificationProps = BaseNotificationProps &amp; {<br>    type: &#39;alert&#39;;<br>};<br><br>type ToastOptions = {<br>    duration: number;<br>    position: &#39;top&#39; | &#39;bottom&#39;;<br>};<br><br>type ToastNotificationProps = BaseNotificationProps &amp; {<br>    type: &#39;toast&#39;;<br>    toastOptions: ToastOptions;<br>};<br><br>type NotificationProps = AlertNotificationProps | ToastNotificationProps;</pre><p>It is a bit more code, agreed, but it does wonders if you are in a large team. We now refactor the Notification as follows:</p><pre>import React from &#39;react&#39;;<br>import { View, StyleSheet, Text, Alert } from &#39;react-native&#39;;<br><br>const Notification: React.FC&lt;NotificationProps&gt; = (props) =&gt; {<br>    const renderToast = (toastOptions: ToastOptions) =&gt; (<br>        &lt;View style={[styles.toast, toastOptions.position === &#39;top&#39; ? { top: 20 } : { bottom: 20 }]}&gt;<br>            {props.children}<br>        &lt;/View&gt;<br>    );<br><br>    const renderAlert = () =&gt; {<br>        Alert.alert(<br>            &quot;Alert&quot;,<br>            &quot;Alert content&quot;,<br>            [{ text: &quot;OK&quot;, onPress: () =&gt; console.log(&quot;OK Pressed&quot;) }],<br>            { cancelable: false }<br>        );<br><br>        return null;<br>    };<br><br>    switch (props.type) {<br>        case &#39;toast&#39;:<br>            return renderToast(props.toastOptions);<br>        case &#39;alert&#39;:<br>            return renderAlert();<br>    }<br>};<br><br>const styles = StyleSheet.create({<br>    toast: {<br>        position: &#39;absolute&#39;,<br>        left: 0,<br>        right: 0,<br>        padding: 10,<br>        backgroundColor: &#39;lightgrey&#39;,<br>        justifyContent: &#39;center&#39;,<br>        alignItems: &#39;center&#39;,<br>        zIndex: 1000,<br>    },<br>});<br><br>export default Notification;</pre><ul><li>The switch statement is used to render the notification based on its type.</li><li>For the ‘toast’ type, the renderToast function is called with toastOptions.</li><li>For the ‘alert’ type, the renderAlert function is invoked.</li></ul><pre>import React from &#39;react&#39;;<br>import { SafeAreaView, Text } from &#39;react-native&#39;;<br>import Notification from &#39;./Notification&#39;;<br><br>const App = () =&gt; {<br>    return (<br>        &lt;SafeAreaView style={{ flex: 1 }}&gt;<br>            {/* Alert Notification */}<br>            &lt;Notification type=&quot;alert&quot;&gt;<br>                &lt;Text&gt;Alert Message&lt;/Text&gt;<br>            &lt;/Notification&gt;<br><br>            {/* Toast Notification */}<br>            &lt;Notification type=&quot;toast&quot; toastOptions={{ duration: 3000, position: &#39;bottom&#39; }}&gt;<br>                &lt;Text&gt;Toast Message&lt;/Text&gt;<br>            &lt;/Notification&gt;<br>        &lt;/SafeAreaView&gt;<br>    );<br>};<br><br>export default App;</pre><p>This implementation ensures type safety and appropriate prop requirements based on the notification type using discriminated unions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e67a27315dea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>