<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[CSandun Blogs]]></title><description><![CDATA[Dev practices, Techologies, Ideas, Thoughts]]></description><link>https://csandunblogs.com/</link><image><url>https://csandunblogs.com/favicon.png</url><title>CSandun Blogs</title><link>https://csandunblogs.com/</link></image><generator>Ghost 5.18</generator><lastBuildDate>Tue, 31 Mar 2026 12:57:24 GMT</lastBuildDate><atom:link href="https://csandunblogs.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[FastEndpoints: The Easy, Clear, and Speedy Way to Define Endpoints in .NET APIs]]></title><description><![CDATA[Define Endpoints in .NET APIs]]></description><link>https://csandunblogs.com/fastendpoints-the-easy-clear-and-speedy-way-to-define-endpoints-in-net-apis/</link><guid isPermaLink="false">68618e50dcfacf04cbe19d10</guid><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Byte-Sized]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Sun, 29 Jun 2025 19:56:54 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2025/06/final.png" medium="image"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2><img src="https://csandunblogs.com/content/images/2025/06/final.png" alt="FastEndpoints: The Easy, Clear, and Speedy Way to Define Endpoints in .NET APIs"><p>.NET provides several ways to build APIs, including MVC Controllers and Minimal APIs. As projects grow, Minimal APIs can get messy, and MVC often leads to unnecessary boilerplate. <strong><a href="https://fast-endpoints.com/">FastEndpoints</a></strong> solves these issues by offering a clean, vertical-slice approach called <strong>REPR</strong> (Request&#x2013;Endpoint&#x2013;Response) while delivering excellent performance.</p><h2 id="what-is-repr-request-%E2%80%93-endpoint-%E2%80%93-response">What is REPR (Request &#x2013; Endpoint &#x2013; Response)?</h2><p>The REPR pattern is at the heart of FastEndpoints. Here&#x2019;s how it works, step by step:</p><ol><li><strong>Request</strong> &#x2013; Define what data comes in (like an ID, name, or any user input).</li><li><strong>Endpoint</strong> &#x2013; Write what your API does with that data. This is where your business logic lives.</li><li><strong>Response</strong> &#x2013; Specify what data goes back to the user (such as details about an item or a status message).</li></ol><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2025/06/image-1.png" class="kg-image" alt="FastEndpoints: The Easy, Clear, and Speedy Way to Define Endpoints in .NET APIs" loading="lazy" width="651" height="414" srcset="https://csandunblogs.com/content/images/size/w600/2025/06/image-1.png 600w, https://csandunblogs.com/content/images/2025/06/image-1.png 651w"></figure><p>Every API feature in your project uses these three parts, making the code tidy, testable, and easy to understand&#x2014;even for beginners.</p><p></p><h2 id="performance-developer-experience">Performance &amp; Developer Experience</h2><p>FastEndpoints delivers performance on par with Minimal APIs and is significantly faster than MVC Controllers&#x2014;benchmarks show around 35k more requests per second than MVC.</p><p>Besides speed, FastEndpoints encourages maintainability, self-contained endpoints, less boilerplate, and easier code organization. This all leads to a better experience for developers at every level.</p><figure class="kg-card kg-image-card kg-card-hascaption"><a href="https://fast-endpoints.com/"><img src="https://csandunblogs.com/content/images/2025/06/image.png" class="kg-image" alt="FastEndpoints: The Easy, Clear, and Speedy Way to Define Endpoints in .NET APIs" loading="lazy" width="1021" height="246" srcset="https://csandunblogs.com/content/images/size/w600/2025/06/image.png 600w, https://csandunblogs.com/content/images/size/w1000/2025/06/image.png 1000w, https://csandunblogs.com/content/images/2025/06/image.png 1021w" sizes="(min-width: 720px) 720px"></a><figcaption>https://fast-endpoints.com/benchmarks#benchmarkdotnet</figcaption></figure><hr><h2 id="how-to-set-up-fastendpoints">How to Set Up FastEndpoints</h2><p>Setting up FastEndpoints is quick and simple. Follow these basic steps:</p><ol><li><strong>Add the FastEndpoints NuGet package</strong></li></ol><pre><code class="language-ps1">dotnet add package FastEndpoints</code></pre><p><strong>2. Register FastEndpoints in your app </strong>In <code>Program.cs</code>, add:</p><figure class="kg-card kg-code-card"><pre><code class="language-csharp">builder.Services.AddFastEndpoints();
app.UseFastEndpoints();</code></pre><figcaption>program.cs</figcaption></figure><p><strong>3. (Optional) Set a global route prefix </strong>To use <code>api</code> as the prefix for all endpoints:</p><figure class="kg-card kg-code-card"><pre><code class="language-csharp">app.UseFastEndpoints(c =&gt; c.Endpoints.RoutePrefix = &quot;api&quot;);</code></pre><figcaption>program.cs</figcaption></figure><p>That&#x2019;s it; your project is ready for FastEndpoints! Now you can start adding endpoints using the REPR pattern.</p><hr><h2 id="creating-a-simple-endpoint">Creating a Simple Endpoint</h2><p>With FastEndpoints, you define each API endpoint as its own class that inherits from the <code>Endpoint</code> base class. Here&#x2019;s a simple example that shows how to handle HTTP GET requests for fetching a customer by ID</p><figure class="kg-card kg-code-card"><pre><code class="language-csharp">public class GetCustomerByIdRequest
{
    public int CustomerId { get; set; }
}

public class GetCustomerByIdResponse
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

public class GetCustomerByIdEndpoint : Endpoint&lt;GetCustomerByIdRequest, GetCustomerByIdResponse&gt;
{
    public override void Configure()
    {
        Get(&quot;api/customers/{CustomerId}&quot;);
        AllowAnonymous();
    }

    public override async Task HandleAsync(GetCustomerByIdRequest req, CancellationToken ct)
    {
        var customer = new GetCustomerByIdResponse
        {
            CustomerId = req.CustomerId,
            Name = &quot;Jane Doe&quot;,
            Email = &quot;jane.doe@example.com&quot;
        };

        await SendAsync(customer);
    }
}</code></pre><figcaption>GetCustomerById.cs</figcaption></figure><p><strong>How it works:</strong></p><ul><li><code>GetCustomerByIdRequest</code>: Describes what data comes in (CustomerId).</li><li><code>GetCustomerByIdResponse</code>: Describes what data goes out (customer info).</li><li><code>GetCustomerByIdEndpoint</code>: Defines the route, accepts the request, processes it, and sends back the response&#x2014;all in one place.</li></ul><h3 id="a-closer-look-at-the-key-methods">A closer look at the key methods</h3><p><strong>Configure()</strong></p><ul><li>This method sets up your endpoint. Here you define the HTTP method (like GET), the route (URL), and any settings such as whether login is needed.</li></ul><p>Example:</p><pre><code class="language-csharp">public override void Configure()
{
    Get(&quot;api/customers/{CustomerId}&quot;);
    AllowAnonymous();
}</code></pre><p>This sets up a GET endpoint at <code>/api/customers/{CustomerId}</code> that does not require login.</p><p><strong>HandleAsync()</strong></p><ul><li>This is where your main logic lives. It runs every time someone makes a request to your endpoint. You use it to process the request, fetch or update data, and prepare the response.</li></ul><p><strong>SendAsync()</strong></p><p>Use this inside <code>HandleAsync()</code> to send the response back to the user.</p><pre><code class="language-csharp">await SendAsync(customer);</code></pre><p>This sends the customer info as the response.</p><p><strong>Endpoint&lt;GetCustomerByIdRequest, GetCustomerByIdResponse&gt;</strong></p><ul><li>This means the class acts like a mini API that takes a <code>GetCustomerByIdRequest</code> (input from the user) and gives back a <code>GetCustomerByIdResponse</code> (the output/result).</li></ul><p>This demonstrates the power of REPR: clear, self-contained code for each API feature.</p><h2 id="further-developmentsbest-practices">Further developments - Best Practices</h2><ul><li><strong>Strongly typed DTOs:</strong> Define clear Request and Response classes for every endpoint.</li><li><strong>Vertical-slice organization:</strong> Keep each endpoint in its own file or folder for better maintainability.</li><li><strong>Global route prefix:</strong> Use <code>app.UseFastEndpoints(c =&gt; c.Endpoints.RoutePrefix = &quot;api&quot;)</code> for a clean API structure.</li><li><strong>Validation:</strong> Integrate FluentValidation for automatic model checks.</li><li><strong>Processors:</strong> Use <code>IPreProcessor&lt;T&gt;</code> and <code>IPostProcessor&lt;T&gt;</code> for cross-cutting concerns like logging and caching.</li><li><strong>Security:</strong> Apply JWT, cookie authentication, or custom schemes; use <code>AllowAnonymous()</code>, <code>Roles()</code>, or <code>Scopes()</code> per endpoint as needed.</li></ul><hr><h2 id="demp-project">Demp Project</h2><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/csandun/PoC1_FastEndpoint"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - csandun/PoC1_FastEndpoint</div><div class="kg-bookmark-description">Contribute to csandun/PoC1_FastEndpoint development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="FastEndpoints: The Easy, Clear, and Speedy Way to Define Endpoints in .NET APIs"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">csandun</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/5cf514024127d338ac87fd5ce999bc8d5192365ed0fab162be6d167f604364be/csandun/PoC1_FastEndpoint" alt="FastEndpoints: The Easy, Clear, and Speedy Way to Define Endpoints in .NET APIs"></div></a></figure><h2 id="resources">Resources</h2><ol><li><a href="https://fast-endpoints.com/">FastEndpoints Doc</a></li><li><a href="https://github.com/FastEndpoints/FastEndpoints">FastEndpoints Github </a></li><li><a href="https://deviq.com/design-patterns/repr-design-pattern">REPR Design Pattern</a></li></ol>]]></content:encoded></item><item><title><![CDATA[MindMapping Azure (AZ-204) - 1 Azure App Service]]></title><description><![CDATA[MindMapping Azure - 1 - We'll start by mind mapping the Azure App Service module, laying the foundation for Az-204 certification journey.]]></description><link>https://csandunblogs.com/az-204-mindmaps-1/</link><guid isPermaLink="false">65ea62cdbe906f04bc86f386</guid><category><![CDATA[azure]]></category><category><![CDATA[az204]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Fri, 08 Mar 2024 02:27:39 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2024/03/Bytesized1-1--1-.png" medium="image"/><content:encoded><![CDATA[<h2 id="welcome-to-the-mindmapping-azure-the-az-204-visual-guide-blog-series">Welcome to the &quot;<strong>MindMapping Azure: The AZ-204 Visual Guide</strong>&quot; blog series</h2><div class="kg-card kg-callout-card kg-callout-card-green"><div class="kg-callout-emoji">&#x1F590;&#xFE0F;</div><div class="kg-callout-text">Welcome to &quot;<strong>MindMapping Azure</strong>,&quot; a blog series crafted to ease your path through the <strong>AZ-204</strong>: <strong>Developing Solutions for Microsoft Azure certification</strong>. Here, we&apos;ll break down the complexities of Azure into clear, manageable pieces, guided by insightful mind maps for each module. This approach aims to make learning about Azure straightforward and accessible to everyone, whether you&apos;re just starting out or looking to deepen your understanding.</div></div><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2024/03/image.png" class="kg-image" alt="MindMapping Azure (AZ-204) - 1 Azure App Service" loading="lazy" width="526" height="440"></figure><img src="https://csandunblogs.com/content/images/2024/03/Bytesized1-1--1-.png" alt="MindMapping Azure (AZ-204) - 1 Azure App Service"><p>To begin our series, we&apos;ll start by mind mapping the Azure App Service module, laying the foundation for our journey.</p><h2 id="azure-app-service-intro">Azure App Service Intro</h2><p>Azure App Service is a powerful cloud platform from Microsoft that lets you easily create web apps and APIs. To start our series, we&apos;re going to create a mind map for the Azure App Service module. This will give us a clear, visual overview of its key features, how to deploy apps, and how to manage them effectively.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://csandunblogs.com/content/images/2024/03/image-1.png" class="kg-image" alt="MindMapping Azure (AZ-204) - 1 Azure App Service" loading="lazy" width="828" height="457" srcset="https://csandunblogs.com/content/images/size/w600/2024/03/image-1.png 600w, https://csandunblogs.com/content/images/2024/03/image-1.png 828w" sizes="(min-width: 720px) 720px"><figcaption>Source : https://weblogs.asp.net/scottgu/announcing-the-new-azure-app-service</figcaption></figure><h2 id="azure-app-service-mind-map">Azure App Service Mind Map</h2><p> Let&apos;s explore Azure App Service as part of the AZ-204 certification, guided by a detailed mind map. This visual representation will help us dissect and understand the service&apos;s key features and functionalities, making complex concepts accessible and straightforward.</p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F590;&#xFE0F;</div><div class="kg-callout-text">The mind map for Azure App Service, as part of the AZ-204 certification study, is available online at the following link.</div></div><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://xmind.app/m/PNFsMj/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">1. Azure App Service</div><div class="kg-bookmark-description">A Mind Map about 1. Azure App Service submitted by ZvFejbBFFA on Mar 8, 2024. Created with Xmind.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://xmind.app/webapp-icon/icon_1024.png" alt="MindMapping Azure (AZ-204) - 1 Azure App Service"><span class="kg-bookmark-author">Xmind</span><span class="kg-bookmark-publisher">Xmind Ltd.</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://share.xmind.app/previews/PNFsMj-bPR2WIx-32432.png" alt="MindMapping Azure (AZ-204) - 1 Azure App Service"></div></a></figure><h3 id="shareable-mind-map">Shareable Mind Map</h3><figure class="kg-card kg-image-card kg-width-full"><a href="https://xmind.app/m/PNFsMj/"><img src="https://csandunblogs.com/content/images/2024/03/1.-Azure-App-Service.png" class="kg-image" alt="MindMapping Azure (AZ-204) - 1 Azure App Service" loading="lazy" width="2000" height="2254" srcset="https://csandunblogs.com/content/images/size/w600/2024/03/1.-Azure-App-Service.png 600w, https://csandunblogs.com/content/images/size/w1000/2024/03/1.-Azure-App-Service.png 1000w, https://csandunblogs.com/content/images/size/w1600/2024/03/1.-Azure-App-Service.png 1600w, https://csandunblogs.com/content/images/size/w2400/2024/03/1.-Azure-App-Service.png 2400w"></a></figure><p><br>Using the provided mind map, we&apos;ll dive deeper into <strong>Azure App Service </strong>in our upcoming discussions. This tool will not only enhance our exploration but also serve as a valuable resource in your preparation for the AZ-204 certification. Stay tuned for our next post, where we&apos;ll continue unraveling the intricacies of Azure App Service together.</p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F590;&#xFE0F;</div><div class="kg-callout-text">I hope you find this content helpful. Keep touching my diaries.<br>Learn something new. Comment your thoughts and share the content.<br>Happy coding!!<br><em>See you again soon. &#x270C;&#x270C;</em></div></div>]]></content:encoded></item><item><title><![CDATA[Simplifying Approval Process with State Machine : A Practical Guide (Part 1) - Modeling]]></title><description><![CDATA[In this two-part blog series, we'll explore the benefits of using StateMachine in C# for managing approval processes, illustrated by a code review approval process example.]]></description><link>https://csandunblogs.com/streamlining-approval-processes-with-statemachine-part-1/</link><guid isPermaLink="false">64430f09be906f04bc86f1fd</guid><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[StateMachine]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Sat, 22 Apr 2023 00:28:02 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/04/statemachine-part-1-1.png" medium="image"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2><img src="https://csandunblogs.com/content/images/2023/04/statemachine-part-1-1.png" alt="Simplifying Approval Process with State Machine : A Practical Guide (Part 1) - Modeling"><p>In my current job, I was tasked with developing <strong>a large-scale approval process</strong> for a complex system. To demonstrate the feasibility and benefits of using a <strong>StateMachine </strong>for this purpose, I created a <strong>Proof of Concept (POC).</strong> Due to confidentiality reasons, I cannot reveal the specifics of my company&apos;s process. However, I can describe the approach and benefits using a <strong>code review approval process</strong> as an <strong>example</strong>. In this <strong>two-part blog post series</strong>, I will first discuss the approach of this type of requirement, &#xA0;then the benefits of using a state machine for managing approval processes and illustrate the process using <strong>PlantUML</strong> diagrams. In the second part, we will implement the <strong>State Machine-based code review approval process in C#</strong>.</p><h2 id="requirement-the-code-review-pr-approval-process">Requirement: The code review (PR) approval process</h2><blockquote>As a software development team, we require a streamlined and effective approach to handling the code review approval process, which encompasses stages such as <u>open</u>, <u>approved</u>, <u>rejected</u>, <u>merged</u>, and <u>closed</u>. The solution should be user-friendly and maintainable, as well as facilitate the addition or modification of states and transitions in the future. Moreover, we&apos;re utilizing the<a href="https://azure.microsoft.com/en-us/products/devops"> Azure DevOps</a> approval process for pull requests.</blockquote><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/04/4b55a195fdc219f78e4fa73a71bb52e1.jpg" class="kg-image" alt="Simplifying Approval Process with State Machine : A Practical Guide (Part 1) - Modeling" loading="lazy" width="562" height="303"></figure><h2 id="advantages-of-using-state-machine">Advantages of Using State Machine</h2><p>Managing the code review approval process can be approached in various ways, such as using <strong>if-else statements</strong>, <strong>switch statements</strong>, or <strong>custom logic</strong>. However, these methods can become <strong>complex and hard to maintain</strong> as the <u>number of states and transitions grows</u>. State machines offer numerous benefits over these techniques:</p><ul><li><strong>Distinct separation of states and transitions</strong>: State machines deliver a clear and organized framework to define and handle states and transitions, resulting in more comprehensible code.</li><li><strong>Scalability</strong>: State machines simplify the process of adding or modifying states and transitions, enabling easy scalability and maintainability.</li><li><strong>Reduced complexity</strong>: State machines abstract the logic for state transitions, decreasing code complexity and making testing and debugging more accessible.<br></li></ul><h3 id="why-we-do-not-use-so-much-if-else">Why we do not use so much If-Else</h3><p>Consider<strong> a simple code review approval process using if-else statements</strong>. While it might work for a <strong>few states, it can quickly become complex</strong> and d<strong>ifficult to maintain as the number of states and transitions increases</strong>. Here&apos;s an example:</p><pre><code class="language-csharp">public void ProcessPullRequest(string action)
{
    if (CurrentState == &quot;Open&quot;)
    {
        if (action == &quot;Approve&quot;)
        {
            CurrentState = &quot;Approved&quot;;
        }
        else if (action == &quot;Reject&quot;)
        {
            CurrentState = &quot;Rejected&quot;;
        }
        else if (action == &quot;Close&quot;)
        {
            CurrentState = &quot;Closed&quot;;
        }
    }
    else if (CurrentState == &quot;Approved&quot;)
    {
        if (action == &quot;Complete&quot;)
        {
            CurrentState = &quot;Completed&quot;;
        }
    }
    else if (CurrentState == &quot;Rejected&quot;)
    {
        if (action == &quot;Resubmit&quot;)
        {
            CurrentState = &quot;Open&quot;;
        }
        else if (action == &quot;Close&quot;)
        {
            CurrentState = &quot;Closed&quot;;
        }
    }
}</code></pre><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/04/6d7872c96cf5cb5a498dd8e6c1170c32a089a731c64914cf8a98392ef2a6e024.jpg" class="kg-image" alt="Simplifying Approval Process with State Machine : A Practical Guide (Part 1) - Modeling" loading="lazy" width="550" height="412"></figure><p>In this example, we&apos;re using &#xA0;to handle the transitions between states in the code review approval process. As the process <strong>becomes more complex with additional states and transitions</strong>, the<strong><u> nested if-else statements will become increasingly difficult to manage, understand, and maintain.</u></strong></p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F929;</div><div class="kg-callout-text">By using a <strong>State Machine</strong>, we can simplify the code and make it more scalable and maintainable, as well as easier to test and debug.</div></div><h2 id="identifying-states-and-transitions">Identifying States and &#xA0;Transitions</h2><p>The code review approval process consists of various states and transitions that help manage the lifecycle of a Pull Request (PR). </p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/04/5b2afd793768903a70151f63e25b94c6.jpg" class="kg-image" alt="Simplifying Approval Process with State Machine : A Practical Guide (Part 1) - Modeling" loading="lazy" width="500" height="382"></figure><p><br>Here&apos;s a brief overview of the states and transitions in the approval process:</p><h3 id="states">States:</h3><ol><li><strong>Open</strong>: The PR is submitted and awaits review.</li><li><strong>Approved</strong>: The PR has been reviewed and meets the required standards.</li><li><strong>Rejected</strong>: The PR does not meet the required standards and needs revisions.</li><li><strong>Completed</strong>: The PR has been approved and integrated into the codebase.</li><li><strong>Closed</strong>: The PR is no longer needed or further revisions won&apos;t be made.</li></ol><h3 id="transitions">Transitions:</h3><ol><li><strong>Submit PR:</strong> A developer submits a PR, transitioning it from a non-existent state to the &quot;Open&quot; state.</li><li><strong>Approve</strong>: A reviewer approves the PR, transitioning it from the &quot;Open&quot; state to the &quot;Approved&quot; state.</li><li><strong>Reject</strong>: A reviewer rejects the PR, transitioning it from the &quot;Open&quot; state to the &quot;Rejected&quot; state.</li><li><strong>Revise and resubmit</strong>: The developer makes revisions and resubmits the PR, transitioning it from the &quot;Rejected&quot; state back to the &quot;Open&quot; state.</li><li><strong>Complete </strong>: The PR is merged into the target branch, transitioning it from the &quot;Approved&quot; state to the &quot;Completed&quot; state.</li><li><strong>Close</strong>: The PR is closed without merging, transitioning it from the &quot;Open&quot; or &quot;Rejected&quot; state to the &quot;Closed&quot; state.</li></ol><p>These states and transitions form the backbone of the code review approval process, allowing teams to effectively manage PRs and ensure a smooth and efficient workflow.</p><h2 id="visualizing-the-process-with-plantuml">Visualizing the Process with PlantUML</h2><p>Before diving into the code implementation, it&apos;s helpful to <strong>visualize </strong>the <strong>approval process</strong> using <strong><a href="https://g.co/kgs/c3b5Cc">PlantUML</a></strong>. By creating a <strong>state diagram</strong> with PlantUML, we can clearly represent the states and transitions in the code review approval process.</p><figure class="kg-card kg-code-card"><pre><code class="language-plantuml">@startuml

hide empty description
title Code Review Approval Process

state &quot;Open&quot; as open
state &quot;Approved&quot; as approved
state &quot;Rejected&quot; as rejected
state &quot;Completed&quot; as completed
state &quot;Closed&quot; as closed

[*] --&gt; open : SubmitPR()
note right of open : Awaiting review
open --&gt; approved : Approve()
note right of approved : Meets standards
open --&gt; rejected : Reject()
note left of rejected : Needs revisions
rejected --&gt; open : Revise&amp;resubmit()
approved --&gt; completed : Complete()
note right of completed : Integrated into codebase
open --&gt; closed : Close()
rejected --&gt; closed : Close()
note left of closed : No further revisions
completed --&gt; [*]
closed --&gt; [*]

@enduml</code></pre><figcaption>code_review_approval_process.plantuml</figcaption></figure><h3 id="lets-see-generated-process-state-machine-image">Lets see generated process State Machine Image</h3><figure class="kg-card kg-image-card kg-width-wide"><img src="https://csandunblogs.com/content/images/2023/04/code--approval.png" class="kg-image" alt="Simplifying Approval Process with State Machine : A Practical Guide (Part 1) - Modeling" loading="lazy" width="658" height="500" srcset="https://csandunblogs.com/content/images/size/w600/2023/04/code--approval.png 600w, https://csandunblogs.com/content/images/2023/04/code--approval.png 658w"></figure><p><br>Copy this PlantUML code and paste it into an online PlantUML editor such as <a href="https://www.planttext.com/">PlantText</a> or <a href="https://www.plantuml.com/plantuml/uml">PlantUML Online Editor</a> to generate a visual diagram of the code review approval process. This diagram illustrates the various states and transitions in the process, providing a clear understanding of the process.</p><div class="kg-card kg-callout-card kg-callout-card-blue"><div class="kg-callout-emoji">&#x1F929;</div><div class="kg-callout-text"><strong>To Be Continued..</strong><br>In the second part of this blog post series, we will implement the StateMachine-based code review<strong> approval process in C# using the states and transitions visualize</strong>d in the PlantUML diagram. <strong><em>This example will demonstrate the benefits and practicality of using a state machine for managing approval processes in real-world scenarios, like the one I encountered in my current job.</em></strong></div></div><hr><h2 id="resources">Resources</h2><ol><li><strong><a href="https://www.lloydatkinson.net/posts/2022/modelling-workflows-with-finite-state-machines-in-dotnet/">Modelling Workflows With Finite State Machines in .NET</a></strong></li><li><a href="https://learn.microsoft.com/en-us/dotnet/framework/windows-workflow-foundation/state-machine-workflows"><strong>State Machine Workflows</strong></a></li><li><strong><a href="https://www.youtube.com/watch?v=FhjNi7PGDaQ">State Machine and State Design Pattern</a></strong></li></ol>]]></content:encoded></item><item><title><![CDATA[The Power of MediatR Notifications in CQRS and Microservices]]></title><description><![CDATA[Discover MediatR's Notification feature in .NET Core, enhancing applications with clean, maintainable code and effective communication between components.]]></description><link>https://csandunblogs.com/mediatr-notifications/</link><guid isPermaLink="false">64258593be906f04bc86f037</guid><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[Mediatr]]></category><category><![CDATA[CSharp]]></category><category><![CDATA[CleanArchitecture]]></category><category><![CDATA[CQRS]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Thu, 30 Mar 2023 15:58:53 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/03/mediator1.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/03/mediator1.png" alt="The Power of MediatR Notifications in CQRS and Microservices"><p>Hi developers! Want to improve your .NET Core projects while keeping your code clean? You&apos;re in luck! Today, we&apos;ll explore MediatR and its Notification feature through a practical use case, showing how it can elevate your applications. Let&apos;s dive in!</p><h2 id="what-is-mediatr">What is MediatR</h2><p>If you&apos;re new to <a href="https://github.com/jbogard/MediatR"><strong>MediatR</strong>,</a> it&apos;s an open-source library that helps you implement the popular <strong>Mediator pattern</strong> in your .NET Core projects.<strong> MediatR acts as a central communication hub, allowing different parts of your application to talk to each other without direct dependencies</strong>. Say goodbye to tightly-coupled code and hello to cleaner, more maintainable projects.</p><div class="kg-card kg-callout-card kg-callout-card-yellow"><div class="kg-callout-emoji">&#x1F4A1;</div><div class="kg-callout-text">Supports request/response, commands, queries, notifications and events, synchronous and async, with intelligent dispatching via C# generic variance.</div></div><h2 id="mediatr-notifications"><br>MediatR Notifications</h2><p>MediatR&apos;s Notification feature, also known as Publish, enables you to broadcast messages to multiple handlers asynchronously. This powerful mechanism informs your application&apos;s components about important events or changes without complicated logic or cumbersome wiring. It&apos;s like having your news network within your project!</p><h2 id="use-case">Use Case: </h2><h3 id="notify-email-and-sms-to-customers-after-order-creation-event"><strong><em>Notify Email and SMS to Customers after Order Creation Event:</em></strong></h3><blockquote><strong><em>Imagine you&apos;re building an e-commerce application and need to notify customers via Email and SMS when their orders are created. Using MediatR Notifications, you can elegantly achieve this.</em></strong></blockquote><figure class="kg-card kg-image-card kg-width-wide"><img src="https://csandunblogs.com/content/images/2023/03/mediator2.png" class="kg-image" alt="The Power of MediatR Notifications in CQRS and Microservices" loading="lazy" width="2000" height="1292" srcset="https://csandunblogs.com/content/images/size/w600/2023/03/mediator2.png 600w, https://csandunblogs.com/content/images/size/w1000/2023/03/mediator2.png 1000w, https://csandunblogs.com/content/images/size/w1600/2023/03/mediator2.png 1600w, https://csandunblogs.com/content/images/2023/03/mediator2.png 2018w" sizes="(min-width: 1200px) 1200px"></figure><h3 id="explanation">Explanation</h3><p>In modern applications, executing tasks like sending emails or SMS notifications <strong>asynchronously </strong>ensures <strong>a smooth user experience and prevents unnecessary delays.</strong> For example, when creating an order, <em>the primary focus should be completing the order process without depending on immediate responses from email or SMS services</em>. <br><br>Leveraging <strong>MediatR Notifications</strong> allows efficient management of these <strong>asynchronous tasks, enabling the independent progression </strong>of the order creation process. This approach ensures application responsiveness and optimal performance while sending email and SMS notifications in the background <strong><u>without impacting the primary functionality</u></strong> of the order creation handler.</p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F918;</div><div class="kg-callout-text"><strong><strong>You want event/notification handlers to be run independently in isolation.</strong></strong> <br>This is where out-of-process messaging comes in.</div></div><p>However, a single request can be handled by Multiple handlers. Some independent operation needs to occur after some events.</p><h2 id="practical">Practical</h2><p>Explore my GitHub-linked codebase, where I&apos;ve implemented the CQRS pattern using the MediatR library. Featuring a clean architecture within a single project structure, I&apos;ve elegantly crafted an <strong>Order Create Command</strong> and corresponding <strong>Command Handler</strong> for the use case mentioned above.</p><p>1. First of all, Let&#x2019;s create a notification and handler. &#xA0;It is also referred to as events. Add a class with the name `OrderCreatedNotification`<strong><strong>.</strong></strong></p><figure class="kg-card kg-code-card"><pre><code class="language-csharp">public class OrderCreatedNotification : INotification
{
    public Order Order { get; set; }
}</code></pre><figcaption>OrderCreatedNotification.cs</figcaption></figure><p>2. Now, I have created two handlers, one for sending Email and one for SMS.</p><figure class="kg-card kg-code-card"><pre><code class="language-csharp">public class OrderCreatedEmailHandler : INotificationHandler&lt;OrderCreatedNotification&gt;
{
    private readonly ILogger&lt;OrderCreatedEmailHandler&gt; _logger;

    public OrderCreatedEmailHandler(ILogger&lt;OrderCreatedEmailHandler&gt; logger)
    {
        _logger = logger;
    }

    public Task Handle(OrderCreatedNotification notification, CancellationToken cancellationToken)
    {
        // Send a confirmation email
        _logger.LogInformation($&quot;Confirmation email sent for order {notification.Order.Id}&quot;);

        return Task.CompletedTask;
    }
}</code></pre><figcaption>OrderCreatedEmailHandler.cs</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-csharp">public class OrderCreatedSMSHandler : INotificationHandler&lt;OrderCreatedNotification&gt;
{
    private readonly ILogger&lt;OrderCreatedSMSHandler&gt; _logger;

    public OrderCreatedSMSHandler(ILogger&lt;OrderCreatedSMSHandler&gt; logger)
    {
        _logger = logger;
    }

    public Task Handle(OrderCreatedNotification notification, CancellationToken cancellationToken)
    {
        // Send a confirmation sms
        _logger.LogInformation($&quot;Confirmation sms sent for order {notification.Order.Id}&quot;);

        return Task.CompletedTask;
    }
}</code></pre><figcaption>OrderCreatedSMSHandler.cs</figcaption></figure><p>You can elegantly incorporate the relevant logic within handlers, ensuring a clean and maintainable approach to implementing functionality in your application.</p><h3 id="trigger-the-notification">Trigger the Notification </h3><p>Open `CreateOrderCommandHandler` and modify the handler method for publishing the order once saved in the database. Here I am representing a new order, including a new OrderId.</p><pre><code class="language-csharp">// Publish a notification that the order has been created
await _mediator.Publish(new OrderCreatedNotification() { Order  = order }, cancellationToken);
</code></pre><p> The notification carries an <code>OrderId</code> property containing the newly created order&apos;s ID. Using the <code>_mediator.Publish()</code> method, the notification is asynchronously dispatched to all registered handlers interested in the <code>OrderCreated</code> event.</p><h3 id="output">Output</h3><p><strong>Swagger representation</strong></p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/03/image.png" class="kg-image" alt="The Power of MediatR Notifications in CQRS and Microservices" loading="lazy" width="1422" height="582" srcset="https://csandunblogs.com/content/images/size/w600/2023/03/image.png 600w, https://csandunblogs.com/content/images/size/w1000/2023/03/image.png 1000w, https://csandunblogs.com/content/images/2023/03/image.png 1422w" sizes="(min-width: 720px) 720px"></figure><p><strong>Output in terminal</strong></p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/03/image-1.png" class="kg-image" alt="The Power of MediatR Notifications in CQRS and Microservices" loading="lazy" width="715" height="118" srcset="https://csandunblogs.com/content/images/size/w600/2023/03/image-1.png 600w, https://csandunblogs.com/content/images/2023/03/image-1.png 715w"></figure><p>Here we can see logs from both handlers.</p><h2 id="other-use-cases-of-mediatr-notifications">Other use cases of MediatR Notifications<br></h2><p><strong><u>1.Event-driven architecture: </u></strong><br>MediatR Notifications enable services in an event-driven system to <strong>communicate through events,</strong> promoting asynchronous reactions and reducing tight coupling.</p><p><strong><u>2.Cross-cutting concerns: </u></strong><br>Notifications handle concerns like l<strong>ogging, auditing, or monitoring </strong>by using separate handlers for each, ensuring clean separation and easy modification.</p><p><u><strong>3.Integrating with external systems:</strong> &#xA0;</u><br>Notifications facilitate integration with <strong>external systems like messaging platforms (e.g., RabbitMQ, Kafka)</strong> or third-party APIs by <strong>processing notifications</strong> and <strong>sending messages</strong> or API requests as needed.</p><p><strong><u>4.Caching and data synchronization: </u></strong><br>Notifications maintain consistency and performance in distributed systems by alerting relevant services or components about <strong>data changes</strong>, <strong>triggering cache</strong> invalidation or<strong> data updates.</strong></p><p>Let&apos;s discuss these concepts further in upcoming sections. Stay tuned for more insights on effectively incorporating this powerful tool in your .NET Core applications!</p><h2 id="conclusion">Conclusion</h2><p>MediatR Notifications is a game-changer for your .NET Core projects in microservices architecture, streamlining communication and enhancing maintainability. Implementing this powerful feature can boost your application&apos;s capabilities while keeping your codebase clean and efficient. </p><hr><h2 id="resources">Resources</h2><ol><li><a href="https://github.com/jbogard/MediatR">MediatR repository</a></li><li><a href="https://codeopinion.com/why-use-mediatr-3-reasons-why-and-1-reason-not/">Why use MediatR? 3 reasons why and 1 reason not</a></li><li><a href="https://github.com/jbogard/MediatR/wiki">Wiki</a></li></ol><h2 id="demo-project">Demo Project</h2><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/csandun/MediatrWithPublish"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - csandun/MediatrWithPublish: This is a sample project demonstrating how to use MediatR INotification to send email notifications</div><div class="kg-bookmark-description">This is a sample project demonstrating how to use MediatR INotification to send email notifications - GitHub - csandun/MediatrWithPublish: This is a sample project demonstrating how to use MediatR ...</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="The Power of MediatR Notifications in CQRS and Microservices"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">csandun</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/48666036dfb3a8cc30108fe779d6a8a339b066756e100afa45f155d08ae28bc2/csandun/MediatrWithPublish" alt="The Power of MediatR Notifications in CQRS and Microservices"></div></a></figure><hr><div class="kg-card kg-callout-card kg-callout-card-red"><div class="kg-callout-emoji">&#x1F4AC;</div><div class="kg-callout-text">You can comment your throughs below comment section. &#x1F447;</div></div><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Linq Intersect() - get common elements from 2 lists]]></title><description><![CDATA[The Intersect() method finds the common elements between two collections.]]></description><link>https://csandunblogs.com/linq-intersect/</link><guid isPermaLink="false">63ee7442be906f04bc86ee8f</guid><category><![CDATA[CSharp]]></category><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[Linq]]></category><category><![CDATA[Byte-Sized]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Thu, 16 Feb 2023 19:50:32 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/02/intersect.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/02/intersect.png" alt="Linq Intersect() - get common elements from 2 lists"><p>In<strong> Byte-Sized #3</strong> we are looking about the <code>Intersect()</code> method. Thats finds the common elements between two collections.</p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F4A1;</div><div class="kg-callout-text">Do not use two inner for-loops to find common elements in two sequences. Use <strong>Intersect()</strong> or <strong>IntersectBy()</strong> methods.</div></div><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/02/image-4.png" class="kg-image" alt="Linq Intersect() - get common elements from 2 lists" loading="lazy" width="508" height="491"></figure><h2 id="what-is-intersect">What is Intersect()</h2><p>In LINQ , <code>Intersect()</code> is an operator to perform a set intersection of two sequences. It <strong>returns a new sequence that contains the elements common to both sequences</strong>, in other words, the elements that appear in both sequences.</p><p>The syntax for using the Intersect operator in LINQ is as follows:</p><pre><code class="language-csharp">var commonElements = sequence1.Intersect(sequence2);</code></pre><p>Today I am going to introduce how to play with Intersect and the new syntaxes of this.</p><h2 id="simple-sequences">Simple sequences</h2><p>You can use the Intersect operator to find the common elements between the two lists as follows:</p><pre><code class="language-csharp">List&lt;int&gt; list1 = new List&lt;int&gt; { 1, 2, 3, 4, 5 };
List&lt;int&gt; list2 = new List&lt;int&gt; { 3, 4, 5, 6, 7 };

var list1list2Common = list1.Intersect(list2);

foreach (var item in list1list2Common)
{
    Console.WriteLine(item);
}

/*
3
4
5
*/</code></pre><p>The result will be a new sequence containing the elements <strong>{ 3, 4, 5 }</strong>, which are the elements that are common to both lists.</p><h2 id="complex-object-sequences">complex object sequences</h2><p>Suppose you have a class Person that represents a person with a name and an age. </p><pre><code class="language-csharp">public class Person : IEquatable&lt;Person&gt;
{
    public string Name { get; set; }
    public int Age { get; set; }
}</code></pre><p>And I used below List3 and List4 for describe examples</p><pre><code class="language-csharp">var list3 = new List&lt;Person&gt; 
{ 
    new Person { Name = &quot;Alice&quot;, Age = 25 }, 
    new Person { Name = &quot;Bob&quot;, Age = 30 }, 
    new Person { Name = &quot;Charlie&quot;, Age = 35 },
    new Person { Name = &quot;Eve&quot;, Age = 50 }
};

var list4 = new List&lt;Person&gt; 
{ 
    new Person { Name = &quot;Bob&quot;, Age = 30 }, 
    new Person { Name = &quot;David&quot;, Age = 35 }, 
    new Person { Name = &quot;Eve&quot;, Age = 40 }
};</code></pre><h3 id="1-using-iequatablet">1. Using IEquatable&lt;T&gt;</h3><p>To use Intersect with complex object lists, you can implement the <code><strong>IEquatable&lt;T&gt;</strong></code> interface on the class that represents the objects in the lists. The <code><strong>IEquatable&lt;T&gt;</strong></code> interface defines the <code><strong>Equals()</strong></code> method, which is used by the Intersect operator to compare the objects in the lists.</p><pre><code class="language-csharp">public class Person : IEquatable&lt;Person&gt;
{
    public string Name { get; set; }
    public int Age { get; set; }

    // override Equals method
    public bool Equals(Person other)
    {
        if (other == null) return false;
        return (this.Name == other.Name 
        			&amp;&amp; this.Age == other.Age);
    }
}

//...

var list3list4CommonEquatable = list3.Intersect(list4);

foreach (var item in list3list4CommonEquatable)
{
    Console.WriteLine(item.Name); // Bob
}</code></pre><p>Here is the Sample code, and As the Name and Age,<strong> Bob is the common element</strong> in the sequence.</p><h3 id="2-using-iequalitycomparert">2. Using IEqualityComparer&lt;T&gt;</h3><p>You can also use the <code>Intersect</code> operator on complex object lists by providing a custom <code>IEqualityComparer&lt;T&gt;</code> implementation that defines how to compare the objects in the lists.</p><p>I have created a custom <code>PersonComparer</code> class that implements the <code>IEqualityComparer&lt;Person&gt;</code> interface. This custom comparer defines how to compare two <code>Person</code> objects by implementing the <code>Equals</code> method, and how to calculate the hash code of a <code>Person</code> object by implementing the <code>GetHashCode</code> method.</p><pre><code class="language-csharp">public class PersonComparer : IEqualityComparer&lt;Person&gt;
{
    public bool Equals(Person x, Person y)
    {
        if (x == null || y == null) return false;
        return (x.Name == y.Name &amp;&amp; x.Age == y.Age);
    }

    public int GetHashCode(Person obj)
    {
        if (obj == null) return 0;
        return obj.Name.GetHashCode() 
        			^ obj.Age.GetHashCode();
    }
}</code></pre><p>To use the <code>Intersect</code> operator on a list of <code>Person</code> objects, you can create two lists and a new instance of <code>PersonComparer</code>, and then call the <code>Intersect</code> method with the two lists and the custom comparer.</p><pre><code class="language-csharp">var comparer = new PersonComparer();

var commonPeople = list1.Intersect(list2, comparer);</code></pre><h2 id="intersectbynew-implementation">IntersectBy() - New Implementation </h2><p>Exisiting method &#xA0;<code>Intersect</code> has been powered up by these new methods which can take a selector function to operate. This <code>IntersectBy()</code> was introduced with .NET 6 new linq features.</p><p>If we simply want to compare elements by key (Name), then we can use <code>IntersectBy</code> instead of creating comparer. Following code generates same output as using comparer.</p><pre><code class="language-csharp">// in this name is the key
var list3list4CommonSingleProperty 
	        = list3.IntersectBy(
            	list4.Select(o =&gt; o.Name), 
                x =&gt;x.Name);

foreach (var item in list3list4CommonSingleProperty)
{
    Console.WriteLine(item.Name);
}

//Bob
//Eve
</code></pre><p>Here is an example of the showcase of how multiple properties can process like comparer. Here Age and Name are considered equality properties.</p><pre><code class="language-csharp">var list3list4CommonMultipleProperties 
		= list3
        .IntersectBy(list4.Select(o =&gt; new { name = o.Name, age = o.Age}),
         x =&gt; new {name = x.Name, age= x.Age});

foreach (var item in list3list4CommonMultipleProperties)
{
    Console.WriteLine(item.Name);
}</code></pre><h2 id="conclusion">Conclusion</h2><div class="kg-card kg-callout-card kg-callout-card-red"><div class="kg-callout-emoji">&#x1F4AB;</div><div class="kg-callout-text">The <code>Intersect</code> operator in LINQ is a powerful tool that allows developers to find the common elements between two collections. It can be used to simplify complex operations and save developers time and effort.<br><br>The <code>IntersectBy</code> is more powerful which can take a selector function to operate.<br></div></div><p></p><hr><h2 id="resources">Resources</h2><ol><li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.intersectby?view=net-7.0">Microsoft Documentation</a></li><li><a href="https://dotnettutorials.net/lesson/linq-intersect-method/">LINQ Intersect Method in C#</a></li></ol><h2 id="demo-project">Demo Project</h2><p>There is a demo project you can check out over on GitHub with the examples for <code>Intersect()</code> and <code>IntersectBy()</code>.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/csandun/IntersectInLinq"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - csandun/IntersectInLinq</div><div class="kg-bookmark-description">Contribute to csandun/IntersectInLinq development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Linq Intersect() - get common elements from 2 lists"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">csandun</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/a8489724f0086e4b2e047e5fe84c49ab67d8cbe93b626179b638e7db7019231e/csandun/IntersectInLinq" alt="Linq Intersect() - get common elements from 2 lists"></div></a></figure><hr><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F48C;</div><div class="kg-callout-text">Put your comments on this topic. See ya soon on another blog post. &#x1F44A;&#x1F44A;</div></div>]]></content:encoded></item><item><title><![CDATA[Git-Emojis - cool git commits]]></title><description><![CDATA[Every commit is important. So let's celebrate each and every commit with a corresponding emoji! ]]></description><link>https://csandunblogs.com/git-emojis/</link><guid isPermaLink="false">63e2a067be906f04bc86ed9f</guid><category><![CDATA[Git]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Byte-Sized]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Tue, 07 Feb 2023 20:05:34 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/02/gitemojis.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/02/gitemojis.png" alt="Git-Emojis - cool git commits"><p><strong>Every commit is important</strong>. So let&apos;s celebrate each and every commit with a corresponding <strong>emoji</strong>! &#x1F600;</p><p>Using emojis in your commit messages will be <strong>fun </strong>(&#x1F60A;) and <strong>cool </strong>(&#x1F60E;) in the first place. <strong>They can be recognized at a glance, no matter the spoken language</strong>. So today, we will look into Git emojis in our short blog post (Byte-Sized #2). <strong>Also Currently, many version control websites are supported for Git Emojis.</strong></p><h2 id="what-is-git-emojis">What is Git Emojis?</h2><p><strong>Git Emojis</strong> are a set of custom emoji symbols used in<strong> commit messages or code comments</strong> to provide <strong>extra context and expression</strong> to the changes being made to a codebase. They are usually added along with a commit message to help convey the nature of the changes made in a <strong>more visually expressive</strong> and fun way.</p><h2 id="benefits-we-can-get-from-git-emojis">Benefits we can get from Git emojis</h2><ol><li><strong>Clarity and Conveying Intent</strong>: Git emojis help convey the intent behind the changes being made clearly and concisely.</li><li><strong>Enhanced Visual Representation</strong>: Emojis are visually appealing and make it easier for developers to quickly understand the nature of the changes being made to a codebase.</li><li><strong>Improved Collaboration</strong>: Using Git emojis can help enhance collaboration within a development team by creating a shared understanding of the changes and the intent behind them.</li><li><strong>Increased Engagement and Fun</strong>: Using Git emojis can add a touch of fun and personality to the otherwise monotonous task of version control and can help increase developers&apos; engagement and motivation.</li><li><strong>Improved Codebase Documentation</strong>: Using Git emojis can help document a codebase&apos;s history and the changes being made, making it easier for new developers to understand the context and intent behind the code.</li></ol><h2 id="example">Example</h2><p><strong>Git emojis</strong> consist of a shortcode representation of an emoji symbol, such as :bug: (&#x1F41B;) for a <strong>bug fix</strong> or :sparkles: (&#x2728;) for a <strong>new feature</strong>. They can be added to the beginning or end of a commit message or code comment to indicate the nature of the changes being made.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/02/image-1.png" class="kg-image" alt="Git-Emojis - cool git commits" loading="lazy" width="1187" height="805" srcset="https://csandunblogs.com/content/images/size/w600/2023/02/image-1.png 600w, https://csandunblogs.com/content/images/size/w1000/2023/02/image-1.png 1000w, https://csandunblogs.com/content/images/2023/02/image-1.png 1187w" sizes="(min-width: 720px) 720px"></figure><p>This is the famous git repository where emojis are used clearly by <a href="https://github.com/jasontaylordev">jasontaylordev</a>. Refer to that commit massages and get a good idea of it.</p><figure class="kg-card kg-bookmark-card kg-card-hascaption"><a class="kg-bookmark-container" href="https://github.com/jasontaylordev/CleanArchitecture"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - jasontaylordev/CleanArchitecture: Clean Architecture Solution Template for .NET 7</div><div class="kg-bookmark-description">Clean Architecture Solution Template for .NET 7. Contribute to jasontaylordev/CleanArchitecture development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Git-Emojis - cool git commits"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">jasontaylordev</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/f007f087099b1c5efc9f4633456687199e728ec8a5b6b14ef1c6e1881857ab73/jasontaylordev/CleanArchitecture" alt="Git-Emojis - cool git commits"></div></a><figcaption>jasontaylordev/CleanArchitecture</figcaption></figure><h2 id="my-favorite-emojis">My favorite emojis</h2><!--kg-card-begin: markdown--><table>
<thead>
<tr>
<th><strong>Emoji</strong></th>
<th><strong>Meaning</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>&#x1F389;</td>
<td>Begin a project.</td>
</tr>
<tr>
<td>&#x2728;</td>
<td>Introduce new features</td>
</tr>
<tr>
<td>&#x1F41B;</td>
<td>Fix a bug</td>
</tr>
<tr>
<td>&#x1F454;</td>
<td>Add or update business logic</td>
</tr>
<tr>
<td>&#x267B;&#xFE0F;</td>
<td>Refactor code</td>
</tr>
<tr>
<td>&#x1F484;</td>
<td>Add or update the UI and style file</td>
</tr>
<tr>
<td>&#x270F;&#xFE0F;</td>
<td>Fix typos</td>
</tr>
<tr>
<td>&#x1F5C3;&#xFE0F;</td>
<td>Perform database related changes</td>
</tr>
<tr>
<td>&#x1F3A8;</td>
<td>Improve structure / format of the code</td>
</tr>
<tr>
<td>&#x1F6A7;</td>
<td>Work in progress</td>
</tr>
<tr>
<td>&#x1F527;</td>
<td>Add or update configuration files</td>
</tr>
<tr>
<td>&#x1F4A1;</td>
<td>Add or update comments in source code</td>
</tr>
<tr>
<td>&#x1F9BA;</td>
<td>Add or update code related to validation</td>
</tr>
</tbody>
</table>
<!--kg-card-end: markdown--><h2 id="how-we-use-git-emojis-in-your-project">How we use Git Emojis in your project</h2><p><strong>Using gitmoji-vscode for VSCode users</strong></p><p><a href="https://github.com/vtrois/gitmoji-vscode"><strong>gitmoji-vscode</strong></a> is a <strong>VSCode extension </strong>&#x1F4C7; that helps you to add emoji right from your editor itself. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://csandunblogs.com/content/images/2023/02/about.gif" class="kg-image" alt="Git-Emojis - cool git commits" loading="lazy" width="1084" height="741" srcset="https://csandunblogs.com/content/images/size/w600/2023/02/about.gif 600w, https://csandunblogs.com/content/images/size/w1000/2023/02/about.gif 1000w, https://csandunblogs.com/content/images/2023/02/about.gif 1084w" sizes="(min-width: 720px) 720px"><figcaption>from gitmoji-vscode extension page</figcaption></figure><p>You can find gitmoji supported extension for your <strong>favorite editor too. </strong>&#x1F9D1;&#x200D;&#x1F4BC;</p><p><strong>You can use git repositories shared by the community.</strong></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://gist.github.com/parmentf/035de27d6ed1dce0b36a"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Git Commit message Emoji</div><div class="kg-bookmark-description">Git Commit message Emoji. GitHub Gist: instantly share code, notes, and snippets.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://gist.github.com/fluidicon.png" alt="Git-Emojis - cool git commits"><span class="kg-bookmark-author">Gist</span><span class="kg-bookmark-publisher">262588213843476</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://github.githubassets.com/images/modules/gists/gist-og-image.png" alt="Git-Emojis - cool git commits"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/ahmadawais/Emoji-Log"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - ahmadawais/Emoji-Log: Emoji-Log &#x2014; An Emoji Git commit log messages spec standard. [ &#x1F4E6;&#x1F44C;&#x1F41B;&#x1F4D6;&#x1F680;&#x1F916; &#x203C;&#xFE0F;]</div><div class="kg-bookmark-description">Emoji-Log &#x2014; An Emoji Git commit log messages spec standard. [ &#x1F4E6;&#x1F44C;&#x1F41B;&#x1F4D6;&#x1F680;&#x1F916; &#x203C;&#xFE0F;] - GitHub - ahmadawais/Emoji-Log: Emoji-Log &#x2014; An Emoji Git commit log messages spec standard. [ &#x1F4E6;&#x1F44C;&#x1F41B;&#x1F4D6;&#x1F680;&#x1F916; &#x203C;&#xFE0F;]</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Git-Emojis - cool git commits"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">ahmadawais</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/87b25b4d5f02cbd49b94187b81f3aff71bf16c9c97d6a918239318bf5c0070aa/ahmadawais/Emoji-Log" alt="Git-Emojis - cool git commits"></div></a></figure><p><strong>You can use the google chrome extension as well.</strong></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://chrome.google.com/webstore/detail/gitmoji-browser-extension/lkjogeoldakjceempbkdahkojohmbaja?hl=en"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Gitmoji Browser Extension</div><div class="kg-bookmark-description">The Gitmoji extension to easily search and copy gitmojis &#x1F61C;</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://ssl.gstatic.com/chrome/webstore/images/icon_144px.png" alt="Git-Emojis - cool git commits"><span class="kg-bookmark-author">Chrome Web Store</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://lh3.googleusercontent.com/8sotygtngKje9afZMlsajQoPbrKm33pQYe835UuItRoUrSmxwFhkZezO4jqb435bA-nEolWTEUE8SNAzgIBMWaVzqzY=w128-h128-e365-rj-sc0x00ffffff" alt="Git-Emojis - cool git commits"></div></a></figure><p><strong>And apart from these methods, you can just copy-paste emoji from the internet too.</strong></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://gitmoji.dev/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">gitmoji</div><div class="kg-bookmark-description">An emoji guide for your commit messages.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://gitmoji.dev/static/android-icon-192x192.png" alt="Git-Emojis - cool git commits"><span class="kg-bookmark-author">An emoji guide for your commit messages</span><span class="kg-bookmark-publisher">Carlos Cuesta</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://gitmoji.dev/static/gitmoji.gif" alt="Git-Emojis - cool git commits"></div></a></figure><h2 id="conclusion">Conclusion</h2><p>Using <strong>Git emojis</strong> is not part of the standard Git specification. Still, <strong>it is a common convention used by many development teams to help make their version control</strong> <strong>workflows more visually appealing and informative</strong>. Using Git emojis, developers can <strong>quickly </strong>and <strong>easily understand </strong>the intent behind changes to a codebase and make version control a more <strong>enjoyable </strong>&#x1F601;<strong> </strong>and<strong> engaging</strong> experience.</p><hr><h2 id="resources">Resources</h2><ol><li><a href="https://gitbetter.substack.com/p/how-to-use-emoji-in-your-commit-message">https://gitbetter.substack.com/p/how-to-use-emoji-in-your-commit-message</a></li><li><a href="https://wilsonmar.github.io/git-messages/">https://wilsonmar.github.io/git-messages/</a></li></ol><hr><div class="kg-card kg-callout-card kg-callout-card-blue"><div class="kg-callout-emoji">&#x1F929;</div><div class="kg-callout-text"><strong>Get fun, add color, and easily recognize your commit message.</strong></div></div><p>Happy coding, Happy git commiting &#x1F921; !!! </p>]]></content:encoded></item><item><title><![CDATA[Console App with Dependency Injection]]></title><description><![CDATA[Let's apply Dependency Injection to Asp.net Core Console App.]]></description><link>https://csandunblogs.com/byte-sized-01-console-app-with-dependency-injection/</link><guid isPermaLink="false">63df282dbe906f04bc86ed65</guid><category><![CDATA[Byte-Sized]]></category><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[CSharp]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Sun, 05 Feb 2023 03:54:38 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/02/Bytesized1-1.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/02/Bytesized1-1.png" alt="Console App with Dependency Injection"><p></p><h2 id="welcome-to-the-byte-sized-blog-series">Welcome to the &quot;Byte-Sized&quot; blog series</h2><div class="kg-card kg-callout-card kg-callout-card-pink"><div class="kg-callout-emoji">&#x1F64B;&#x1F3FB;&#x200D;&#x2640;&#xFE0F;</div><div class="kg-callout-text">Welcome to &quot;<strong><em>Byte-Sized,</em></strong>&quot; a series of brief, informative posts about quick programming techniques or code snippets. In this series, we&apos;ll cover a wide range of topics, from the basics of coding to the latest trends and technologies in the industry in short and sweet. Whether you&apos;re a beginner or an experienced programmer, our goal is to provide you with the knowledge and tools you need to take your skills to the next level. So, get ready to join us in a short post format.</div></div><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/02/7a0lbu.jpg" class="kg-image" alt="Console App with Dependency Injection" loading="lazy" width="612" height="408" srcset="https://csandunblogs.com/content/images/size/w600/2023/02/7a0lbu.jpg 600w, https://csandunblogs.com/content/images/2023/02/7a0lbu.jpg 612w"></figure><p>To kick off our series, let&apos;s apply Dependency Injection to Asp.net Core Console App.</p><h2 id="byte-sized-01-context">Byte-Sized 01 Context</h2><p>In my previous company, we relied heavily on console applications and windows services to automate various tasks and processes. In this context, I applied Dependency Inject into the Console Apps.</p><p>I got several benefits: increased flexibility and improved testability, better code reuse, easier maintenance, and improved code organization. Also, it helps to make the application more scalable and maintainable, ultimately resulting in better performance and quality.</p><h2 id="how-to-apply-dependency-injection-di-in-a-console-application">How to apply Dependency Injection (DI) in a console application</h2><h3 id="1-create-dotnet-7-console-app">1. Create dotnet 7 Console App </h3><p>Create an empty console app using your IDE or dotnet CLI . Here I am using Rider. You can use &#xA0;blow command in dotnet CLI</p><pre><code class="language-terminal">dotnet new console</code></pre><p>When create a console app, you can see a simple &apos;Hello world&apos; &#xA0;application like this.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/02/1.png" class="kg-image" alt="Console App with Dependency Injection" loading="lazy" width="943" height="252" srcset="https://csandunblogs.com/content/images/size/w600/2023/02/1.png 600w, https://csandunblogs.com/content/images/2023/02/1.png 943w" sizes="(min-width: 720px) 720px"></figure><h3 id="2-create-a-mock-service-with-interface-as-business-logic">2. Create a mock service with interface as business logic</h3><!--kg-card-begin: markdown--><p>Well, Then I create a mock business service called <code>CustomerService</code>. As well <code>ICustomerService</code>. Today we are going to register this service in DI layer.</p>
<!--kg-card-end: markdown--><figure class="kg-card kg-code-card"><pre><code class="language-csharp">public interface ICustomerService
{
    public void CalculateCustomerAge(int id);

}</code></pre><figcaption>ICustomerService.cs</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-chsarp">public class CustomerService: ICustomerService
{
    public void CalculateCustomerAge(int id)
    {
        Console.WriteLine(&quot;CustomerService:CalculateCustomerAge runs&quot;);
    }
}</code></pre><figcaption>CustomerService.cs</figcaption></figure><h3 id="3-setup-host">3. Setup Host</h3><p><strong>1. Add relevant NuGet packages</strong></p><!--kg-card-begin: markdown--><p>Add the <code>Microsoft.Extensions.DependencyInjection</code> NuGet package to your project using dotnet CLI.</p>
<!--kg-card-end: markdown--><pre><code class="language-terminal">dotnet add package Microsoft.Extensions.DependencyInjection --version 7.0.0</code></pre><!--kg-card-begin: markdown--><p>Also we want <code>Microsoft.Extensions.Hosting </code> to add hosting and startup infrastructure for the application</p>
<!--kg-card-end: markdown--><pre><code class="language-terminal">dotnet add package Microsoft.Extensions.Hosting --version 7.0.0</code></pre><p><strong>2. Put code snippets to create builder and DI layer</strong></p><p>In the Main method of the console application, create a new <code>HostBuilder</code> object, and register your concrete implementation with the service collection. </p><figure class="kg-card kg-code-card"><pre><code class="language-csharp">// create hosting object and DI layer
using IHost host = CreateHostBuilder(args).Build();

// create a service scope
using var scope = host.Services.CreateScope();

var services = scope.ServiceProvider;


// add entry point or call service methods
// more .....


// implementatinon of &apos;CreateHostBuilder&apos; static method and create host object
IHostBuilder CreateHostBuilder(string[] strings)
{
    return Host.CreateDefaultBuilder()
        .ConfigureServices((_, services) =&gt;
        {
            services.AddSingleton&lt;ICustomerService, CustomerService&gt;();
            services.AddSingleton&lt;App&gt;();
        });
}
</code></pre><figcaption>Program.cs</figcaption></figure><p>Here you can register our <code>CustomerService</code> mock service in Dependency layer.</p><h3 id="4-add-entry-point-to-application">4. Add Entry point to Application</h3><p>Create a <code>App</code> class as a entry class with <code>Run()</code> entry method.</p><figure class="kg-card kg-code-card"><pre><code class="language-csharp">public class App
{
    private readonly ICustomerService _customerService;
    
    public App(ICustomerService customerService)
    {
        _customerService = customerService;
    }

    public void Run(string[] args)
    {
        _customerService.CalculateCustomerAge(1);
    }
}</code></pre><figcaption>App.cs</figcaption></figure><p>You can access console arguments from <code>args</code> string property. Also you should register <code>App</code> class in DI layer</p><pre><code class="language-csharp">IHostBuilder CreateHostBuilder(string[] strings)
{
    return Host.CreateDefaultBuilder()
        .ConfigureServices((_, services) =&gt;
        {
            services.AddSingleton&lt;ICustomerService, CustomerService&gt;();
            services.AddSingleton&lt;App&gt;(); // -&gt; register App class 
        });
}</code></pre><p>In <code>Program.cs</code> we can call Run method as below.</p><pre><code class="language-csharp">// ....

var services = scope.ServiceProvider;

try
{
    services.GetRequiredService&lt;App&gt;().Run(args);
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}


//...</code></pre><p>Time to run the your first &quot;<strong>Hello World&quot; </strong>Console application with Depencency Injection.</p><hr><h2 id="full-program-class">Full Program Class</h2><figure class="kg-card kg-code-card"><pre><code class="language-csharp">using ConsoleAppWithDI;
using ConsoleAppWithDI.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using IHost host = CreateHostBuilder(args).Build();
using var scope = host.Services.CreateScope();

var services = scope.ServiceProvider;

try
{
    services.GetRequiredService&lt;App&gt;().Run(args);
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

IHostBuilder CreateHostBuilder(string[] strings)
{
    return Host.CreateDefaultBuilder()
        .ConfigureServices((_, services) =&gt;
        {
            services.AddSingleton&lt;ICustomerService, CustomerService&gt;();
            services.AddSingleton&lt;App&gt;();
        });
}</code></pre><figcaption>Full Program.cs</figcaption></figure><h2 id="source-code-repository">Source Code repository</h2><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/csandun/ConsoleAppWithDI"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - csandun/ConsoleAppWithDI</div><div class="kg-bookmark-description">Contribute to csandun/ConsoleAppWithDI development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Console App with Dependency Injection"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">csandun</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/3e31dccc8b04a7bd2b7fffa8ebec2b619743cbc13fb50704bdd22730eca66ff8/csandun/ConsoleAppWithDI" alt="Console App with Dependency Injection"></div></a></figure><hr><h2 id="resources">Resources</h2><ol><li><a href="https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration">Documentation</a></li><li><a href="https://www.youtube.com/watch?v=GAOCe-2nXqc">From Tom Coory</a> <strong>| From Youtube </strong></li></ol><hr><h3 id="next-step">Next Step:</h3><p>The next step in this blog series can be to add an appsettings.json file and read configuration and add logs in your ASP.NET Core console application under DI framework. Keep in touch this valueable short series.</p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F4E8;</div><div class="kg-callout-text">Put your comments on this topic. See ya soon on another blog post. &#x1F44A;&#x1F44A;</div></div>]]></content:encoded></item><item><title><![CDATA[Efficient way to use empty Enumerable]]></title><description><![CDATA[Today's blog post is about efficient and effective ways to return an empty IEnumerable from a method]]></description><link>https://csandunblogs.com/ways-to-use-empty-enumerable/</link><guid isPermaLink="false">63dbdde5be906f04bc86ec42</guid><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[Performance]]></category><category><![CDATA[CSharp]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Thu, 02 Feb 2023 17:10:18 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/02/Empty-enumurable-1.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/02/Empty-enumurable-1.png" alt="Efficient way to use empty Enumerable"><p>Today&apos;s blog post is about efficient and effective ways to return an empty <strong>IEnumerable</strong> from a method. &#xA0;Many developers need to be aware of the different options available. &#xA0;Still, with the help of some benchmark testing and a deep dive into the appropriate methods, we will clear up any confusion and provide a comprehensive guide. &#xA0;By the end of this post, you will have a solid understanding of the<strong> most efficient ways</strong> to return an empty <strong>IEnumerable </strong>from a method and be equipped to make informed decisions for your projects.</p><h2 id="intro">Intro</h2><p>As per my experience, &#xA0;there are three common ways to return an empty <strong>IEnumerable </strong>from a method:</p><h3 id="1-new-listt">1. new List&lt;T&gt;()</h3><p>This creates a <strong>new instance</strong> of an empty List object, which implements the <strong>IEnumerable </strong>interface. &#xA0;This method is so straightforward.</p><h3 id="2-new-listt0">2. new List&lt;T&gt;(0)</h3><!--kg-card-begin: markdown--><p>This creates a <strong>new instance</strong> of a List object with <strong>an initial capacity of 0 (zero)</strong>.  This method is similar to <code>new List ()</code>.</p>
<!--kg-card-end: markdown--><h3 id="3-enumerableemptyt">3. Enumerable.Empty&lt;T&gt;()</h3><p>This method returns a singleton instance of an empty <strong>IEnumerable </strong>object.</p><h2 id="benchmarking">Benchmarking </h2><p>Let&apos;s talk about these methods behave in a <strong>benchmark test</strong>. &#xA0;According to the results, we can deep-dive into the method&apos;s actual implementation.</p><p>Let&apos;s examine further by benchmarking the performance using <strong>Benchmark.Net</strong>. &#xA0;For the tests, let&apos;s create the following class.</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/42263e4d821c20c4ea65746ea9522257.js"></script><!--kg-card-end: html--><p>After benchmarking, I got the below results for m<strong>emory allocation</strong> and <strong>execution time</strong>.</p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://csandunblogs.com/content/images/2023/02/emem.png" class="kg-image" alt="Efficient way to use empty Enumerable" loading="lazy" width="744" height="147" srcset="https://csandunblogs.com/content/images/size/w600/2023/02/emem.png 600w, https://csandunblogs.com/content/images/2023/02/emem.png 744w"></figure><p>As you can see, though the <strong>StaticEmptyMethod</strong> is <strong>slightly faster</strong>, it also <strong>consumes non of the memory</strong>. &#xA0;How does it happen? &#xA0;It&apos;s time to investigate the reasons.</p><h2 id="why-new-list-bit-slow-than-others">Why new List() bit slow than others</h2><p>This method is straightforward but can result in <strong>unnecessary object creation, affecting performance</strong>, especially in situations where the empty collection is returned frequently. &#xA0;As well, every time it allocates memory for the new List.<br><br>Additionally, it creates a list with an<strong> initial capacity of 0</strong>, but the capacity is <strong>automatically resized as elements are added to the list</strong>. &#xA0;This means that the list will be<strong> resized multiple times</strong> as elements are added, which can affect performance.</p><h2 id="why-new-list0-bit-efficient-than-new-list">Why new List(0) bit efficient than new List()</h2><p>This method is similar to <strong><em>new List ()</em></strong> but provides a more efficient way to create an empty list when you know <strong>the final size of the List will be 0</strong>. &#xA0;<strong>This means that the list will not need to be resized as elements are added, resulting in more efficient performance.</strong></p><h2 id="why-does-enumerableempty-show-well-efficient-than-others">Why does Enumerable.Empty() show well efficient than others</h2><p>As you can see <a href="https://github.com/Microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs">here</a>, <em><strong>Empty()</strong></em> is just a static method returning <em>Instance</em> from <strong><em>EmptyEnumerable</em> </strong>class&#x2026;</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/0ba2369af913cc6fbb93ace4754dafaa.js"></script><!--kg-card-end: html--><p>going bit further....</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/a370a51e4f3766e92bd756144b07abe1.js"></script><!--kg-card-end: html--><p>Oh, look, just a static property of a 0-sized array! &#xA0;So every time we call <em><strong>Enumerable.Empty&lt;T&gt;();</strong></em> we get the same array. &#xA0;So when we call <em><strong>Enumerable.Empty&lt;T&gt;()</strong></em> 100 times; again there will be just 1 array more in the memory instead of 100. &#xA0;So there is not 100 memory allocations 100 times. &#xA0;Wow, It is an awasome practice by Microsoft.<br><br>Also interesting code commit there:</p><blockquote>// We have added some optimization in SZArrayHelper class to cache the enumerator of zero length arrays so<br>// the enumerator will be created once per type.</blockquote><div class="kg-card kg-callout-card kg-callout-card-purple"><div class="kg-callout-emoji">&#x1F929;</div><div class="kg-callout-text">Well they <strong>cache </strong>it, <strong>singleton </strong>it, and returns <strong>one static instance.</strong></div></div><div class="kg-card kg-callout-card kg-callout-card-blue"><div class="kg-callout-emoji">&#x26A0;&#xFE0F;</div><div class="kg-callout-text">Interesting:<br>If you love to know how do Enumurables working behind the sence, please refer this sourcecode. It will give you the ground level experience on the .Net practices.</div></div><p>Also <strong><em>Enumerable.Empty()</em></strong> added consistency for the code.<br>Using <strong><em>Enumerable.Empty()</em></strong> makes it clear that the intention is to return an empty collection, rather than a collection with a specific number of elements. This can<strong> improve code readability and maintainability</strong>.</p><p>Also can ensure consistency throughout your codebase and make it easier to maintain a common pattern for creating empty collections.</p><h2 id="my-thoughts-and-conclusion">My Thoughts and Conclusion</h2><p>In terms of memory usage,<strong> </strong>&#x26A1;&#xFE0F;<em><strong>Enumerable.Empty()</strong>&#x26A1;&#xFE0F;<strong> is more efficient</strong></em> because it returns a reference to <strong><em>a singleton instance</em></strong> of an empty collection, rather than creating a <strong><em>new instance each time</em></strong> it&apos;s called. This helps <em>r<strong>educe the number of objects created</strong>,</em> which can be beneficial in terms of both <em><strong>memory and performance</strong>.</em><br>Additionally, using <strong>Enumerable.Empty()</strong> can also<strong> improve code readability and maintainability</strong> by making it clear that the intention is to return an empty collection, rather than a collection with a specific number of elements.</p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F47D;</div><div class="kg-callout-text"><strong>So, in conclusion, if you want to create an empty enumerable in C#, it&apos;s best to use</strong>&#x26A1;&#xFE0F;<strong> Enumerable.Empty()</strong>&#x26A1;&#xFE0F;<strong>.</strong></div></div><hr><h2 id="resources">Resources</h2><ol><li><a href="https://bytelanguage.com/2018/07/27/enumerable-empty-vs-array-initialization-syntax/">https://bytelanguage.com/2018/07/27/enumerable-empty-vs-array-initialization-syntax/</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.empty?view=net-7.0">https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.empty?view=net-7.0</a> &#x1F525;&#x1F525;</li><li>Source code of <strong>Enumerable class</strong> in Github</li></ol><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/Microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs"><div class="kg-bookmark-content"><div class="kg-bookmark-title">referencesource/Enumerable.cs at master &#xB7; microsoft/referencesource</div><div class="kg-bookmark-description">Source from the Microsoft .NET Reference Source that represent a subset of the .NET Framework - referencesource/Enumerable.cs at master &#xB7; microsoft/referencesource</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Efficient way to use empty Enumerable"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">microsoft</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/96dc8edcbe1894d706733e789fe0070599aa6061bce95dfe46b9222c047af074/microsoft/referencesource" alt="Efficient way to use empty Enumerable"></div></a></figure><hr><h2 id="source-code">Source Code</h2><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/csandun/WaysToReturnEmptyEnumurable"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - csandun/WaysToReturnEmptyEnumurable</div><div class="kg-bookmark-description">Contribute to csandun/WaysToReturnEmptyEnumurable development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Efficient way to use empty Enumerable"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">csandun</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/aaae04be7556b17cd6bfe1613437f259f3c38d7ae9d01c2e039cd653fa66c0bc/csandun/WaysToReturnEmptyEnumurable" alt="Efficient way to use empty Enumerable"></div></a></figure><p></p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F4E8;</div><div class="kg-callout-text">Put your comments on this topic. See ya soon on another blog post. &#x1F44A;&#x1F44A;</div></div>]]></content:encoded></item><item><title><![CDATA[ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty guard clauses]]></title><description><![CDATA[ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty had been introduced as guard clause in .NET 6  and .NET 7 releases. They will help to throw null exceptions cleaner way.]]></description><link>https://csandunblogs.com/argumentexception-throwifnull-and-argumentexception-throwifnullorempty-guard-clauses-c-new-features/</link><guid isPermaLink="false">63cbf148be906f04bc86eb4d</guid><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[CSharp]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Sat, 21 Jan 2023 14:59:17 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/01/argumentexception.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/01/argumentexception.png" alt="ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty guard clauses"><p><strong>ArgumentException.ThrowIfNull</strong> and <strong>ArgumentException.ThrowIfNullOrEmpty </strong>had been introduced as guard clause in .NET 6 &#xA0;and .NET 7 releases. They will help to throw null exceptions cleaner way.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/01/simplifying-the-code.jpg" class="kg-image" alt="ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty guard clauses" loading="lazy" width="600" height="400" srcset="https://csandunblogs.com/content/images/2023/01/simplifying-the-code.jpg 600w"></figure><h2 id="what-is-argumentexception">What is ArgumentException</h2><p><strong>ArgumentNullException</strong> is a class in the .NET Framework that represents an exception when <strong>a null reference</strong> is passed to a method that does not accept it as a valid argument. This exception is thrown when a method or constructor is called with <strong>a null argument</strong>, and the method or constructor is not designed to handle that.</p><p>It is typically thrown by the <strong>runtime</strong> when a null argument is passed to a method or constructor that doesn&apos;t accept it. It can also be thrown explicitly by the developer by using the throw keyword, along with a new instance of the ArgumentNullException class, to indicate that a null argument is not valid for the method or constructor being called.</p><p><strong>Prior to C# 10 </strong>you may have had code similar to the following using ArgumentNullException.</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/7a1e2b24b9986ece1f30de994a0c4257.js"></script><!--kg-card-end: html--><p>If the parameter <strong>&apos;Summary&apos;</strong> is null, then an <strong>ArgumentNullException</strong> will be thrown.</p><h2 id="newly-added-argumentnullexception-guard-clause"><strong>Newly added ArgumentNullException guard clause</strong></h2><p>C# 10 (.NET 6) and C# 11 (.NET 7) introduced an improved way to avoid robust code. They are working like guard clauses.</p><div class="kg-card kg-callout-card kg-callout-card-purple"><div class="kg-callout-emoji">&#x1F4A5;</div><div class="kg-callout-text"><strong>C# 10 (.NET 6) - ArgumentException.ThrowIfNull<br><br>C# 11 (.NET 7) - ArgumentException.ThrowIfNullOrEmpty</strong><br></div></div><h3 id="usage">Usage</h3><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/a62df23bf89d322c9efe6b178fd1adf8.js"></script><!--kg-card-end: html--><p>In the preceding code, a new static method called <strong>ThrowIfNull and </strong> ThrowIfNullOrEmpty have been added to the <strong>ArgumentNullException</strong> class and allow us to check and throw ArgumentNullExceptions quickly.</p><p>Using this kind of guard clauses instead of if statement checks results in <strong>cleaner code</strong>.</p><hr><p>I like it; hopefully, Microsoft can continue adding more guard clauses in future .NET releases.</p><p>Until they release, I am using two excellent libraries from the open-source community.</p><ol><li>amantinband/<strong>throw</strong></li></ol><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/amantinband/throw"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - amantinband/throw: A simple, fluent, extensible, and fully customizable library for throwing exceptions for projects using .NET 6+</div><div class="kg-bookmark-description">A simple, fluent, extensible, and fully customizable library for throwing exceptions for projects using .NET 6+ - GitHub - amantinband/throw: A simple, fluent, extensible, and fully customizable li...</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty guard clauses"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">amantinband</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/de44a346f263fa25a49bddec93b6447a6f1359f5b938a76ab15ba7527c38aac8/amantinband/throw" alt="ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty guard clauses"></div></a></figure><p>2. ardalis/<strong>GuardClauses</strong></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href=" https://github.com/ardalis/GuardClauses"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - ardalis/GuardClauses: A simple package with guard clause extensions.</div><div class="kg-bookmark-description">A simple package with guard clause extensions. Contribute to ardalis/GuardClauses development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty guard clauses"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">ardalis</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://repository-images.githubusercontent.com/103309798/d4d97280-cc28-11ea-9a39-0694d0ce617e" alt="ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty guard clauses"></div></a></figure><p>This is a trendy library through .NET people. Which is a set of best practices for input validation and error handling in C# code, developed by Steve Smith (ardalis)</p><div class="kg-card kg-callout-card kg-callout-card-blue"><div class="kg-callout-emoji">&#x1F4AC;</div><div class="kg-callout-text">Lets talk guard clauses and above library in the near future. Keep in touch with my blog.</div></div><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F4AC;</div><div class="kg-callout-text">Put your valuable comments on this topic. See ya soon on another blog post. &#x1F44A;&#x1F44A;<br>Happy coding....!</div></div><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Angular deep copy]]></title><description><![CDATA[Here we will identify Deep copy/ Deep clone methods and their behavior and performances in JavaScript and Typescript.       ]]></description><link>https://csandunblogs.com/angular-deep-copy-methods/</link><guid isPermaLink="false">63c3de74be906f04bc86e896</guid><category><![CDATA[Angular]]></category><category><![CDATA[Performance]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Sun, 15 Jan 2023 14:03:56 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/01/deepcopy.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/01/deepcopy.png" alt="Angular deep copy"><p>Here we will identify Deep copy/ Deep clone methods and their behavior and performances in JavaScript and Typescript. &#xA0; &#xA0; &#xA0; &#xA0; &#xA0; &#xA0; &#xA0; &#xA0; &#xA0; &#xA0; &#xA0; &#xA0;</p><h2 id="introduction">Introduction</h2><h3 id="what-is-deep-copy">What is Deep Copy</h3><p>In JavaScript/Typescript, a deep copy is a copy of an object that creates a new instance of the object rather than simply creating a reference to the original object. Any changes to the copied object will not affect the original object and vice versa.</p><p>This Copy that will be a faithful reflection of the base object, with all attributes and fields at every nesting level into &#xA0;new references.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/01/image-4.png" class="kg-image" alt="Angular deep copy" loading="lazy" width="2000" height="1699" srcset="https://csandunblogs.com/content/images/size/w600/2023/01/image-4.png 600w, https://csandunblogs.com/content/images/size/w1000/2023/01/image-4.png 1000w, https://csandunblogs.com/content/images/size/w1600/2023/01/image-4.png 1600w, https://csandunblogs.com/content/images/2023/01/image-4.png 2118w" sizes="(min-width: 720px) 720px"></figure><h3 id="why-deep-copy">Why Deep Copy</h3><p>The purpose of a deep copy in Angular is to create a new instance of an object completely independent of the original object. This is useful when you want to change an object without affecting the original object, such as when working with data that should not be modified.</p><p>For example, when creating a new component in Angular, you may want to pass data to that component without modifying the original data. Using a deep copy ensures that any changes made to the data within the component do not affect the original data.</p><p>Additionally, when you have a large and complex data structure, using a deep copy can be useful to create a new copy of the data and keep the original data intact.</p><p>In general, it&apos;s a good practice to use deep copy when working with data in Angular to avoid unintended side-effects that could occur as a result of modifying the original data.</p><h3 id="deep-copy-vs-shallow-copy">Deep Copy vs Shallow Copy</h3><p>A shallow copy, on the other hand, creates a new instance of the object but it only copies the reference of the nested objects, not the nested objects themselves. This means that any changes made to the nested objects in the copied object will also affect the original object, and vice versa.</p><p>When we talk about Angular deep copy, Shallow copy cannot be forgotten. I will discuss Shallow Copy in a separate blog post in the future.</p><hr><h2 id="deep-copy-methods">Deep Copy Methods</h2><p>A deep copy can be created in several ways, including:</p><h2 id="1-using-json-stringify-function">1. &#xA0;Using JSON stringify function</h2><p>This method uses the built-in JSON object to convert the object to a JSON string, and then parse it back into an object. This method is simple and works for most basic objects.</p><figure class="kg-card kg-code-card"><pre><code class="language-javascript">let obj2 = JSON.parse(JSON.stringify(obj));</code></pre><figcaption>JSON stringify function</figcaption></figure><h3 id="do-not-use-in">Do not Use in</h3><div class="kg-card kg-callout-card kg-callout-card-red"><div class="kg-callout-emoji">&#x274C;</div><div class="kg-callout-text">This does not work for objects with methods or <strong>circular references</strong>.</div></div><div class="kg-card kg-callout-card kg-callout-card-red"><div class="kg-callout-emoji">&#x274C;</div><div class="kg-callout-text">If your object contains: <strong>Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types.</strong></div></div><h3 id="best-to-use">Best to use</h3><div class="kg-card kg-callout-card kg-callout-card-green"><div class="kg-callout-emoji">&#x2705;</div><div class="kg-callout-text"><strong>Small object</strong> can be use easily. and this can be <strong>relatively fast </strong>for them</div></div><h2 id="2-using-lodashclonedeepobj-method">2. &#xA0;Using <a href="https://www.npmjs.com/package/lodash">lodash</a>.cloneDeep(obj) method</h2><p>This method uses the <strong><em>lodash library </em></strong>to create a deep copy of an object. </p><p>You need to install the<strong> <code>lodash</code></strong> library first by running <code><strong>npm install lodash</strong></code> and then import it in your component or service where you want to use it:</p><figure class="kg-card kg-code-card"><pre><code class="language-javascript">import * as _ from &apos;lodash&apos;;

let obj2 = _.cloneDeep(obj);</code></pre><figcaption><a href="https://www.npmjs.com/package/lodash">lodash</a>.cloneDeep(obj)</figcaption></figure><h3 id="warning">Warning</h3><div class="kg-card kg-callout-card kg-callout-card-yellow"><div class="kg-callout-emoji">&#x26A0;&#xFE0F;</div><div class="kg-callout-text">This method can be slower than JSON method in large object.</div></div><h3 id="best-to-use-1">Best to use</h3><div class="kg-card kg-callout-card kg-callout-card-green"><div class="kg-callout-emoji">&#x2705;</div><div class="kg-callout-text">It can handle <strong>large objects</strong> and <strong>preserve all data types. </strong>&#xA0;It is a good sign to use it.</div></div><h2 id="3-%F0%9F%94%A5%F0%9F%94%A5-angular-devkit-deepcloneobj-method%F0%9F%94%A5%F0%9F%94%A5">3. &#x1F525;&#x1F525; <a href="https://www.npmjs.com/package/@angular-devkit/build-angular">@angular-devkit</a> deepClone(obj) method&#x1F525;&#x1F525;</h2><p>This method creates a deep copy of an object using the <strong><code>deepClone</code></strong> &#xA0;method from the<strong> <code>@angular-devkit/core</code></strong> package. It can handle large objects and preserve all data types. But it requires an additional package to be installed and imported.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.npmjs.com/package/@angular-devkit/build-angular"><div class="kg-bookmark-content"><div class="kg-bookmark-title">@angular-devkit/build-angular</div><div class="kg-bookmark-description">Angular Webpack Build Facade. Latest version: 15.1.1, last published: 3 days ago. Start using @angular-devkit/build-angular in your project by running `npm i @angular-devkit/build-angular`. There are 197 other projects in the npm registry using @angular-devkit/build-angular.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.npmjs.com/1996fcfdf7ca81ea795f67f093d7f449.png" alt="Angular deep copy"><span class="kg-bookmark-author">npm</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://static.npmjs.com/338e4905a2684ca96e08c7780fc68412.png" alt="Angular deep copy"></div></a></figure><figure class="kg-card kg-code-card"><pre><code class="language-javascript">import { deepClone } from &apos;@angular-devkit/core&apos;;

let obj2 = deepClone(obj);</code></pre><figcaption><a href="https://www.npmjs.com/package/@angular-devkit/build-angular">@angular-devkit</a> deepClone(obj)</figcaption></figure><h3 id="warning-1">Warning</h3><div class="kg-card kg-callout-card kg-callout-card-yellow"><div class="kg-callout-emoji">&#x26A0;&#xFE0F;</div><div class="kg-callout-text"><strong>Since v12.0</strong>, unused by the Angular tooling. So this is currently <strong>deprecated</strong>.</div></div><h3 id="best-to-use-2">Best to use</h3><div class="kg-card kg-callout-card kg-callout-card-green"><div class="kg-callout-emoji">&#x2705;</div><div class="kg-callout-text">It can handle <strong>large objects</strong> and <strong>preserve all data types.</strong></div></div><div class="kg-card kg-callout-card kg-callout-card-green"><div class="kg-callout-emoji">&#x2705;</div><div class="kg-callout-text">Comparatively, this method is <strong>faster than</strong> <em>JSON </em>and <em>loadsh </em>methods in <strong>large objects</strong>.&#xA0;</div></div><blockquote>Even <strong>deprecated</strong>, this would be my favorite method to deep copy JavaScript objects.</blockquote><h2 id="4-objectassign-obj-nested-properties-are-shallow-copy">4. &#xA0;Object.assign({}, obj) (nested properties are shallow copy)</h2><p>This method uses the built-in <strong>Object.assign</strong> method to create a new object with the properties of the original object. This method is also <strong>simple </strong>and works for <strong>most basic objects</strong>, but it only creates a <strong>shallow copy.</strong></p><figure class="kg-card kg-code-card"><pre><code class="language-javascript">let obj2 = Object.assign({}, obj);</code></pre><figcaption>Object.assign({}, obj)</figcaption></figure><h3 id="do-not-use-in-1">Do not Use in</h3><div class="kg-card kg-callout-card kg-callout-card-red"><div class="kg-callout-emoji">&#x274C;</div><div class="kg-callout-text">This is a <strong>shallow copy</strong> for the nested objects. <strong>So do not use for the large JavaScript objects.</strong></div></div><p>It creates a <strong>shallow copy</strong> of the object and nested objects within the original object are <strong>still references to the original objects</strong>.</p><h3 id="best-to-use-3">Best to use</h3><div class="kg-card kg-callout-card kg-callout-card-green"><div class="kg-callout-emoji">&#x2705;</div><div class="kg-callout-text"><strong>Very fast</strong> method for<strong> the small objects.</strong></div></div><p></p><h2 id="performance-comparison">Performance Comparison</h2><p>I am created a sample Angular application and tested above 4 methods using a benchmark library. </p><p>Here I am used<a href="https://www.npmjs.com/package/benchmark"> benchmark.js</a> npm library to compare methods.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.npmjs.com/package/benchmark"><div class="kg-bookmark-content"><div class="kg-bookmark-title">benchmark</div><div class="kg-bookmark-description">A benchmarking library that supports high-resolution timers &amp; returns statistically significant results.. Latest version: 2.1.4, last published: 6 years ago. Start using benchmark in your project by running `npm i benchmark`. There are 230 other projects in the npm registry using benchmark.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.npmjs.com/1996fcfdf7ca81ea795f67f093d7f449.png" alt="Angular deep copy"><span class="kg-bookmark-author">npm</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://static.npmjs.com/338e4905a2684ca96e08c7780fc68412.png" alt="Angular deep copy"></div></a></figure><h3 id="performance-results">Performance results</h3><p>Now lets check the performance comparisons. </p><!--kg-card-begin: markdown--><table>
<thead>
<tr>
<th></th>
<th><strong>Small Object (s)</strong></th>
<th><strong>Large Object (s)</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>JSON.parse(JSON.stringify(obj))</td>
<td>2.04783E-06</td>
<td>6.48E-06</td>
</tr>
<tr>
<td>Object.assign({},   obj)</td>
<td>7.39E-08</td>
<td>1.49E-07</td>
</tr>
<tr>
<td>lodash.cloneDeep(obj)</td>
<td>1.44E-06</td>
<td>7.59629E-06</td>
</tr>
<tr>
<td>devkit.deepCopy(obj)</td>
<td>6.23E-07</td>
<td>1.50492E-06</td>
</tr>
</tbody>
</table>
<!--kg-card-end: markdown--><p>Here I am simplify this table into a barchart.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/01/image-5.png" class="kg-image" alt="Angular deep copy" loading="lazy" width="1139" height="583" srcset="https://csandunblogs.com/content/images/size/w600/2023/01/image-5.png 600w, https://csandunblogs.com/content/images/size/w1000/2023/01/image-5.png 1000w, https://csandunblogs.com/content/images/2023/01/image-5.png 1139w" sizes="(min-width: 720px) 720px"></figure><h2 id="summarizing-with-performances">Summarizing with performances</h2><p>According to the benchmark test, the fastest way to &#xA0;<strong>Object.assign. Unfortunately it </strong>supports only <strong>shallow copy</strong>. </p><p>Both the <code>JSON.parse(JSON.stringify(obj))</code> and <code>@angular-devkit/core/src/utils/object.deepClone(obj)</code> methods can be good choices for deep copying large objects, depending on the specific requirements of your application.</p><h2 id="my-opinion">My opinion </h2><blockquote>Per the performance testing, &#x1F525;<strong>Devki</strong>t &#x1F525; will be a good choice for large and small objects with comparatively speed than other options and preserve all data types. If you do not have a specific requirement and do not like 3rd party libraries, the &#x1F525;<strong>JSON stringify function</strong>&#x1F525; best option.</blockquote><hr><h2 id="source-code">Source Code</h2><p>Before run this code install dependent libraries.</p><ol><li>loadsh</li><li>devkit</li><li>benchmark.js in npm</li></ol><figure class="kg-card kg-code-card"><pre><code class="language-javascript">import {Component} from &apos;@angular/core&apos;;
import * as Benchmark from &apos;benchmark&apos;;
import * as _ from &apos;lodash&apos;;
import {deepCopy} from &quot;@angular-devkit/core/src/utils/object&quot;;


@Component({
    selector: &apos;app-root&apos;,
    template: `
        &lt;h1&gt;Cloning Method Comparison&lt;/h1&gt;
    `
})
export class AppComponent {


    ngOnInit() {
        var obj = {
            name: &apos;John Doe&apos;,
            age: 30,
            address: {
                city: &apos;New York&apos;,
                country: &apos;USA&apos;
            }
        };

        const bench = new Benchmark.Suite(&apos;Cloning Method Comparison&apos;)
            .add(&apos;JSON.parse(JSON.stringify(obj))&apos;, () =&gt; {
                JSON.parse(JSON.stringify(obj))
            })
            .add(&apos;Object.assign({}, obj)&apos;, () =&gt; {
                Object.assign({}, obj)
            })
            .add(&apos;lodash.cloneDeep(obj)&apos;, () =&gt; {
                _.cloneDeep(obj)
            })
            .add(&apos; deepCopy(obj)&apos;, () =&gt; {
                deepCopy(obj)
            })
            .on(&apos;cycle&apos;, (event: any) =&gt; {
                console.log(String(event.target));
            })
            .on(&apos;complete&apos;, function () {
                bench.forEach((o: any) =&gt; {
                    console.log(o.stats.mean);
                });
            })
            .run({async: true});


        let obj2 = {
            orderNumber: 12345,
            customer: {
                firstName: &quot;John&quot;,
                lastName: &quot;Doe&quot;,
                email: &quot;john.doe@example.com&quot;,
                phone: &quot;555-555-5555&quot;
            },
            shippingAddress: {
                street: &quot;123 Main St&quot;,
                city: &quot;Anytown&quot;,
                state: &quot;CA&quot;,
                zip: &quot;12345&quot;
            },
            billingAddress: {
                street: &quot;456 Park Ave&quot;,
                city: &quot;Anytown&quot;,
                state: &quot;CA&quot;,
                zip: &quot;54321&quot;
            },
            items: [
                {
                    itemName: &quot;Item 1&quot;,
                    itemId: &quot;123&quot;,
                    quantity: 2,
                    price: 19.99
                },
                {
                    itemName: &quot;Item 2&quot;,
                    itemId: &quot;456&quot;,
                    quantity: 1,
                    price: 9.99
                },
                {
                    itemName: &quot;Item 3&quot;,
                    itemId: &quot;789&quot;,
                    quantity: 3,
                    price: 29.99
                }
            ],
            total: 89.97,
            status: &quot;Processing&quot;,
            placedOn: &quot;2022-12-01T09:30:00Z&quot;
        };

        const benchLargeObject = new Benchmark.Suite(&apos;Cloning Method Comparison&apos;)
            .add(&apos;JSON.parse(JSON.stringify(obj))&apos;, () =&gt; {
                JSON.parse(JSON.stringify(obj2))
            })
            .add(&apos;Object.assign({}, obj)&apos;, () =&gt; {
                Object.assign({}, obj2)
            })
            .add(&apos;lodash.cloneDeep(obj)&apos;, () =&gt; {
                _.cloneDeep(obj2)
            })
            .add(&apos;devkit.deepCopy(obj)&apos;, () =&gt; {
                deepCopy(obj)
            })
            .on(&apos;cycle&apos;, (event: any) =&gt; {
                console.log(String(event.target));
            })
            .on(&apos;complete&apos;, function() {
                benchLargeObject.forEach((o: any) =&gt; {
                    console.log(o.stats.mean);
                } );
            })
            .run({ async: true });
    }
}</code></pre><figcaption>How do I benchmark above methods</figcaption></figure><h2 id="resources">Resources</h2><ol><li><a href="https://frontbackend.com/javascript/what-is-the-the-fastest-way-to-deep-clone-an-object-in-javascript">What is the best and most efficient way to deep clone an object in JavaScript?</a></li><li><a href="https://blog.devgenius.io/angular-deep-copy-vs-shallow-copy-685511e43b42">Angular deep copy vs shallow copy</a> &#x1F525;</li></ol><hr><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F4E8;</div><div class="kg-callout-text">Put your comments on this topic. See ya soon on another blog post. &#x1F44A;&#x1F44A;</div></div>]]></content:encoded></item><item><title><![CDATA[Decorated Windows 11 Terminal   with oh-my-posh]]></title><description><![CDATA[Every day you see only a blinking cursor on Command Line or Powershell? No colors, same font every day. Do you want to change your windows Terminal beautiful way? ]]></description><link>https://csandunblogs.com/windows-11-terminal-decorate-like-a-boss-with-oh-my-posh-cascadia-code-nerd-fonts-and-powershell/</link><guid isPermaLink="false">63b9b5003b92180517341f6d</guid><category><![CDATA[PowerShell]]></category><category><![CDATA[Windows App]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Sat, 07 Jan 2023 18:48:25 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/01/colorful-termninal.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/01/colorful-termninal.png" alt="Decorated Windows 11 Terminal   with oh-my-posh"><p>Every day you see only a blinking cursor on Command Line or Powershell? No colors, same font every day. Do you want to change your windows in Terminal beautiful way?</p><p>This post is helping to customize your <strong>Windows 11 Terminal</strong> beautifully and nicely.</p><p>Below Terminal will use your dreamy <strong>Terminal </strong>today onwards.</p><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://csandunblogs.com/content/images/2023/01/image-1.png" class="kg-image" alt="Decorated Windows 11 Terminal   with oh-my-posh" loading="lazy" width="626" height="160" srcset="https://csandunblogs.com/content/images/size/w600/2023/01/image-1.png 600w, https://csandunblogs.com/content/images/2023/01/image-1.png 626w"><figcaption>csandun&apos;s decorated PowerShell</figcaption></figure><h2 id="pre-requisites">Pre Requisites</h2><h3 id="1-windows-11-terminal-windows-terminal-from-ms-store">1. Windows 11 Terminal / Windows Terminal &#xA0;from MS Store</h3><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://apps.microsoft.com/store/detail/windows-terminal/9N0DX20HK701?hl=en-in&amp;gl=in&amp;rtc=1"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Get Windows Terminal from the Microsoft Store</div><div class="kg-bookmark-description">The Windows Terminal is a modern, fast, efficient, powerful, and productive terminal application for users of command-line tools and shells like Command Prompt, PowerShell, and WSL. Its main features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering&#x2026;</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://apps.microsoft.com/store/images/logo-512x512.png?v=f2rydDlJdXXmnXiyZg1ubNHcwV62KQE8CXnBIZmf1u4" alt="Decorated Windows 11 Terminal   with oh-my-posh"></div></div><div class="kg-bookmark-thumbnail"><img src="https://microsoft-store.azurewebsites.net/store/detail/9N0DX20HK701/image" alt="Decorated Windows 11 Terminal   with oh-my-posh"></div></a></figure><h3 id="2oh-my-posh-packages">2.Oh-My-Posh packages</h3><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://ohmyposh.dev/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Home | Oh My Posh</div><div class="kg-bookmark-description">A prompt theme engine for any shell.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://ohmyposh.dev/img/favicon.ico" alt="Decorated Windows 11 Terminal   with oh-my-posh"><span class="kg-bookmark-author">Oh My Posh</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://ohmyposh.dev/img/logo.svg" alt="Decorated Windows 11 Terminal   with oh-my-posh"></div></a></figure><h3 id="3nerd-fonts">3.Nerd fonts</h3><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.nerdfonts.com/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Nerd Fonts - Iconic font aggregator, glyphs/icons collection, &amp; fonts patcher</div><div class="kg-bookmark-description">Iconic font aggregator, collection, &amp; patcher: 3,600+ glyph/icons, 40+ patched fonts: Hack, Source Code Pro, more. Popular glyph collections: Font Awesome, Octicons, Material Design Icons, and more</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.nerdfonts.com/assets/img/apple-touch-icon.png" alt="Decorated Windows 11 Terminal   with oh-my-posh"><span class="kg-bookmark-author">Nerd Fonts</span><span class="kg-bookmark-publisher">Ryan L McIntyre</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.nerdfonts.com/assets/img/sankey-glyphs-combined-diagram.png" alt="Decorated Windows 11 Terminal   with oh-my-posh"></div></a></figure><h3 id="4cascadia-code-fonts">4.Cascadia Code Fonts</h3><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/microsoft/cascadia-code"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - microsoft/cascadia-code: This is a fun, new monospaced font that includes programming ligatures and is designed to enhance the modern look and feel of the Windows Terminal.</div><div class="kg-bookmark-description">This is a fun, new monospaced font that includes programming ligatures and is designed to enhance the modern look and feel of the Windows Terminal. - GitHub - microsoft/cascadia-code: This is a fun...</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Decorated Windows 11 Terminal   with oh-my-posh"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">microsoft</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://repository-images.githubusercontent.com/196284711/55f53b00-e52b-11e9-97f3-0071ed0cb894" alt="Decorated Windows 11 Terminal   with oh-my-posh"></div></a></figure><hr><h2 id="steps-to-reach-your-dreamy-terminal">Steps to reach your dreamy Terminal</h2><h3 id="1-get-the-windows-terminal">1. Get The Windows Terminal</h3><ul><li>In<strong> Windows 11</strong>, you have an inbuilt Terminal application. You can find it through the apps list.</li><li>If you are using<strong> Windows 10</strong>, you want to download the Terminal from<strong> the Store</strong>. Here is the downloadable link for the <a href="https://apps.microsoft.com/store/detail/windows-terminal/9N0DX20HK701?hl=en-us&amp;gl=us">Windows Terminal</a>.</li></ul><h3 id="2-install-the-cascadia-code-font-and-nerd-font">2. Install the Cascadia Code font And Nerd Font</h3><h4 id="cascadia-code-font">Cascadia Code font</h4><p><strong>Cascadia Code</strong> is a power line compatible font that is already used in Visual studio as well. Cascadia Code has a unique and lovely character set most compatible with Terminal.</p><p>This link is the <a href="https://github.com/microsoft/cascadia-code/releases?WT.mc_id=-blog-scottha">Cascadia Code</a> release page.</p><h4 id="nerd-font">Nerd font</h4><p><strong>Nerd font </strong>has been used in Oh-My-Posh symbols. Download your favorite font style from <a href="https://www.nerdfonts.com/font-downloads">here</a>.</p><p>Here I am using &apos;<strong>Hack Nerd Font</strong>&apos; fonts. It is my favorite one through the Nerd font collection.</p><p>Then install both fonts in the windows font directory.</p><h3 id="3-install-oh-my-posh-packages-in-powershell">3. Install Oh-My-Posh packages in PowerShell</h3><p>The <strong>Oh-My-Posh</strong> is a <strong>theme engine for any shell</strong>. It is customizable, Portable, and colorable. Believe me, Oh-My-Posh is a friendly tool for customizing your Terminal.</p><div class="kg-card kg-callout-card kg-callout-card-yellow"><div class="kg-callout-emoji">&#x1F5A5;&#xFE0F;</div><div class="kg-callout-text"><em>Install these commands to install <strong>Oh-My-Posh</strong> modules. I recommend </em><a href="https://github.com/PowerShell/PowerShell/releases?WT.mc_id=-blog-scottha"><em>PowerShell 6.2.3 or above</em></a></div></div><p><strong>i. First</strong>, Open a PowerShell prompt and run the following command:</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/41c590f14f0c009c62690878d5649c27.js"></script><!--kg-card-end: html--><p>This command installs a couple of things:</p><!--kg-card-begin: markdown--><ul>
<li><strong>oh-my-posh.exe</strong> - Windows executable</li>
<li><strong>themes</strong> - The latest Oh My Posh themes</li>
</ul>
<!--kg-card-end: markdown--><h3 id="create-a-powershell-profile-and-add-theme-settings">Create a PowerShell profile and add theme settings</h3><p><strong>ii. Second</strong>, identify whether your Powershell profile file exists or not on your PC.</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/39d58ef629ca9fa636b69c21f1395e54.js"></script><!--kg-card-end: html--><p><strong>iii. Third</strong>, open notepad using</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/2607699094f670b649f2318a6a46f427.js"></script><!--kg-card-end: html--><p><strong>iv. Fourth</strong>, Add prompt command to the profile file.</p><p>Edit the profile file by adding this command.</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/d2391a8d163ed19dbfaf61fb54692223.js"></script><!--kg-card-end: html--><h3 id="customization-of-the-theme">Customization of the theme</h3><p>You can choose your favorite one through the plenty of themes by providing the <strong>Oh-My-Posh</strong> team. (<a href="https://ohmyposh.dev/docs/themes">Theme list</a>)</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://ohmyposh.dev/docs/themes"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Themes | Oh My Posh</div><div class="kg-bookmark-description">Oh My Posh comes with many themes included out-of-the-box. Below are some screenshots of the more common themes.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://ohmyposh.dev/img/favicon.ico" alt="Decorated Windows 11 Terminal   with oh-my-posh"><span class="kg-bookmark-author">Oh My Posh</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://ohmyposh.dev/assets/images/1_shell-11dcf5b96a8cc827259324ca6e9824c2.png" alt="Decorated Windows 11 Terminal   with oh-my-posh"></div></a></figure><p>You can change the theme using the <strong>theme path.</strong></p><p>There are two possible values the --config flag can handle:</p><ol><li><strong>A path to a local configuration file</strong></li></ol><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/d2391a8d163ed19dbfaf61fb54692223.js"></script><!--kg-card-end: html--><p><strong>2. &#xA0;A URL pointing to a remote config</strong></p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/5b0912b2f6b99743dae9fad0e64470b9.js"></script><!--kg-card-end: html--><p><strong>DONE !!!!</strong></p><p>Now you can see like this.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/01/image-2.png" class="kg-image" alt="Decorated Windows 11 Terminal   with oh-my-posh" loading="lazy" width="626" height="160" srcset="https://csandunblogs.com/content/images/size/w600/2023/01/image-2.png 600w, https://csandunblogs.com/content/images/2023/01/image-2.png 626w"></figure><hr><p><strong>Oh-My-Posh</strong> gives me an exciting look at the boring <strong>Windows Terminal</strong>. Come on!!!!! &#x270C;&#x1F602;</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/01/image-3.png" class="kg-image" alt="Decorated Windows 11 Terminal   with oh-my-posh" loading="lazy" width="229" height="220"></figure><p></p><h2 id="references">References</h2><ol><li><strong>Youtube </strong>- <a href="https://www.youtube.com/watch?v=lu__oGZVT98">How to set up an awesome prompt with your Git Branch, Windows Terminal, PowerShell, + Cascadia Code!</a></li><li><strong>BlogPost </strong>- <a href="https://www.hanselman.com/blog/how-to-make-a-pretty-prompt-in-windows-terminal-with-powerline-nerd-fonts-cascadia-code-wsl-and-ohmyposh">How to make a pretty prompt in Windows Terminal with Powerline, Nerd Fonts, Cascadia Code, WSL, and oh-my-posh</a></li><li><strong>oh-My-posh documentation - </strong><a href="https://ohmyposh.dev/docs/installation/windows">documentation</a></li></ol><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F5A5;&#xFE0F;</div><div class="kg-callout-text">Put your comments on this topic. See ya soon on another blog post. &#x1F44A;&#x1F44A;</div></div>]]></content:encoded></item><item><title><![CDATA[Reduce the size of a JPEG image comes from a byte array using Asp.net Core]]></title><description><![CDATA[C# code for efficiently reducing the size of a JPEG image based on the quality threshold.]]></description><link>https://csandunblogs.com/reduce-the-size-of-an-jpeg-image-comes-from-byte-array-using-c/</link><guid isPermaLink="false">63b8d6223b92180517341f1c</guid><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[CSharp]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Sat, 07 Jan 2023 02:55:41 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2023/01/Image-reduse.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2023/01/Image-reduse.png" alt="Reduce the size of a JPEG image comes from a byte array using Asp.net Core"><p>C# code for efficiently reducing the size of a JPEG image based on the quality threshold.</p><h2 id="usecase">Usecase</h2><p>If you remember, I posted a blog post last week on &quot;<a href="https://csandunblogs.com/convert-base64-string-to-image-and-show-in-a-table-using-angular-pipe/">Convert base64 string to image and showing in a table using Angular Pipe.</a>&quot; In this blog post, I used a byte array to show the table through angular code.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://csandunblogs.com/convert-base64-string-to-image-and-show-in-a-table-using-angular-pipe/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Convert base64 string to image and show in a table using Angular Pipe</div><div class="kg-bookmark-description">Parameterize Pipe to transform the base64array string to a base64 image</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://csandunblogs.com/content/images/size/w256h256/2022/12/favicon.png" alt="Reduce the size of a JPEG image comes from a byte array using Asp.net Core"><span class="kg-bookmark-author">CSandun Blogs</span><span class="kg-bookmark-publisher">Chathuranga</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://csandunblogs.com/content/images/2022/12/pipe.png" alt="Reduce the size of a JPEG image comes from a byte array using Asp.net Core"></div></a></figure><p>Accidently, I got a performance <strong>issue </strong>on the API side because t<strong>he API call is too slow when I am using large files</strong>. QA engineers also reported it.</p><h2 id="how-do-i-fix-the-above-issue">How do I fix the above issue?</h2><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F6A7;</div><div class="kg-callout-text">I used <strong>image-reducing size </strong>based on <strong>quality drop </strong>using the c# code. <u>I assumed the image view was only in a table column in a small space</u>.</div></div><h2 id="working-on-the-problem">Working on the problem</h2><p>I used the below method to reduce the size of the image quality.</p><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/b493930b8ac45efadb2a34ae8b179e40.js"></script><!--kg-card-end: html--><h2 id="explanation">Explanation</h2><p>Decreasing the size of a <strong>JPEG image</strong> by increasing the compression will also decrease the quality of the image. I reduced the size of a JPEG image using the <strong><a href="https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image?redirectedfrom=MSDN&amp;view=dotnet-plat-ext-6.0">Image </a></strong>class.</p><p>By decreasing the <strong>jpegQuality </strong>(<strong>which should be 0-100</strong>),<u> you can increase the compression at the cost of lower image quality</u>. See the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.drawing.imaging.encoder.quality?redirectedfrom=MSDN&amp;view=dotnet-plat-ext-6.0">Encoder.Quality</a> field for more information.</p><p>Here is an example where you can see how <strong>jpegQuality </strong>affects image quality.</p><!--kg-card-begin: markdown--><table>
<thead>
<tr>
<th>#</th>
<th>JPEG QUALITY RATIO</th>
<th>IMAGE SIZE</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>20</td>
<td>4.99 kb</td>
</tr>
<tr>
<td>2</td>
<td>50</td>
<td>8.28 kb</td>
</tr>
<tr>
<td>3</td>
<td>80</td>
<td>12.9 kb</td>
</tr>
</tbody>
</table>
<!--kg-card-end: markdown--><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2023/01/image.png" class="kg-image" alt="Reduce the size of a JPEG image comes from a byte array using Asp.net Core" loading="lazy" width="630" height="354" srcset="https://csandunblogs.com/content/images/size/w600/2023/01/image.png 600w, https://csandunblogs.com/content/images/2023/01/image.png 630w"></figure><p></p><hr><p>This is how I fixed the performance issue reported by QA engineers. I hope you will learn something from my mistaken issue.</p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F6A7;</div><div class="kg-callout-text">Keep touching my diaries. Learn something new. Comment your thoughts and share the content.<br><br><em>Thank you.!</em><br><em>Have an incredible coding journey.</em><br><em>See you soon. &#x270C;&#x270C;&#x270C;</em></div></div><p></p>]]></content:encoded></item><item><title><![CDATA[REST API Best Practices with a Mind Map]]></title><description><![CDATA[Summarizing REST API Best Practices with a mind map. REST (Representational State Transfer) is a software architectural style that defines a set of constraints to be used for creating Web services.]]></description><link>https://csandunblogs.com/rest-api-best-practices-with-mind-map/</link><guid isPermaLink="false">63ae1e652be67904bb426f0e</guid><category><![CDATA[REST API]]></category><category><![CDATA[MindMaps]]></category><category><![CDATA[csandun]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Thu, 29 Dec 2022 23:29:14 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2022/12/rest-api-best-practices.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2022/12/rest-api-best-practices.png" alt="REST API Best Practices with a Mind Map"><p>Summary of the best practices of REST API with a huge mind map.<br>&quot;<a href="https://www.oreilly.com/library/view/rest-api-design/9781449317904/"><strong>REST API Design Rulebook</strong></a>&quot; is a book by <strong>Mark Masse</strong> that provides <strong>guidelines for designing REST APIs</strong>. Here I used it as a reference to define <strong>my rule set </strong>and the best practices.</p><h2 id="introduction">Introduction</h2><p>As a developer, you may find yourself needing to build or consume a REST API at some point in your career. REST APIs are a popular way for systems to <strong>communicate with each other over the we</strong>b, and they offer many benefits such as being <strong>easy to use </strong>and <strong>maintain</strong>. However, it&apos;s important to follow best practices when designing and building a REST API to ensure it is reliable, scalable, and easy to use for clients.</p><p>Unfortunately, not all developers follow best practices when building an API. This can lead to issues such as confusing or inconsistent URL conventions, which can make the API more difficult to use and understand. In this blog post, we&apos;ll cover the most important <strong>best practices</strong> for designing and building a REST API from a developer&apos;s perspective. Here I &#xA0;introduced a set of rules to remember well. As well I designed a huge mind map to store the rules in your brain. By following these best practices, you can build an API that is easy to use and <strong>understand, and avoid common pitfalls </strong>that can lead to frustration for API users.</p><p>&quot;<a href="https://www.oreilly.com/library/view/rest-api-design/9781449317904/">REST API Design Rulebook</a>&quot; is a book by <strong>Mark Masse</strong> that provides guidelines for designing REST APIs. Here I used it as a reference to define my rule set and the best practices.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.oreilly.com/library/view/rest-api-design/9781449317904/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">REST API Design Rulebook</div><div class="kg-bookmark-description">In today&#xE2;??s market, where rival web services compete for attention, a well-designed REST API is a must-have feature. This concise book presents a set of API design rules, drawn primarily &#x2026; - Selection from REST API Design Rulebook [Book]</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.oreilly.com/library/view/static/images/apple-touch-icon.png" alt="REST API Best Practices with a Mind Map"><span class="kg-bookmark-author">O&#x2019;Reilly Online Learning</span><span class="kg-bookmark-publisher">Mark Masse</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://learning.oreilly.com/library/cover/9781449317904/360h/" alt="REST API Best Practices with a Mind Map"></div></a></figure><h2 id="rest-api-mindmap-sharable-image">REST API Mindmap sharable image</h2><figure class="kg-card kg-image-card kg-width-full"><img src="https://csandunblogs.com/content/images/2022/12/REST-Api--Best-Practices.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="2000" height="2321" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/REST-Api--Best-Practices.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/REST-Api--Best-Practices.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/REST-Api--Best-Practices.png 1600w, https://csandunblogs.com/content/images/size/w2400/2022/12/REST-Api--Best-Practices.png 2400w"></figure><h2 id="1-what-is-rest-api">1. What is REST API</h2><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://csandunblogs.com/content/images/2022/12/1.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="1632" height="1642" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/1.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/1.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/1.png 1600w, https://csandunblogs.com/content/images/2022/12/1.png 1632w" sizes="(min-width: 720px) 720px"><figcaption>What is REST API</figcaption></figure><p>Here we are discussing, &quot;<strong>What is REST</strong>?&quot;, main <strong>constraints</strong>, and <strong>benefits</strong>. &#xA0;Furthermore here shows how to communicate with clients and servers through HTTP. I am hoping to deep dive into this soon in another blog post.</p><h2 id="2-uri-definition">2. URI Definition</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/3.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="2000" height="1192" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/3.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/3.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/3.png 1600w, https://csandunblogs.com/content/images/size/w2400/2022/12/3.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>A <strong>URI (Uniform Resource Identifier)</strong> is a string of characters that identifies a resource on the web. In the context of a REST API, it is common to use URLs to identify resources, as they specify both the name and location of the resource.</p><p>In this section, I put some best practices for using URI. We can discuss this in a more informative way in the near future.</p><h2 id="3-uri-authority-design">3. URI &#xA0;Authority Design</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/2-1.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="2000" height="1823" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/2-1.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/2-1.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/2-1.png 1600w, https://csandunblogs.com/content/images/size/w2400/2022/12/2-1.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>In a URI, the authority is the part of the URI that specifies the location of the resource. According to the PDF, there are 4 archetypes for modeling resources in URI. We will discuss this topic in the future more descriptively. Keep in touch with my blog.</p><h2 id="4-uri-path-design">4. URI Path Design </h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/4.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="2000" height="1927" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/4.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/4.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/4.png 1600w, https://csandunblogs.com/content/images/size/w2400/2022/12/4.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>The path portion of a URI is the part of the URI that follows the authority and specifies the name and location of the resource being accessed. It is important to follow best practices when designing the path of a URI to ensure it is easy to use and understand.<br>This is the most critical section for a backend developer who designs well REST API. I plan to write a blog post on this section soon.</p><h2 id="5-uri-query-design">5. URI Query Design</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/5.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="2000" height="803" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/5.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/5.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/5.png 1600w, https://csandunblogs.com/content/images/size/w2400/2022/12/5.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>The query portion of a URI is the part of the URI that follows the path and specifies additional information about the resource being accessed. The query is typically made up of one or more key-value pairs separated by an ampersand (&amp;).</p><p>Here are some best practices for designing the query portion of a URI. I put them much as, possible into this section. Go through the mind map and follow these practices in your code base.</p><h2 id="6-http-methods">6. HTTP Methods</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/6.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="1602" height="1824" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/6.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/6.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/6.png 1600w, https://csandunblogs.com/content/images/2022/12/6.png 1602w" sizes="(min-width: 720px) 720px"></figure><p>In the context of a REST API, HTTP methods (also known as &quot;verbs&quot;) are used to specify the desired action to be performed on a resource. This section is the most important one for the developer&apos;s life. Keep in touch with descriptive blog posts on this in the future.</p><h2 id="7-response-codes">7. Response Codes</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/7.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="1508" height="1380" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/7.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/7.png 1000w, https://csandunblogs.com/content/images/2022/12/7.png 1508w" sizes="(min-width: 720px) 720px"></figure><p>In a REST API, HTTP response codes are used to indicate the status of a request. They provide information about whether the request was successful or encountered an error and provide additional information about the nature of the error. </p><p>Here I put most high-level error patterns and usage. We can discuss the most important response codes and other codes in the next couple of blogs.</p><h2 id="8-versioning">8. Versioning</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/8.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="2000" height="641" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/8.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/8.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/8.png 1600w, https://csandunblogs.com/content/images/size/w2400/2022/12/8.png 2400w" sizes="(min-width: 720px) 720px"></figure><h2 id="9-client-concerns">9. Client Concerns</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/9.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="1730" height="1408" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/9.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/9.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/9.png 1600w, https://csandunblogs.com/content/images/2022/12/9.png 1730w" sizes="(min-width: 720px) 720px"></figure><h2 id="10-documentation">10. Documentation</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/10.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="1476" height="848" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/10.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/10.png 1000w, https://csandunblogs.com/content/images/2022/12/10.png 1476w" sizes="(min-width: 720px) 720px"></figure><p>Documentation is an important part of any REST API. It provides information about the API&apos;s functionality, resources, and available operations, as well as any requirements or restrictions. We will discuss more tools and techniques near future.</p><h2 id="11-hateos">11. HATEOS</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/11.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="820" height="496" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/11.png 600w, https://csandunblogs.com/content/images/2022/12/11.png 820w" sizes="(min-width: 720px) 720px"></figure><hr><h2 id="12-resources">12. Resources</h2><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/99.png" class="kg-image" alt="REST API Best Practices with a Mind Map" loading="lazy" width="948" height="942" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/99.png 600w, https://csandunblogs.com/content/images/2022/12/99.png 948w" sizes="(min-width: 720px) 720px"></figure><p>&quot;<a href="https://www.oreilly.com/library/view/rest-api-design/9781449317904/">REST API Design Rulebook</a>&quot; is a book by Mark Masse that provides guidelines for designing REST APIs. Here I used it as the main reference to improve my best practices on REST API.</p><p></p><p>I hope this information has been helpful! Let me know if you have any further questions. I will plan to discuss the above topics from a REST API blog series. Keep in touch on my blog site. Happy Coding!!</p><hr><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F44B;</div><div class="kg-callout-text">I hope you find this content helpful. Keep touching my diaries.<br>Learn something new. Comment your thoughts and share the content.<br>Happy coding!!<br><em>See you again soon. &#x270C;&#x270C;</em></div></div>]]></content:encoded></item><item><title><![CDATA[Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1]]></title><description><![CDATA[The benchmarking technique aids in calculating the performance metrics of a single or multiple sections of code in your application. Benchmark can assist you in identifying the parts of your source code that require optimization.]]></description><link>https://csandunblogs.com/optimizing-dotnet-source-code-using-benchmarking-technique-using-benchmarkdotnet-part-1/</link><guid isPermaLink="false">637733fbb927b804a5d95f9d</guid><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[CSharp]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Mon, 26 Dec 2022 19:13:15 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2022/12/Benchmark1.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2022/12/Benchmark1.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"><p><strong>The benchmarking technique</strong> aids in<strong> calculating the performance metrics</strong> of a single or multiple sections of code in your application. Benchmark can assist you in identifying the parts of your source code that require optimization.</p><h2 id="whats-a-benchmark">What&apos;s a Benchmark?</h2><p>A <strong>benchmark </strong>is a basic test that delivers a set of quantifiable statistics that can assist you in determining whether or not a modification to your code has increased, decreased, or had no influence on the overall performance. It is essential to have an understanding of the performance metrics that are associated with the methods that make up your application to make use of them during the process of code optimization.</p><h2 id="benefits-of-benchmarking-a-source-code">Benefits of Benchmarking a source code</h2><ul><li><strong>Benchmarking </strong>is the process of comparing the performance of code snippets, usually against a predefined baseline.</li><li><strong>Benchmarking </strong>can assist in <strong>identifying performance bottlenecks in an application</strong>. (By identifying bottlenecks, you can determine the changes needed in your source code to improve the application&apos;s performance and scalability.)</li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/dotnet/BenchmarkDotNet"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - dotnet/BenchmarkDotNet: Powerful .NET library for benchmarking</div><div class="kg-bookmark-description">Powerful .NET library for benchmarking. Contribute to dotnet/BenchmarkDotNet development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">dotnet</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://repository-images.githubusercontent.com/12191244/e327c900-f194-11e9-8d50-db9acd1690af" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"></div></a></figure><blockquote><strong><a href="https://github.com/dotnet/BenchmarkDotNet">BenchmarkDotNet</a></strong> helps you to transform methods into benchmarks, track their performance, and share reproducible measurement experiments.</blockquote><p><strong>This is </strong>an<strong> open-source library </strong><em>that can convert your.NET methods into benchmarks, monitor those methods, and gain insights into the performance data collected</em>. It is compatible with both.<strong>NET Framework and.NET Core applications</strong>. <strong>BenchmarkDotNet </strong>can quickly convert your methods into benchmarks, run those benchmarks, and retrieve the benchmarking results. An operation in BenchmarkDotNet terminology involves executing a method decorated with the Benchmark attribute.</p><h2 id="steps-for-benchmarking-code-using-benchmakdotnet">Steps for benchmarking code using BenchmakDotNet</h2><p>To run <strong>BenchmarkDotNet </strong>in your .NET Framework or .NET Core application, you must follow these steps:</p><ol><li><strong>Add the necessary NuGet package</strong></li><li><strong>Add Benchmark attributes to your methods</strong></li><li><strong>Create a BenchmarkRunner instance</strong></li><li><strong>Run the application in Release mode</strong></li></ol><h2 id="practical">Practical</h2><p>Now we can see how to config <strong>BenchmarkDotNet library </strong>in your asp.net core project and try to retrieve some measurements on the selected Scenario.</p><h3 id="considering-scenariostring-builder-vs-string-performance">Considering Scenario - string builder vs. string performance.</h3><p>To learn the <strong>BenchmarkDotNet </strong>library with the asp.net core project, a simple development scenario is utilized here.</p><div class="kg-card kg-callout-card kg-callout-card-purple"><div class="kg-callout-emoji">&#x1F4AD;</div><div class="kg-callout-text"><strong><em>We will compare the string builder and string in terms of performance. Here, we look at how long it takes and how much memory it takes to append 100 characters into a single string.</em></strong></div></div><p>First, let&apos;s create a console application and install the<strong> BenchmarkDotNet NuGet</strong> package.</p><h3 id="create-dotnet-6-console-project-and-add-benchmarkdotnet-library">Create Dotnet 6 Console project and add BenchmarkDotNet library</h3><p>Let&#x2019;s open <a href="https://visualstudio.microsoft.com/vs/" rel="noreferrer noopener">Visual Studio 2022</a> and create a <a href="https://dotnet.microsoft.com/en-us/download/dotnet/6.0" rel="noreferrer noopener">.NET </a>6 based console application. I named it <em>&quot;StringBuilderVsStringBenchmarkDotnet&quot;.</em></p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/11/image-23.png" class="kg-image" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1" loading="lazy" width="1187" height="203" srcset="https://csandunblogs.com/content/images/size/w600/2022/11/image-23.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/11/image-23.png 1000w, https://csandunblogs.com/content/images/2022/11/image-23.png 1187w" sizes="(min-width: 720px) 720px"></figure><p>This is the time to install the <a href="https://www.nuget.org/packages/BenchmarkDotNet">BenchmarkDotNet </a>NuGet package into my console application. You can use the command given below to add the package to the console app. This command should be executed from the project directory path.</p><!--kg-card-begin: markdown--><p><code>dotnet add package BenchmarkDotNet</code></p>
<!--kg-card-end: markdown--><p>You can also add NuGet references using Manage NuGet Packages. It will open the dialog as shown below. Search for <code><a href="https://www.nuget.org/packages/BenchmarkDotNet" rel="noreferrer noopener">BenchmarkDotNet</a> </code>and install the package.<br><strong>Note: </strong>Here, I am using <strong><a href="https://www.jetbrains.com/rider/">Rider</a> </strong>as my main IDE.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/11/image-24.png" class="kg-image" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1" loading="lazy" width="1337" height="275" srcset="https://csandunblogs.com/content/images/size/w600/2022/11/image-24.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/11/image-24.png 1000w, https://csandunblogs.com/content/images/2022/11/image-24.png 1337w" sizes="(min-width: 720px) 720px"></figure><h2 id="benchmark-code">Benchmark Code</h2><p>This is the complete code for the run <strong>benchmark </strong>methods. Here we implemented two scenarios of methods.</p><div class="kg-card kg-callout-card kg-callout-card-green"><div class="kg-callout-emoji">&#x1F514;</div><div class="kg-callout-text"><em>These couple of methods we want to benchmark. For that, we simply add <strong>[Benchmark] </strong>annotation on top of the method. It is a sign for considering to BenchmarkRunner class.</em><br><br><em>Also,&#xA0;<strong>[MemoryDiagnoser()]</strong>annotation helps to identify the memory heap of a method.</em></div></div><!--kg-card-begin: html--><script src="https://gist.github.com/csandun/cf043751889d50403f77b1679b49ac7b.js"></script><!--kg-card-end: html--><h2 id="running-benchmark-project">Running benchmark project</h2><p>Running the benchmarking application in <strong>release configuration </strong>is a requirement for benchmarking. When building the project, you should ideally have the <strong>optimize option set to true</strong> in <strong>csproj</strong> or the CSC command line.</p><p>Additionally, the process<strong> <u>shouldn&apos;t have a debugger attached</u></strong> to it. This implies that we have two choices whenever we want to run the benchmarking application.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/11/image-25.png" class="kg-image" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1" loading="lazy" width="640" height="88" srcset="https://csandunblogs.com/content/images/size/w600/2022/11/image-25.png 600w, https://csandunblogs.com/content/images/2022/11/image-25.png 640w"></figure><ul><li>Run the application from <strong>Visual Studio/Rider</strong> using <strong>Debug -&gt; Start Without Debugging</strong> (keyboard shortcut<strong> CTRL + F5 </strong>). The configuration should be set to release.</li></ul><!--kg-card-begin: markdown--><ul>
<li>OR the other option is to run the application using .<strong>Net CLI</strong>. While using .Net run command, we should ensure that we add <code>-c release</code> switch to the command.</li>
</ul>
<!--kg-card-end: markdown--><!--kg-card-begin: markdown--><p><code>dotnet run -p StringBuilderVsStringBenchmarkDotnet.csproj -c Release</code></p>
<!--kg-card-end: markdown--><p>Running this straightforward app might take a few seconds. This is due to BenchmarkDotNet&apos;s <u>repeated launch of the benchmark process</u>.</p><h2 id="result-of-the-test">Result of the test</h2><p>We can then look at the outcomes below. Here is the summary I received on my computer for your reference.</p><figure class="kg-card kg-image-card"><img src="https://csandunblogs.com/content/images/2022/12/image.png" class="kg-image" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1" loading="lazy" width="639" height="292" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/image.png 600w, https://csandunblogs.com/content/images/2022/12/image.png 639w"></figure><div class="kg-card kg-callout-card kg-callout-card-red"><div class="kg-callout-emoji">&#x26A0;&#xFE0F;</div><div class="kg-callout-text"><strong>NOTE : </strong>Be aware that in order to perform a benchmark, we must ensure that all programs other than the benchmark process and the default <strong>OS processes are turned off.</strong> Running a benchmark while working in Visual Studio simultaneously can have a negative impact on the benchmark results.</div></div><!--kg-card-begin: markdown--><p>Considering the result set, we should consider two parameters:</p>
<ol>
<li>Mean parameter</li>
<li>Allocated parameter</li>
</ol>
<!--kg-card-end: markdown--><p>The <strong>mean </strong>parameter describes<strong> the average time it takes the method to run.</strong><br>An <strong>allocated </strong>parameter describes <strong>the average allocation of the heap in memory </strong>while the method is running.</p><h2 id="conclusion">Conclusion</h2><p>As we know, in programming technics, &#xA0;We get the expected result from the application.</p><div class="kg-card kg-callout-card kg-callout-card-yellow"><div class="kg-callout-emoji">&#x2139;&#xFE0F;</div><div class="kg-callout-text"><b>StringBuilder shows much-improved performance than the string concatenation. Average execution time and heap are also pretty low than the string concatenation.</b></div></div><p>This article does not cover all of the available features and customization options. However, it should help you get started with this package. If you want to learn more, check out <a href="https://benchmarkdotnet.org/articles/overview.html">their documentation.</a></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://benchmarkdotnet.org/articles/overview.html"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Overview | BenchmarkDotNet</div><div class="kg-bookmark-description"></div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://benchmarkdotnet.org/logo/icon-32.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"><span class="kg-bookmark-author">BenchmarkDotNet</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://benchmarkdotnet.org/images/v0.12.0/rplot.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"></div></a></figure><h2 id="sample-repository">Sample repository</h2><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/csandun/StringBuilderVsStringBenchmarkDotnet/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - csandun/StringBuilderVsStringBenchmarkDotnet: StringBuilder Vs String BenchmarkDotnet</div><div class="kg-bookmark-description">StringBuilder Vs String BenchmarkDotnet. Contribute to csandun/StringBuilderVsStringBenchmarkDotnet development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">csandun</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/a55e98868bef793817f477c5a726155eb1f88bcce647e1cbddb39e3daf7ba006/csandun/StringBuilderVsStringBenchmarkDotnet" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"></div></a></figure><hr><h2 id="resources">Resources</h2><ol><li>Intro to Benchmark.net - How To Benchmark C# Code</li></ol><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.youtube.com/watch?v=mmza9x3QxYE"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Intro to Benchmark.net - How To Benchmark C# Code</div><div class="kg-bookmark-description">How efficient is your code? Is the change you just made going to improve your application or not? How do you know? How important was that change? These are q...</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.youtube.com/s/desktop/451d4225/img/favicon_144x144.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"><span class="kg-bookmark-author">YouTube</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://i.ytimg.com/vi/mmza9x3QxYE/maxresdefault.jpg?sqp=-oaymwEmCIAKENAF8quKqQMa8AEB-AH-DoACuAiKAgwIABABGEsgVyhlMA8=&amp;rs=AOn4CLDGYdrQdq-ttLBS1y3QopYnJ-SXpQ" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"></div></a></figure><p>2. Documentation</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://benchmarkdotnet.org/articles/overview.html"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Overview | BenchmarkDotNet</div><div class="kg-bookmark-description"></div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://benchmarkdotnet.org/logo/icon-32.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"><span class="kg-bookmark-author">BenchmarkDotNet</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://benchmarkdotnet.org/images/v0.12.0/rplot.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"></div></a></figure><p>3. GitHub Repo</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/dotnet/BenchmarkDotNet"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - dotnet/BenchmarkDotNet: Powerful .NET library for benchmarking</div><div class="kg-bookmark-description">Powerful .NET library for benchmarking. Contribute to dotnet/BenchmarkDotNet development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">dotnet</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://repository-images.githubusercontent.com/12191244/e327c900-f194-11e9-8d50-db9acd1690af" alt="Optimizing DotNet source code using benchmarking technique using BenchmarkDotNet - Part 1"></div></a></figure><p></p><div class="kg-card kg-callout-card kg-callout-card-green"><div class="kg-callout-emoji">&#x1F44B;</div><div class="kg-callout-text">I hope you find this content helpful. Keep touching my diaries.<br>Learn something new. Comment your thoughts and share the content.<br>Happy coding!!<br><em>See you again soon. &#x270C;&#x270C;</em></div></div>]]></content:encoded></item><item><title><![CDATA[CSandun's .Net Backend Developer roadmap for 2023]]></title><description><![CDATA[It's the end of 2022, and coming to a new year in your career. Many developers stay in their comfort zone with CRUD operations and basic development technologies. It is time to move with new Dotnet technologies and current industry trends and challenges in 2023.]]></description><link>https://csandunblogs.com/csadnun-dotnet-road-map/</link><guid isPermaLink="false">63a4cc412be67904bb426d5d</guid><category><![CDATA[Asp.Net Core]]></category><category><![CDATA[MindMaps]]></category><category><![CDATA[CSharp]]></category><category><![CDATA[csandun]]></category><dc:creator><![CDATA[Chathuranga]]></dc:creator><pubDate>Sat, 24 Dec 2022 18:05:56 GMT</pubDate><media:content url="https://csandunblogs.com/content/images/2022/12/Roadmap.png" medium="image"/><content:encoded><![CDATA[<img src="https://csandunblogs.com/content/images/2022/12/Roadmap.png" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"><p>It&apos;s the end of 2022, and coming to a new year in your career. Many developers stay in their comfort zone with CRUD operations and basic development technologies. <strong>It is time to move with new Dotnet technologies and current industry trends and challenges in 2023</strong>.</p><h2 id="comfort-zone-of-a-developer">Comfort Zone of a developer</h2><p>As a developer, our <strong>comfort zone</strong> refers to the set of technologies, tools, and practices that a developer is familiar with and comfortable using. It&apos;s natural for us to feel more comfortable and confident when working within our comfort zone, as we are already familiar with the technologies and have had the opportunity to develop our skills in those areas.<br><br>However, we must also be willing to step <strong>outside of our comfort zone </strong>and <strong>learn new technologies and approaches</strong>. This can help us stay with <strong>current industry trends and expand our skillset</strong>, leading to more significant growth.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://csandunblogs.com/content/images/2022/12/comfort_zone.webp" class="kg-image" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023" loading="lazy" width="640" height="640" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/comfort_zone.webp 600w, https://csandunblogs.com/content/images/2022/12/comfort_zone.webp 640w"><figcaption>developer comfort zone to growth zone</figcaption></figure><p><strong>To step outside our comfort zone</strong>, we can <strong>learn new technologies, &#xA0;tools, practices, and patterns and collaborate with colleagues with different skill set</strong>s. It is also helpful to <strong>seek opportunities </strong>to work on projects that require new technologies or approaches, as <strong>this can provide a structured and supported way to learn and grow</strong>.</p><h2 id="step-outside-our-comfort-zone-with-a-roadmap">Step outside our comfort zone with a Roadmap</h2><p>For the above, we can learn new things in the coming year, set out of our comfort zone, and gain new challenges. As a Dotnet developer, I created a <strong>roadmap</strong> that is helping <strong>my thoughts and my opinions</strong>. I am doing REST Api-based developments using dot net core. And also I followed cloud technologies and microservices patterns in my carrier. <strong><em>My ideas entirely propose this roadmap; anyone can agree or disagree with me.</em></strong> <em><strong>Also open to suggestions for this. </strong></em><br><br><a href="https://twitter.com/nickchapsas?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">NickChapsas(@nickchapsas)</a> &#xA0;inspire me to create a roadmap for this year. Based on <a href="https://github.com/Elfocrash/.NET-Backend-Developer-Roadmap">his roadmap,</a> I update my roadmap and I put my opinions into it. </p><div class="kg-card kg-callout-card kg-callout-card-yellow"><div class="kg-callout-emoji">&#x1F4A1;</div><div class="kg-callout-text"><strong><em>I plan to share these technologies in the upcoming year, 2023, via my blogs. Keep in touch with <a href="https://csandunblogs.com/">csandunblogs.com</a> and <a href="https://www.linkedin.com/in/csandun/">my LinkedIn</a>.</em></strong></div></div><h2 id="roadmap">Roadmap</h2><p>Coming to the <a href="https://xmind.app/m/zbjpp3/"><strong>roadmap</strong></a>, here is my proposed mind map for Dotnet developers can follow next year.</p><p>Here <strong>red</strong> means <strong>a must know,</strong> <strong>yellow</strong> means <strong>a good to know</strong>, and a <strong>grey</strong> means<strong> maybe</strong>, and I will explain why it is a perhaps as I goand keep in mind that this is very I <strong>opinionated</strong>. This is my take it doesn&apos;t mean that everyone will agree with this. It&apos;s okay; we can disagree, but this is how I would work this, how I would hire and there is room for that.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://xmind.app/m/zbjpp3/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">CSandun&#x2019;s .NET Backend Developer Roadmap in 2023 (1)</div><div class="kg-bookmark-description">Xmind is the most professional and popular mind mapping tool. Millions of people use Xmind to clarify thinking, manage complex information, brainstorming, get work organized, remote and work from home WFH.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://xmind.app/webapp-icon/icon_1024.png" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"><span class="kg-bookmark-author">Mind Mapping App</span><span class="kg-bookmark-publisher">Xmind Ltd.</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://s3.amazonaws.com/xmindshare/previews/zbjpp3-qyl1R3f-35326.png" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"></div></a></figure><h2 id="shareable-roadmap-image">Shareable Roadmap Image</h2><figure class="kg-card kg-image-card kg-width-full kg-card-hascaption"><img src="https://csandunblogs.com/content/images/2022/12/roadmap-image.png" class="kg-image" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023" loading="lazy" width="2000" height="4542" srcset="https://csandunblogs.com/content/images/size/w600/2022/12/roadmap-image.png 600w, https://csandunblogs.com/content/images/size/w1000/2022/12/roadmap-image.png 1000w, https://csandunblogs.com/content/images/size/w1600/2022/12/roadmap-image.png 1600w, https://csandunblogs.com/content/images/size/w2400/2022/12/roadmap-image.png 2400w"><figcaption>CSandun&apos;s .Net Backend Developer Roadmap 2023</figcaption></figure><h2 id="how-to-give-you-contribute-to-improving-the-roadmap">How to give you contribute to improving the roadmap</h2><p>Please share your <strong>thoughts and changes</strong> for this. I can update this with your suggestions. </p><div class="kg-card kg-callout-card kg-callout-card-pink"><div class="kg-callout-emoji">&#x1F30E;</div><div class="kg-callout-text"><strong><em>Please report your ideas and suggestions in the GitHub issues section or Linkedin post comment section.</em></strong></div></div><h3 id="github-repository">GitHub repository</h3><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/csandun/dotnet-roadmap-2023"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - csandun/dotnet-roadmap-2023</div><div class="kg-bookmark-description">Contribute to csandun/dotnet-roadmap-2023 development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">csandun</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/a2531f63c2b819284cd77b4ef55dd06fb6932c99bb09539109c8f7fd370947f6/csandun/dotnet-roadmap-2023" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"></div></a></figure><h2 id="thoughts">Thoughts</h2><blockquote>Cheers, It is time to move with new Dotnet technologies and current industry trends and challenges in 2023. Let&apos;s do it in 2023.</blockquote><h2 id="my-inspiration-repositories-and-roadmaps">My inspiration repositories and roadmaps.</h2><ol><li><strong>My .NET backend developer roadmap for 2022</strong></li></ol><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.youtube.com/watch?v=gw-6lKrKlp0"><div class="kg-bookmark-content"><div class="kg-bookmark-title">My .NET backend developer roadmap for 2022</div><div class="kg-bookmark-description">Check out my courses: https://nickchapsas.comBecome a Patreon and get source code access: https://www.patreon.com/nickchapsasHello everybody I&#x2019;m Nick and in ...</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.youtube.com/s/desktop/451d4225/img/favicon_144x144.png" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"><span class="kg-bookmark-author">YouTube</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://i.ytimg.com/vi/gw-6lKrKlp0/maxresdefault.jpg" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"></div></a></figure><p>2<strong>. Nick&apos;s .NET Backend Developer Roadmap for 2022</strong></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/Elfocrash/.NET-Backend-Developer-Roadmap"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - Elfocrash/.NET-Backend-Developer-Roadmap: Nick&#x2019;s Roadmap for a .NET Backend Developer working with Microservices</div><div class="kg-bookmark-description">Nick&amp;#39;s Roadmap for a .NET Backend Developer working with Microservices - GitHub - Elfocrash/.NET-Backend-Developer-Roadmap: Nick&amp;#39;s Roadmap for a .NET Backend Developer working with Microser...</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">Elfocrash</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/0755748e2f9c334a2d5b13a279650367d4eeb098ae5406c07e805bac7790c5d6/Elfocrash/.NET-Backend-Developer-Roadmap" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"></div></a></figure><p>3. ASP.NET Core Developer Roadmap</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/MoienTajik/AspNetCore-Developer-Roadmap"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - MoienTajik/AspNetCore-Developer-Roadmap: Roadmap to becoming an ASP.NET Core developer in 2022</div><div class="kg-bookmark-description">Roadmap to becoming an ASP.NET Core developer in 2022 - GitHub - MoienTajik/AspNetCore-Developer-Roadmap: Roadmap to becoming an ASP.NET Core developer in 2022</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.com/fluidicon.png" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">MoienTajik</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://repository-images.githubusercontent.com/169371413/4f1ed800-9df2-11eb-94f8-ba0166f1aa0d" alt="CSandun&apos;s .Net Backend Developer roadmap for 2023"></div></a></figure><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">&#x1F44B;</div><div class="kg-callout-text">I hope you find this content helpful. Keep touching my diaries.<br>Learn something new. Comment your thoughts and share the content.<br>Happy coding!!<br><em>See you again soon. &#x270C;&#x270C;</em></div></div>]]></content:encoded></item></channel></rss>