<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eugene Krapivin on Medium]]></title>
        <description><![CDATA[Stories by Eugene Krapivin on Medium]]></description>
        <link>https://medium.com/@nocgod?source=rss-5c3971e71656------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8EDX6QcWsYzlzQML</url>
            <title>Stories by Eugene Krapivin on Medium</title>
            <link>https://medium.com/@nocgod?source=rss-5c3971e71656------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:35:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nocgod/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Linkedin AI SlopTechTips]]></title>
            <link>https://medium.com/@nocgod/linkedin-ai-sloptechtips-42845698ba0c?source=rss-5c3971e71656------2</link>
            <guid isPermaLink="false">https://medium.com/p/42845698ba0c</guid>
            <category><![CDATA[ai-slop]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[code-critical-thinking]]></category>
            <dc:creator><![CDATA[Eugene Krapivin]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 14:58:32 GMT</pubDate>
            <atom:updated>2026-09-06T14:58:32.625Z</atom:updated>
            <content:encoded><![CDATA[<p>While kicking back on a chair, sipping some beer, I’ve browsed LinkedIn. Really, not sure why, its just a dumpster fire of AI Slop generated tech tips these days. Most days I just scroll-by giggling a bit, but today I decided to actually add my thoughts, so I slipped a comment into the endless stream of “Wow this is insightful”, “Really innovative” and “Revealing” comments.</p><p>Let me share the gist of the posts, without revealing identifying information to keep the privacy of the authors.</p><h3>The Dependency Injection enshitification</h3><p>The first one seems really cool (then you think about it):</p><p>“SomeLib in <a href="https://www.linkedin.com/safety/go/?url=http%3A%2F%2FASP%2ENET&amp;urlhash=plA_&amp;mt=gHDvsNpPVvfTVLM-gMvNFCpXOb8Hr9GKlOpKL-uCOCPHAMae13r2oRDPyOH5RarF2el3Is9fD5Of5bRbXJ4Rb00lR-0cHj00SRHZpla3xxgAPogh_do44dvDPQ&amp;isSdui=true">ASP.NET</a> Core — Simplify Dependency Injection<br>As a .NET application grows, manually registering every service can make startup configuration repetitive and harder to maintain.<br>With SomeLib, you can use assembly scanning to automatically register services based on conventions.”</p><p>I cut it a bit for brevity (but you got the gist of it), this followed by an AI generated example image:</p><pre>builder.Services.AddScoped&lt;IOrderService, OrderService&gt;();<br>builder.Services.AddScoped&lt;ICustomerService, CustomerService&gt;();<br>builder.Services.AddScoped&lt;IInvoiceService, InvoiceService&gt;();<br>// .. and many more</pre><blockquote>With a red warning: hard to maintain, easy to forget, and doesn’t scale.</blockquote><p>And as a good example:</p><pre>builder.Services.Scan(scan =&gt; scan<br> .FromAssemblyOf&lt;OrderService&gt;()<br> .AddClasses()<br> .AsMatchingInterface()<br> .WithScopedLifetime());</pre><blockquote>With a green box stating: clean, maintainable, and future-proof.</blockquote><p>So lets talk about that =)</p><h4>Been there done that</h4><pre>// Convention based registration in Castle Windsor<br>container.Register(Classes.FromThisAssembly()<br>    .InSameNamespaceAs&lt;RootComponent&gt;()<br>    .WithService.DefaultInterfaces()<br>    .LifestyleTransient());<br>// Convetion based registration in Ninject<br>kernel.Bind(x =&gt; x<br>    .FromThisAssembly()<br>    .SelectAllClasses()<br>    .BindDefaultInterface());</pre><p>I’ve met with this pattern years ago at the first company I worked at (with <a href="https://github.com/castleproject/windsor">castle windsor</a>), and unfortunately this pattern is currently deeply rooted inside the current company’s infrastructure (with <a href="https://github.com/ninject/Ninject">ninject</a>).</p><p>At my first gig we had this pattern of carpet bombing registrations into the DI container. It feels really powerful when you are a lowly junior developer seeing such tools at work.</p><p>With time however, you start to notice you are more and more having to rebind stuff, some should have been a singleton, others transient, some should have never been in the DI container at all. I want to see you try debugging a DI container registration with only asp.net and generic hosting crap in it, now carpet bomb your whole assembly and voila, grab a shovel and start shoveling.</p><p>In addition to the garbage lets talk about, <strong>the startup times</strong>, why pay the price of startup for registering crap you never needed? Slow startup times translate to slow reaction in scaling up or rolling back, 2 out of the 3 operations when startup occurs (the thirds being deployment obviously).</p><p>Lets also talk about the meaning: the developer adding functionality does not think about component life-cycle at all, they just blindly follow some convention. You really should be stopping for a second and asking the question: How long should it live? when should it be disposed? could it be shared? is this stateless? could it be a singleton? should we really have a fresh copy on each time the dependency is injected or should it be scoped to some scope (like a request)?<br>If we stop asking these questions, we are bound to find ourselves at 3AM debugging why the hell are we chugging GC or worse than that, my customer A is seeing data from customer B.</p><p>What if my dependency requires a bit more juggling when registering? Maybe it has a configuration and some sub-registrations based on some parameters, for example a strategy based on a config.</p><h4>So what should be do?</h4><p>Well generally, if its a simple ISomeService to SomeService just go and put it in the composition root.</p><p>If it requires a bit more work, just make sure the assembly with ISomeService has an extension method for AddSomeService(config); and AddSomeService(config =&gt; {...}); and if it doesn’t, extension methods in C# are really really strong and simple.</p><p>It is readable, maintainable, you can go into the implementation to understand what is happening in the code (good luck doing it with dynamic scanning).</p><p>The reader understands without guessing <strong>WHAT </strong>is registered, a quick search on the interface reveals <strong>WHY </strong>its registered.</p><h4>Plugins</h4><p>It’s not that scanning for DI registrations is inherently bad. You might want to scan a folder in order to load plugins, and this pattern is perfectly acceptable. But in this case, you define a strict contract between <strong>what</strong> and <strong>where</strong> you are scanning, <strong>what</strong> you are registering, and <strong>how</strong> you are registering it.</p><p>I’d still be cautious about passing my IServiceCollection into an unknown plugin. You don&#39;t know <strong>WHAT</strong> it might pull from the service collection. In such a case, I&#39;d still probably follow a safer path:</p><ol><li>Scan a specific plugin folder.</li><li>Assembly.Load(...) the DLLs.</li><li>Find all implementations of ICoolPlugin.</li><li>Validate the contract of the implementation — for example, require a parameterless constructor.</li><li>Register the plugin with a transient lifetime using a factory method that explicitly calls new, ensuring the plugin has no access to IServiceCollection or IServiceProvider.</li></ol><p>I’m pretty sure this can be circumvented if you’re dealing with genuinely untrusted code, because once you’ve loaded the assembly into your process, you’ve already given it a lot of power. But for enforcing a clean architectural boundary between a plugin and the host’s dependency graph, I’d still prefer this approach over handing the plugin the entire DI container.</p><p>The important distinction is that <strong>scanning is being used here to discover components that implement a well-defined contract, not to blindly construct and register arbitrary classes into the application’s dependency graph.</strong></p><p>.NET no longer supports Code Access Security (CAS), and the old AppDomain-based sandboxing model is <strong>obsolete </strong>and <strong>unsupported</strong>. So if these are genuinely untrusted plugins, trying to sandbox them inside the host process is probably the wrong architecture anyway.</p><p>A better approach would be to run plugins in a separate process and communicate with them through an explicit IPC contract — gRPC, HTTP, named pipes, or whatever fits the requirements.</p><p>That gives you an actual process boundary instead of pretending that hiding IServiceProvider from the plugin is a security boundary.</p><h3>Boss said its slow, what should I fix?</h3><p>The next jewel came in the form of a question:</p><blockquote>The code mentioned runs on a list of 500,000 users, once per request. It’s noticeably slow. How would you optimize this code?</blockquote><blockquote>a) Replace the foreach with a for loop for faster iteration.<br>b) Set the list’s capacity in advance using List&lt;string&gt; to avoid repeated resizing.<br>c) Use AsParallel() to process users across multiple cores.<br>d) Use string.ToUpperInvariant() instead of .ToUpper() for culture-independent behavior and better performance.</blockquote><pre>class User<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public bool IsActive { get; set; }<br>}<br><br>class Program<br>{<br>    public List&lt;string&gt; GetActiveUserNames(List&lt;User&gt; users)<br>    {<br>        var result = new List&lt;string&gt;();<br><br>        foreach (var user in users)<br>        {<br>            if (user.IsActive)<br>            {<br>                result.Add(user.Name.ToUpper());<br>            }<br>        }<br><br>        return result;<br>    }<br>}</pre><p>How I see it? Some junior engineer got called by his boss: “hey, this is slow! make fast!”. The engineer is sitting at his desk, unsure what&#39;s wrong, asks some AI LLM thingy, and it suggests some micro optimizations, totally ignoring the problem.</p><h4>XY Problem</h4><p>An XY problem is when you have problem Y, you think X will solve it, so you are asking about X, instead of asking about Y.</p><p>Follow the link to <a href="https://xyproblem.info/">https://xyproblem.info/</a> to get more insight.</p><h4>Why none of the solutions actually matter</h4><p>Lets start with “(a) Replace the foreach with a for loop for faster iteration”</p><p>Sure, it might shave off a few nano-seconds, but really, if you look at benchmarks, in this specific case it won’t matter much. The for loop shaves off a few abstractions along the way, but not as much to make a real impact on the overall performance.</p><p>“(b) Set the list’s capacity in advance using List&lt;string&gt; to avoid repeated resizing.”</p><p>Yeah, that&#39;s always a great idea, if you know the approximate size of the List&lt;T&gt; you should always opt for initializing its size to the target size, avoid resizing it during the Add operation. But we do not know the approximate size of the result array, for all we know it could be the whole 500,000 users, or 0. It is an O(n) space problem here, you either init for the whole 500,000 users, or agree to increase size at least once.</p><p>Lets think about increasing size. If we leave the list uninitialized it starts with capacity 0. Adding even 1 element will allocate 4 slots, adding 4 slots will double the capacity to 8, then 16, then 32… you get the picture, its a geometric series, powers of 2.</p><p>On the 19th resize we will reach a capacity of 524,288 elements. That’s a lot of copies saved if we are smart about properly initializing our results list. But we’d also be smart to remember, the underlaying data structure underneath the List&lt;T&gt; is actually a T[] , when we are resizing we are actually using Array.Copy which is highly optimized and very fast. Anyways, using the proper initialization is a good idea, but not a solution to shit code, it might patch it now, but when the requests-per-second rise, this solution will fail again.</p><p>By the way, the OP was expecting the answer to set the size of the List&lt;T&gt; before working with it.</p><h4>Benchmarking the suggested solutions</h4><p>I’ve gone ahead created benchmarks for each of the suggested solutions, they could be <a href="https://gist.github.com/EugeneKrapivin/1575eaa3e4a0238c988595fff4744b20">found here</a>. You have fun reading through, I’ll just post the numbers:</p><p>This is my setup</p><pre>BenchmarkDotNet v0.15.6, Windows 11 (10.0.26200.9278)<br>11th Gen Intel Core i9-11950H 2.60GHz (Max: 2.61GHz), 1 CPU, 16 logical and 8 physical cores<br>  [Host] : .NET 10.0.11, X64 NativeAOT x86-64-v4<br><br>Toolchain=InProcessNoEmitToolchain</pre><p>And as for the results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11ebaef4310b28b40a6baefd0833706a/href">https://medium.com/media/11ebaef4310b28b40a6baefd0833706a/href</a></iframe><p>As you see they all behave roughly the same. as expected the PreSizesList is a bit faster due to not having to copy the lists 20 times, but the memory footprint doesn’t show any real improvements.</p><h4>Why they don’t actually matter?</h4><p>Well, lets break the code apart and ask some questions</p><pre>public List&lt;string&gt; GetActiveUserNames(List&lt;User&gt; users)<br>{<br>    var result = new List&lt;string&gt;();<br><br>    foreach (var user in users)<br>    {<br>        if (user.IsActive)<br>        {<br>            result.Add(user.Name.ToUpper());<br>        }<br>    }<br><br>    return result;<br>}</pre><ol><li>Why are we getting a List&lt;User&gt; ? Could it be edited externally? because if it is altered while we are iterating over it using foreach we are going to have a nasty InvalidOperationException: collection was modified</li><li>If the List&lt;User&gt; input comes from a DB, why doesn’t it filter by the IsActive column/property and retrieve only what we need?</li><li>Those ToUpper() calls seem cheap, but in reality they allocate a new string where all characters were changed to upper case, I assume after we return the result these strings are no longer needed and will require GC with the list. Very wasteful, probably all the time we’ve saved by pre-allocating the result list will be wasted in some GC pause down the road.</li><li>Why does every request have to process this whole information? Does it get updated in a single place? if so, why not cache it for a long period and revoke in the single place which alters the data?</li></ol><h3>What I’d do?</h3><p>I’d be asking different questions about this piece of code altogether, because the solution approach as a whole is wrong, not the individual suggested solutions, those have their merit when used in the proper place.</p><ol><li>I’d use a DB and query it to only get what I need, maybe even move the ToUpper call into the DB if possible.</li><li>Definitely understand the requirements from this data and evaluate the possibility to cache it to avoid calling the DB for this query.</li><li>If we must use the Name property in upper case, maybe save a virtual/calculated column or even the specific column in upper case from the get go, just to avoid doing those ToUpper operations.</li></ol><h3>Take away</h3><p>LinkedIn always was a social network with tons go garbage, it became an AI slop swamp since the rise of the LLMs, everyone is an architect, which out the millage.</p><p>There is a reason why LinkiDinki added the Seems like AI slop option, please use it.</p><p>If you are creating content on LinkedIn, create it by hand, from experience, use AI to help polish, like I’m going to do once I’m done with my long format rant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42845698ba0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deduplicate your processes using the TaskCompletionSource]]></title>
            <link>https://medium.com/@nocgod/deduplicate-your-processes-using-the-taskcompletionsource-ee70567b74e1?source=rss-5c3971e71656------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee70567b74e1</guid>
            <dc:creator><![CDATA[Eugene Krapivin]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 11:25:08 GMT</pubDate>
            <atom:updated>2024-09-01T11:25:38.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exposition</h3><p>It’s 3 AM. The service you deployed with five instances has been running smoothly for a while, but suddenly, CPU usage spikes, the service hangs, and alerts start blaring. A tired engineer is jolted awake to address the crisis. This was the start of my journey to debug a service with unexplained CPU behavior, leading to uncontrolled scale-out on Kubernetes and eventually, a full service crash.</p><p>The core of the problem was linked to an outdated memcached driver, which we eventually resolved by swapping it out. However, the process of deduplicating the configuration update logic was a vital part of the refactor that followed, ensuring our services became more robust and resilient.</p><h3>Updating configurations</h3><p>One of the features of our internal framework is “Recreate clients on configuration update”. Which sounds nice: You change a connection string in the config, and the service just continues to work, without a restart, using the new connection string.</p><p>Some old wrapper code we had was wrapping an some old, long unmaintained memcached driver. On each call to any operation we’d first check if the config was changed. If it was, we recreated the clients before we executed the operation. But the client is a singleton, its one. There is no need to recreate it multiple times.</p><p>See the problem?</p><h4>The problem</h4><p>Under load, multiple requests would flow through the memcached client, triggering multiple, parallel configuration updates. Although these updates were rare, they could sometimes lead to simultaneous client disposal and recreation.</p><p>Luckily the original developer thought of that and used the common “check-lock-check” pattern.</p><pre>private async Task UpdateConfig()<br>{<br>    try<br>    {<br>        var config = await _getConfig();<br><br>        if (ReferenceEquals(_currentConfig, config))<br>        {<br>            return;<br>        }<br><br>        lock (_configLock)<br>        {<br>            if (ReferenceEquals(_currentConfig, config))<br>            {<br>                return;<br>            }<br><br>            _currentConfig = config;<br><br>            CreateMemcachedClient();<br>        }<br>    }<br>    catch (Exception ex)<br>    {<br>        // redacted<br>    }<br>}</pre><p>At first glance, this looks fine, right? Unfortunately, no. Using a lock inside an asynchronous context can lead to performance degradation (because the thread is locked), potential deadlocks, and the inability to use await inside a lock. The internet is full of reasons why this pattern is problematic. Instead, a SemaphoreSlim would be a better alternative.</p><h3>First rewrite</h3><p><a href="https://learn.microsoft.com/en-us/dotnet/standard/threading/semaphore-and-semaphoreslim">SemaphoreSlim</a> supports asynchronous programming, making it our first attempt at improving this code.</p><pre>private readonly SemaphoreSlim _configSemaphore = new(1,1);<br>private async Task UpdateConfig()<br>{<br>    try<br>    {<br>        var config = await _getConfig();<br><br>        if (ReferenceEquals(_currentConfig, config))<br>        {<br>            return;<br>        }<br><br>        await _configSemaphore.WaitAsync();<br>        try<br>        {<br>            if (ReferenceEquals(_currentConfig, config))<br>            {<br>                return;<br>            }<br><br>            _currentConfig = config;<br><br>            CreateMemcachedClient();<br>        }<br>        finally<br>        {<br>            _configSemaphore.Release();<br>        }<br>    }<br>    catch (Exception ex)<br>    {<br>        // redacted<br>    }<br>}</pre><p>Now, the critical section is safe to use await statements, and we’re not locking a thread unnecessarily. However, there are still issues:</p><ul><li>We’re retrieving the configuration multiple times.</li><li>We’re double-checking the reference.</li><li>Worst of all, each flow calling this method has to await the semaphore, only to do what all other tasks have already done.</li></ul><p>We could move the semaphore higher, but that would only enlarge the critical section without solving the outlined problems.</p><h3>Second rewrite: TaskCompletionSource</h3><p>Enter the <a href="https://devblogs.microsoft.com/pfxteam/the-nature-of-taskcompletionsourcetresult/">TaskCompletionSourc</a>e. This tool allows us to streamline our approach, ensuring only a single execution enters, and most importantly, executes, the critical section.</p><pre>private TaskCompletionSource _updateConfigTcs;<br>private async Task UpdateConfig()<br>{<br>    var tcs = Interlocked.CompareExchange(<br>        ref _updateConfigTcs, <br>        new TaskCompletionSource(), <br>        null);<br>        <br>    if (tcs is not null)<br>    {<br>        await tcs.Task;<br>        return;<br>    }<br><br>    try <br>    {<br>        var config = await _getConfig();<br>            <br>        if (ReferenceEquals(_currentConfig, config))<br>        {<br>            return;<br>        }<br><br>        _currentConfig = config;<br><br>        CreateMemcachedClient();<br>    }<br>    catch (Exception ex)<br>    {<br>        // redacted<br>    }<br>    finally    <br>    {<br>        if (!_updateConfigTcs.TrySetResult())<br>        {<br>            _updateConfigTcs.SetException(<br>                new InvalidOperationException());<br>        }<br>        Interlocked.Exchange(ref _updateConfigTcs, null);<br>    }          <br>}</pre><h3>Breaking it down</h3><h4>Entering the critical section</h4><p>The first thing we’ll do is atomically set an new TaskCompletionSource.</p><pre>var tcs = Interlocked.CompareExchange(<br>        ref _updateConfigTcs, <br>        new TaskCompletionSource(), <br>        null);</pre><p>The interesting thing to note is that only 1 thread would be able to do that, all other threads are going to get the TaskCompletionSource that the first thread placed in _updateConfigTcs. So the first thread getting here, will have a null value in tcs, the rest however will have a non-null value for tcs.</p><pre>if (tcs is not null)<br>{<br>    await tcs.Task;<br>    return;<br>}</pre><h4>Handling Concurrent Requests</h4><p>All threads except the first one, will enter this if statement and await tcs.Task, letting the threads detach from the execution and find something else to do. A neat thing to notice is that once the tcs.Task is resolved, the execution flow doesn’t continue the method. Well, that means that only a single flow execution stepped over this if statement.</p><h4>Critical Section</h4><p>Now that we’ve made sure that only a single execution is allowed in the critical section, we’ve effectively de-duplicated the critical section. Only the first execution will execute the critical section.</p><pre>try <br>{<br>  // this code didn&#39;t change between versions<br>}<br>catch (Exception ex)<br>{<br>    _updateConfigTcs.SetException(ex);<br>    throw;<br>}<br>finally    <br>{<br>    if (!_updateConfigTcs.TrySetResult())<br>    {<br>        _updateConfigTcs.SetException(<br>            new InvalidOperationException());<br>    }<br>    Interlocked.Exchange(ref _updateConfigTcs, null);<br>}</pre><p>It is crucial that the critical section is followed by a release of the “lock” we’ve taken. Since all the executions are awaiting for the tcs.Task to resolve, we must make sure that it resolves one way or the other. This is why the critical section is wrapped in a try-finally block, thus ensuring we either call SetResult (TrySetResult in this example) or SetException in case we encountered one.</p><p>Last thing to do is make sure we nullify the _updateConfigTcs. This way, the next flow executing the UpdateConfig method will not be automatically resolving on an old TaskCompletionSource.</p><h4>Conclusion</h4><p>In a highly parallelized environment, it’s easy to overlook the importance of managing critical sections correctly. The TaskCompletionSource is a valuable tool in ensuring that your code executes only once, benefiting all awaiting tasks. This approach can prevent unnecessary work and reduce the risk of performance issues, making your services more resilient in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee70567b74e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro-benchmarking and code optimization]]></title>
            <link>https://medium.com/@nocgod/micro-benchmarking-and-code-optimization-5d3e8e393569?source=rss-5c3971e71656------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d3e8e393569</guid>
            <dc:creator><![CDATA[Eugene Krapivin]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 06:45:22 GMT</pubDate>
            <atom:updated>2023-07-05T07:23:22.413Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I will show some code optimization techniques I’ve encountered, how to approach to micro optimizations to code, my thought process and how spans simplify this endeavour.</p><p>A while ago I had to help out migrating passwords from a SAP ABAP system to another solution supporting standard password hashing algorithms like <a href="https://en.wikipedia.org/wiki/PBKDF2">PBKDF2</a>. The migration process is very simple, but alas, it required full implementation of the <a href="https://patents.google.com/patent/US20080235772">patented SAP algorithm</a> (hashing and verification).</p><p>But we aren’t here to talk about the migration process. I want to talk about how I optimized the run time and memory footprint of the C# implementation of the SAP ABAP password hashing algorithm.</p><p>All the code for this post could be found on my github <a href="https://github.com/EugeneKrapivin/BenchmarkingAndOptimizationSnippins">EugeneKrapivin/BenchmarkingAndOptimization</a></p><h3>The Algorithm</h3><p>The ABAP password hashing algorithm is a patented hashing algorithm used by some older SAP systems. This algorithm should not be used in production (in my opinion), since there are better solutions recommended by NIST (like the aforementioned PBKDF2 algorithm).</p><p>The gist of the algorithm is:</p><pre>password &lt;- get clear text password utf8 bytes<br>r_1 &lt;-sha(password.salt)<br>r_n &lt;- sha(password.r_n-1)</pre><p>This is an iterative algorithm aimed to hash the password for N rounds using a standard hashing algorithm like SHA1, SHA256, SHA384. The full algorithm also encodes the result, but this post will not discuss this encoding.</p><h3>Optimization cycle</h3><p>An optimization cycle is deceivingly simple, it’s actually 2 steps:</p><ol><li>Benchmark</li><li>Optimize</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*q4L7BjTtTVaccDqlwa7rzg.png" /><figcaption>optimization cycle</figcaption></figure><p>But there are some prerequisites:</p><ol><li><strong>Define you KPIs</strong> — As I mentioned earlier, performance is contextual. Something taking 100ms and 1KB of memory to execute might not be a pain point in one place but a horror show in another. Define measurable KPIs and reasonable targets that work well in the context of your business.</li><li><strong>Measure your KPIs </strong>— You must develop benchmarks that target your KPIs</li></ol><p>For the purpose of measuring my KPIs, I’ve used the amazing <a href="https://github.com/dotnet/BenchmarkDotNet">BenchmarkDotNet library</a>, which I suggest you familiarize yourself with. It&#39;s a valuable tool on the belt of any C# developer (IMHO).</p><h3>Naive Implementation</h3><p>Our first naive implementation will also be a naive implementation. In your case it will be the existing implementation, we will use it as the baseline against which we will evaluate optimization progress.</p><pre>public static HashedPassword SAPPasswordAlgorithmNaive(string clearText, byte[] salt, HashAlgorithm hasher, int rounds = 1000)<br>{<br>    var passwordBytes = Encoding.UTF8.GetBytes(clearText);<br><br>    var buffer = hasher.ComputeHash(passwordBytes.Concat(salt).ToArray());<br><br>    for (var i = 1; i &lt; rounds; i++)<br>    {<br>        buffer = hasher.ComputeHash(passwordBytes.Concat(buffer).ToArray());<br>    }<br><br>    return new() { PasswordHash = buffer, Rounds = rounds, Salt = salt };<br>}</pre><p>This really is a simple algorithm. From this code you could probably already spot some soar points like the constant calls to ToArray() on the buffer concatenations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18280300341fbdf746af395fa7282f15/href">https://medium.com/media/18280300341fbdf746af395fa7282f15/href</a></iframe><blockquote><strong>Note</strong>: This implementation will be the most readable one, albeit being the worst performer.</blockquote><h4>The results</h4><p>Throughout this post I’ll be adding results to the table above. I’ll add a short legend, just to make sure you understand the results</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2176e0e4b64795eb99d11edf89356add/href">https://medium.com/media/2176e0e4b64795eb99d11edf89356add/href</a></iframe><p>Now let&#39;s get back to optimizing.</p><h3>Get rid of the ToArray allocations</h3><p>The naive implementation concatenated the password byte array with the salt byte array using the LINQ Concat method.</p><pre>passwordBytes.Concat(salt).ToArray();</pre><p>The result of this method is an IEnumerable&lt;T&gt;. In our case, the ComputeHash method doesn’t accept it, so we must call ToArray , thus allocating the concatenated byte array on the heap.</p><p>Lets change the naive function to that we avoid calling ToArray in the loop, using pre-allocated byte arrays.</p><pre>public static HashedPassword SAPPasswordAlgorithmAvoidToArray(string clearText, byte[] salt, HashAlgorithm hasher, int rounds = 1000)<br>{<br>    var passwordBytes = Encoding.UTF8.GetBytes(clearText);<br><br>    var initialArray = new byte[passwordBytes.Length + salt.Length];<br>    passwordBytes.CopyTo(initialArray, 0);<br>    salt.CopyTo(initialArray, passwordBytes.Length);<br>    <br>    var buffer = hasher.ComputeHash(initialArray);<br><br>    var roundBuffer = new byte[passwordBytes.Length + buffer.Length];<br>    passwordBytes.CopyTo(roundBuffer, 0);<br>    for (var i = 1; i &lt; rounds; i++)<br>    {<br>        buffer.CopyTo(roundBuffer, passwordBytes.Length);<br>        buffer = hasher.ComputeHash(roundBuffer);<br>    }<br><br>    return new() { PasswordHash = buffer, Rounds = rounds, Salt = salt };<br>}</pre><p>This implementation allocates 2 byte arrays:</p><ol><li>initialArray — buffer for the initial buffer of the password + salt.</li><li>roundBuffer — buffer for the input between the hashing rounds.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13afdc33217c8a0301e0f70eaa4db705/href">https://medium.com/media/13afdc33217c8a0301e0f70eaa4db705/href</a></iframe><p>This improves the memory footprint nicely, even the runtime is improved. For some use cases this maybe enough of an improvement. However, we will continue to improve a bit more.</p><blockquote><strong>Notice</strong>: the complexity of the code is a bit higher than the naive implementation but it is still very manageable</blockquote><h3>Array Pooling</h3><p>We are still allocating byte arrays, lets avoid it by using Array pooling<a href="https://learn.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1.shared?view=net-7.0#remarks">[1]</a>[<a href="https://adamsitnik.com/Array-Pool/">2</a>]. Following the <a href="https://en.wikipedia.org/wiki/Object_pool_pattern">Object pool pattern</a>, the runtime has pools of arrays, already allocated on the heap ready for use. We will use the `ArrayPool&lt;T&gt;.Shared.Rent` to get at least the passed amount of memory (and not forget to free it in the end… so C).</p><blockquote><strong>Note</strong>: The rent method returns <strong>at least</strong> the amount of requested memory. You must take care not to slide into the buffer parts you aren’t using.</blockquote><pre>public static HashedPassword SAPPasswordAlgorithmArrayPooling(string clearText, byte[] salt, HashAlgorithm hasher, int rounds = 1000)<br>{<br>    var passwordBytes = Encoding.UTF8.GetBytes(clearText);<br>    <br>    var initialArraySize = passwordBytes.Length + salt.Length;<br>    var initialArray = Malloc(initialArraySize);<br>    passwordBytes.CopyTo(initialArray, 0);<br>    salt.CopyTo(initialArray, passwordBytes.Length);<br>    <br>    var buffer = hasher.ComputeHash(initialArray,0, initialArraySize);<br>    <br>    var roundBufferSize = passwordBytes.Length + buffer.Length;<br>    var roundBuffer = Malloc(roundBufferSize);<br>    <br>    passwordBytes.CopyTo(roundBuffer, 0);<br>    <br>    for (var i = 1; i &lt; rounds; i++)<br>    {<br>        buffer.CopyTo(roundBuffer, passwordBytes.Length);<br>        buffer = hasher.ComputeHash(roundBuffer, 0, roundBufferSize);<br>    }<br><br>    var result = new HashedPassword() { PasswordHash = buffer, Rounds = rounds, Salt = salt };<br>    <br>    Free(roundBuffer);<br>    Free(initialArray);<br>    <br>    return result;<br>}<br><br>[MethodImpl(MethodImplOptions.AggressiveInlining)]<br>static byte[] Malloc(int size) =&gt; ArrayPool&lt;byte&gt;.Shared.Rent(size);<br><br>[MethodImpl(MethodImplOptions.AggressiveInlining)]<br>static void Free(in byte[] buffer) =&gt; ArrayPool&lt;byte&gt;.Shared.Return(buffer);</pre><p>I’ve moved the ArrayPool&lt;byte&gt;.Shared.Rent and ArrayPool&lt;byte&gt;.Shared.Return into short static methods for the gag. However, it ended up making the code a bit cleaner (IMHO).</p><p><strong>You must always return rented buffers</strong>, failure to do so will lead to <strong>memory leaks</strong>. The keen-eyed of you have probably noticed that in case of an exception the Free methods will never be called. In a production scenario, Rented memory should be wrapped in <strong>try-finally</strong> to ensure memory is always freed. I will try to address that in the next example.</p><blockquote><strong>Note</strong>: The Malloc and Free methods are decorated with the MethodImplAttribute which hints the compiler to inline the code in these methods where ever they are used by the MethodImplOptions.AggressiveInlining option. It is not strictly required here, the compiler is more than capable to do this optimization on it’s own. Moreover, the whole function call is unnecessary due to how short it is. In the scenario where the method implementation is not inlined it will incur additional performance penalties.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f2fb140bcc7cd33b3b3e5e64e253a4f/href">https://medium.com/media/2f2fb140bcc7cd33b3b3e5e64e253a4f/href</a></iframe><p>Alas, this doesn’t improve our performance by much. Only 2.8% improvement in execution time over the previous implementation and a mere 127 bytes in memory footprint.</p><h3>Eliminate hash algorithm buffer allocation</h3><p>The reason why the previous attempt didn’t improve is because it doesn’t handle the memory pain point. The hasher allocates memory each time we call the ComputeHash method for the return buffer.</p><h4>We can do better.</h4><p>First of all, lets address the memory leak problem I’ve mentioned in the previous implementation. I’ll be adding a small struct as a holder for the rented memory.</p><pre>internal struct RentedMemoryHandle : IDisposable<br>{<br>    private readonly byte[] _buffer;<br>    private int _size;<br><br>    public Span&lt;byte&gt; AsSpan() =&gt; _buffer.AsSpan()[.._size];<br><br>    private RentedMemoryHandle(int size)<br>    {<br>        _buffer = ArrayPool&lt;byte&gt;.Shared.Rent(size);<br>        _size = size;<br>    }<br><br>    [MethodImpl(MethodImplOptions.AggressiveInlining)]<br>    public static RentedMemoryHandle Malloc(int size) =&gt; new(size);<br><br>    public void Dispose()<br>    {<br>        ArrayPool&lt;byte&gt;.Shared.Return(_buffer);<br>    }<br>}</pre><p>Since it implements the IDisposable interface we could use the using keyword to safely dispose of those holders in the end of the scope.</p><p>I’ll also add a small method to return the expected size of the hash, so that we could rent the required buffer:</p><pre>[MethodImpl(MethodImplOptions.AggressiveInlining)]<br>static int GetHashSize&lt;T&gt;(in T alg) where T: HashAlgorithm<br>    =&gt; alg switch<br>    {<br>        SHA1 =&gt; SHA1.HashSizeInBytes,<br>        SHA256 =&gt; SHA256.HashSizeInBytes,<br>        SHA384 =&gt; SHA384.HashSizeInBytes,<br>        SHA512 =&gt; SHA512.HashSizeInBytes,<br>        _ =&gt; throw new NotImplementedException(),<br>    };</pre><p>Now that we’ve got all the required parts in place, this is the next iteration:</p><pre>public static HashedPassword SAPPasswordAlgorithmReuseHashBuffers(string clearText, byte[] salt, HashAlgorithm hasher, int rounds = 1000)<br>{<br>    var passwordByteLen = Encoding.UTF8.GetByteCount(clearText);<br>    using var passwordByteArray = RentedMemoryHandle.Malloc(passwordByteLen);<br>    var passwordBytes = passwordByteArray.AsSpan();<br>    <br>    Encoding.UTF8.GetBytes(clearText, passwordBytes);<br>    <br>    var hashSize = GetHashSize(hasher);<br>    <br>    // get our input array<br>    var hasherInputSize = passwordBytes.Length + Math.Max(salt.Length, hashSize);<br>    using var hashInputByteArray = RentedMemoryHandle.Malloc(hasherInputSize);<br>    var hashInput = hashInputByteArray.AsSpan();<br>    <br>    // prep the input array<br>    passwordBytes.CopyTo(hashInput);<br>    salt.CopyTo(hashInput[passwordBytes.Length..]);<br>    <br>    using var hashBytesArray = RentedMemoryHandle.Malloc(hashSize);<br>    var hashBytes = hashBytesArray.AsSpan();<br>    <br>    var initialSize = passwordBytes.Length + salt.Length;<br>    hasher.TryComputeHash(hashInput[..initialSize], hashBytes, out var _);<br>    <br>    var roundSize = passwordBytes.Length + hashSize;<br>    passwordBytes.CopyTo(hashInput);<br>    for (var i = 1; i &lt; rounds; i++)<br>    {<br>        hashBytes[..hashSize].CopyTo(hashInput[passwordBytes.Length..]);<br>        hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>    }<br>    <br>    return new() { PasswordHash = hashBytes[..hashSize].ToArray(), Rounds = rounds, Salt = salt }; ;<br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8454c70dbd535bf2642efa7b303e4f5/href">https://medium.com/media/b8454c70dbd535bf2642efa7b303e4f5/href</a></iframe><p>This implementation begins to get closer to my final version. Notice the complexity of the implementation, memory being copied all over, what a mess. However, changing the ComputeHash to TryComputeHash allowed us to pass in a Span&lt;byte&gt; which we can rent and avoid allocations.</p><h4>Let’s talk a bit about Span&lt;T&gt;</h4><p>Spans were introduced in C# 7.2, alongside struct ref on which the Span&lt;T&gt; is built. This means that the Span&lt;T&gt; can not be allocated on the heap nor can it be boxed. This means that Span&lt;T&gt; are very performant constructs.</p><h4>But what is it???</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*sPJIUt5QpKlVNtYHMlg9kA.png" /></figure><p>You can use spans to represent continuous memory, like arrays, native memory and stack memory (we’ll explore this option next). Why is it useful? it allows you to address memory in a uniform way without incurring heap overhead (since the span is not allocated on the heap). In addition, spans allow us to “slice” data. However, unlike Substring or similar operations, slices use the same array, just change the reference to array start and array end indexes. This description is a gross oversimplification of the real implementation (which you could <a href="https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Span.cs">check out here</a>). I won’t try to provide a simplified implementation of a span, you should really take a look at the original implementation and try to wrap your head around it. It plays with “pointers” and “pointer math” to an extent. You can read more on spans <a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2018/january/csharp-all-about-span-exploring-a-new-net-mainstay">in this post by Stephen Toub</a> and many others, like <a href="https://adamsitnik.com/Span/">this one</a> by Adam Sitnik.</p><h3>Lets get whacky and not use the heap at all</h3><p>This implementation replaces the use of array pooling (and the Malloc and Free methods) and uses instead stackalloc . Previously, the use of stackalloc was confined to unsafe code regions. However, with the introduction of Span&lt;T&gt; we are able to use it in regular code regions as well.</p><pre>public static HashedPassword SAPPasswordAlgorithmStackAllocation(string clearText, byte[] salt, HashAlgorithm hasher, int rounds = 1000)<br>{<br>    var passwordBytesCount = Encoding.UTF8.GetByteCount(clearText);<br>    Span&lt;byte&gt; passwordBytes = stackalloc byte[passwordBytesCount];<br>    Encoding.UTF8.GetBytes(clearText, passwordBytes);<br>    <br>    // look for implementation in the previous iteration<br>    var hashSize = GetHashSize(hasher);<br>    <br>    var hasherInputSize = passwordBytes.Length + Math.Max(salt.Length, hashSize);<br>    Span&lt;byte&gt; hashInput = stackalloc byte[hasherInputSize];<br>    <br>    passwordBytes.CopyTo(hashInput);<br>    salt.CopyTo(hashInput[passwordBytes.Length..]);<br>    <br>    Span&lt;byte&gt; hashBytes = stackalloc byte[hashSize];<br>    var initialSize = passwordBytes.Length + salt.Length;<br>    <br>    hasher.TryComputeHash(hashInput[..initialSize], hashBytes, out var _);<br>    <br>    var roundSize = passwordBytes.Length + hashSize;<br>    passwordBytes.CopyTo(hashInput);<br>    for (var i = 1; i &lt; rounds; i++)<br>    {<br>        hashBytes.CopyTo(hashInput[passwordBytes.Length..]);<br>        hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>    }<br>    <br>    return new() { PasswordHash = hashBytes.ToArray(), Rounds = rounds, Salt = salt };<br>}</pre><blockquote><strong>Note</strong>: You should be careful to not over allocate on the stack since you might get a nice stack overflow :) For more “does and don’ts” when using stackalloc please <a href="https://vcsjones.dev/stackalloc/">checkout this very nice post</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*VhB6tfPEusl4nF983pOkdw.png" /><figcaption>Stack overflow</figcaption></figure><p>This implementation is a bit easier on the eye to my taste. However, it has the same performance as the previous implementation, we only allocate once at the end when returning the hashed password. This also could be avoided if we change the method signature to accept an external buffer for the hashed password.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b6c5ecfa696dbded666706f514ff1d9/href">https://medium.com/media/5b6c5ecfa696dbded666706f514ff1d9/href</a></iframe><blockquote><strong>Interesting note</strong>: Actually the performance on the stackalloc version is consistently slower than the previous one. I’m sad to say I’m not sure why though. If you have a theory (or a solution) ping the comments :)</blockquote><h3>Bonus: loop unrolling</h3><p>Let’s get off the charts.</p><p>I won’t try to define what loop unrolling is, I’ll just copy from <a href="https://en.wikipedia.org/wiki/Loop_unrolling">Wikipedia</a>:</p><blockquote><strong>Loop unrolling</strong>, also known as <strong>loop unwinding</strong>, is a <a href="https://en.wikipedia.org/wiki/Loop_transformation">loop transformation</a> technique that attempts to optimize a program’s execution speed at the expense of its <a href="https://en.wikipedia.org/wiki/Binary_file">binary</a> size, which is an approach known as <a href="https://en.wikipedia.org/wiki/Space%E2%80%93time_tradeoff">space–time tradeoff</a>. The transformation can be undertaken manually by the programmer or by an <a href="https://en.wikipedia.org/wiki/Optimizing_compiler">optimizing compiler</a>. <strong>On modern processors, loop unrolling is often counterproductive, as the increased code size can cause more cache misses;</strong></blockquote><p>So, with this in mind, I present you with the following:</p><pre>public static HashedPassword SAPPasswordAlgorithmStackAllocationUnroll(string clearText, byte[] salt, HashAlgorithm hasher, int rounds = 1000)<br>{<br>    var passwordBytesCount = Encoding.UTF8.GetByteCount(clearText);<br>    Span&lt;byte&gt; passwordBytes = stackalloc byte[passwordBytesCount];<br>    Encoding.UTF8.GetBytes(clearText, passwordBytes);<br>    <br>    var hashSize = GetHashSize(hasher);<br>    <br>    // get our input array<br>    var hasherInputSize = passwordBytes.Length + Math.Max(salt.Length, hashSize);<br>    Span&lt;byte&gt; hashInput = stackalloc byte[hasherInputSize];<br>    <br>    // prep the input array<br>    passwordBytes.CopyTo(hashInput);<br>    salt.CopyTo(hashInput[passwordBytes.Length..]);<br>    <br>    Span&lt;byte&gt; hashBytes = stackalloc byte[hashSize];<br>    var initialSize = passwordBytes.Length + salt.Length;<br>    <br>    hasher.TryComputeHash(hashInput[..initialSize], hashBytes, out var _);<br>    <br>    var roundSize = passwordBytes.Length + hashSize;<br>    passwordBytes.CopyTo(hashInput);<br>    <br>    var left = rounds - 1;<br>    const int unroll = 6;<br>    var loops = left / unroll;<br>    var additional = left - loops * unroll;<br>    <br>    for (var i = 0; i &lt; loops; i++)<br>    {<br>        hashBytes.CopyTo(hashInput[passwordBytes.Length..]);<br>        hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>        hashBytes.CopyTo(hashInput[passwordBytes.Length..]);<br>        hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>        hashBytes.CopyTo(hashInput[passwordBytes.Length..]);<br>        hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>        hashBytes.CopyTo(hashInput[passwordBytes.Length..]);<br>        hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>        hashBytes.CopyTo(hashInput[passwordBytes.Length..]);<br>        hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>        hashBytes.CopyTo(hashInput[passwordBytes.Length..]);<br>        hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>    }<br>    <br>    for (var i = 0; i &lt; additional; i++)<br>    {<br>     hashBytes.CopyTo(hashInput[passwordBytes.Length..]);<br>     hasher.TryComputeHash(hashInput[..roundSize], hashBytes, out var _);<br>    }<br>    <br>    return new HashedPassword() { PasswordHash = hashBytes.ToArray(), Rounds = rounds, Salt = salt };<br>}</pre><p>This implementation <strong>has</strong> a small improvement in execution time, albeit having a tighter error and standard deviation margins. I’m not sure this improvement is worth the decrease in readability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5162256ecd90ae923756ae162b12d34f/href">https://medium.com/media/5162256ecd90ae923756ae162b12d34f/href</a></iframe><h3>Summary</h3><p>I’ve started the task, expecting to have fun, and fun I had. Considering the code had to be used in a hot path, I’ve opted for the most performance I could get with 0 regards to readability; Fully hoping that at some point we will stop migrating users from client’s legacy systems that bring onboard strange password algorithms.</p><p>I hope this post gave you a glance into some interesting techniques for improving performance around the usage of arrays, ArrayPooling and stack allocation. You should probably not opt-in into using them from the get go, but rather refactor the implementation to use them if your performance requirements demand it. As you’ve probably noticed, the more we tried to optimize, the more unreadable the code got. You should always prefer code readability and maintainability when possible, given it answers your performance requirements. Keep in mind that all performance gains you’ll gain through optimization might be lost in the time you try to maintain the code.</p><p>If you’ve got an idea on how to even further improve the execution time (I’m pretty sure we are on the money with memory footprint), feel free to comment or submit a pull-request with a test and benchmark entry on github <a href="https://github.com/EugeneKrapivin/BenchmarkingAndOptimizationSnippins">EugeneKrapivin/BenchmarkingAndOptimization</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d3e8e393569" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing CLIs in C#]]></title>
            <link>https://medium.com/@nocgod/writing-clis-in-c-3d84fe8da735?source=rss-5c3971e71656------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d84fe8da735</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[spectreconsole]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[mediatr]]></category>
            <dc:creator><![CDATA[Eugene Krapivin]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 06:24:15 GMT</pubDate>
            <atom:updated>2023-03-16T14:51:44.483Z</atom:updated>
            <content:encoded><![CDATA[<p>CLIs provide a quick and easy way to interact with your applications, without the need for a graphical user interface (GUI). In this post I’ll be building a simple CLI tool using some libraries I found very useful while building a CLI at work.</p><ul><li><a href="https://spectreconsole.net/">Spectre.Console</a> is a cross-platform library for building beautiful console applications in .NET. It provides a simple API for working with colors, styles, and tables, and makes it easy to create a great-looking CLI.</li><li><a href="https://github.com/jbogard/MediatR">MediatR</a> is a library that allows you to use the Mediator pattern in your applications. It provides a simple way to decouple your code and make it more modular, which is essential when building complex CLI applications.</li></ul><blockquote>Note: throughout this post I’ll be using various features from <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10">C# 10</a> and <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11">C# 11</a> like the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required">required keyword</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#raw-string-literals">raw string literals</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#file-scoped-namespace-declaration">file scoped namespaces</a> and probably others I’ve missed. <strong>I strongly suggest you go checkout the references :)</strong></blockquote><h3>Setting up your project</h3><blockquote><strong>Note</strong>: All the code from this post is available on github: <a href="https://github.com/EugeneKrapivin/MyAwesomeCLI">https://github.com/EugeneKrapivin/MyAwesomeCLI</a></blockquote><p>To get started, create a new C# console application:</p><pre>dotnet new console -n MyAwesomeCLI</pre><p>Then, add the following NuGet packages to your project:</p><pre>dotnet add package Spectre.Console.Cli --version 0.46.1-preview.0.13<br>dotnet add package MediatR --version 12.0.1<br>dotnet add package Microsoft.Extensions.DependencyInjection --version 8.0.0-preview.1.23110.8</pre><p>Once you’ve added the packages, you’re ready to start building your CLI.</p><h3>Scaffold your application</h3><p>Before we begin writing commands and handlers, lets first build out our “boilerplate” code to allow us to tie up together all the parts we will write.</p><p>In the program.cs file you’ll find the new (somewhat empty) console template:</p><pre>// See https://aka.ms/new-console-template for more information<br>Console.WriteLine(&quot;Hello, World!&quot;);</pre><p>we will now plug-in MediatR</p><pre>using Microsoft.Extensions.DependencyInjection;<br><br>var services = new ServiceCollection();<br><br>services.AddMediatR(cfg =&gt; cfg.RegisterServicesFromAssemblyContaining&lt;Program&gt;());  </pre><p>currently this code does nothing, but we will begin doing some magic soon.</p><p>Next, we will plug in Spectre.Console. In order to integrate Spectre.Console with the microsoft DI library we have to pass it in and wrap it using a type called TypeRegistrar we find in their <a href="https://github.com/spectreconsole/spectre.console/tree/main/examples/Cli/Injection/Infrastructure">examples</a>:</p><pre>using System;<br>using Microsoft.Extensions.DependencyInjection;<br>using Spectre.Console.Cli;<br><br>namespace Injection.Infrastructure;<br><br>public sealed class TypeRegistrar : ITypeRegistrar<br>{<br>    private readonly IServiceCollection _builder;<br><br>    public TypeRegistrar(IServiceCollection builder)<br>    {<br>        _builder = builder;<br>    }<br><br>    public ITypeResolver Build()<br>    {<br>        return new TypeResolver(_builder.BuildServiceProvider());<br>    }<br><br>    public void Register(Type service, Type implementation)<br>    {<br>        _builder.AddSingleton(service, implementation);<br>    }<br><br>    public void RegisterInstance(Type service, object implementation)<br>    {<br>        _builder.AddSingleton(service, implementation);<br>    }<br><br>    public void RegisterLazy(Type service, Func&lt;object&gt; func)<br>    {<br>        if (func is null)<br>        {<br>            throw new ArgumentNullException(nameof(func));<br>        }<br><br>        _builder.AddSingleton(service, (provider) =&gt; func());<br>    }<br>}</pre><p>and the type resolver class:</p><pre>using System;<br>using Spectre.Console.Cli;<br><br>namespace Injection.Infrastructure;<br><br>public sealed class TypeResolver : ITypeResolver, IDisposable<br>{<br>    private readonly IServiceProvider _provider;<br><br>    public TypeResolver(IServiceProvider provider)<br>    {<br>        _provider = provider ?? throw new ArgumentNullException(nameof(provider));<br>    }<br><br>    public object Resolve(Type type)<br>    {<br>        if (type == null)<br>        {<br>            return null;<br>        }<br><br>        return _provider.GetService(type);<br>    }<br><br>    public void Dispose()<br>    {<br>        if (_provider is IDisposable disposable)<br>        {<br>            disposable.Dispose();<br>        }<br>    }<br>}</pre><p>I’m not sure why these classes aren’t part of the package distribution, but it is what it is :) just copy those into your code and lets continue. After copy-paste-engineering the TypeResolver and TypeRegistrar classes into our project, lets create the app and pass the arguments into it.</p><pre>using Microsoft.Extensions.DependencyInjection;<br>using Spectre.Console.Cli;<br><br>using MyAwesomeCLI;<br><br>var services = new ServiceCollection();<br><br>services.AddMediatR(cfg =&gt; cfg.RegisterServicesFromAssemblyContaining&lt;Program&gt;());<br><br>var registrar = new TypeRegistrar(services);<br><br>var app = new CommandApp(registrar);<br><br>await app.RunAsync(args);</pre><p>Already, if we run this application we have an output:</p><pre>USAGE:<br>    MyAwesomeCLI.dll [OPTIONS] &lt;COMMAND&gt;<br><br>OPTIONS:<br>    -h, --help       Prints help information<br>    -v, --version    Prints version information</pre><p>Awesome! Now, that we are sort-of done with the boiler plate, lets make some meaningful code.</p><h3>The premise</h3><p>Let&#39;s assume we are building a CLI for a big SaaS system that manages deployments. Managing each deployment manually from a friendly web UI is easy even when you have a handful of deployments. However, when you are managing thousands of deployments, it is not easy to manage.</p><p>So let&#39;s assume we are building our nifty CLI for such a system. To begin with, we need to define some sort of execution context. It will scope the actions of our CLI to a specific set of deployments and credentials. Somewhat like the context in kubectl .</p><p>So lets define those classes:</p><pre>public class ContextModel<br>{<br>    public string CurrentContext { get; set; } = string.Empty;<br>    public List&lt;WorkspaceContext&gt; DefinedContexts { get; set; } = new();<br>}<br><br>public class WorkspaceContext<br>{<br>    public required string Name { get; set; }<br>    public required string UserKey { get; set; }<br>    public required string Secret { get; set; }<br>}</pre><p>Now that we have a model, left define our commands:</p><ul><li>create a new context awesomecli context create --name &lt;name&gt; --user-key &lt;key&gt; --user-secret &lt;secret&gt;</li><li>set current context awesomecli context set --name &lt;name&gt;</li><li>get current context awesomecli context current</li><li>delete a context awesomecli context delete --name</li><li>list all contexts awesomecli context --list-all</li></ul><p>A legit list of commands. So let’s get our hands dirty.</p><h3>Defining your commands</h3><p>Commands in Spectre.Console are defined by inheriting the Command&lt;TCommandSettings&gt; or the AsyncCommand&lt;TCommandSettings&gt; abstract classes:</p><pre>public class CreateContextCommand : AsyncCommand&lt;CreateContextCommand.CreateContextArgument&gt;<br>{<br>    public override Task&lt;int&gt; ExecuteAsync(CommandContext context, CreateContextArgument settings)<br>    {<br>        throw new NotImplementedException();<br>    }<br><br>    public class CreateContextArgument : CommandSettings<br>    {<br>        [Required]<br>        [CommandOption(&quot;-n|--name&quot;)]<br>        public string Name { get; set; }<br><br>        [Required]<br>        [CommandOption(&quot;-u|--user-key&quot;)]<br>        public string UserKey { get; set; }<br><br>        [Required]<br>        [CommandOption(&quot;-s|--user-secret&quot;)]<br>        public string Secret { get; set; }<br>    }<br>}</pre><p>Notice that in order to define command arguments/options we will create another class (I prefer to nest it as it doesn’t have any use outside of the command class itself).</p><blockquote><strong>Note</strong>: There are 2 types of settings supported by Spectre.Console the Option and the Argument. Please refer to <a href="https://spectreconsole.net/">their documentation</a> for more information about defining the <a href="https://spectreconsole.net/cli/settings">command settings</a>.</blockquote><p>We will begin with a command to create a new context. This implementation is very naive:</p><pre>public override Task&lt;int&gt; ExecuteAsync(CommandContext commandContext, CreateContextArgument settings)<br>{<br>    const string cliFolder = &quot;.awesome_cli&quot;;<br>    const string configFileName = &quot;.awesome_cli.config&quot;;<br>    var targetFolder = Path.Combine(GetFolderPath(SpecialFolder.UserProfile), cliFolder);<br>    var targetFile = Path.Combine(targetFolder, configFileName);<br>    <br>    Directory.CreateDirectory(targetFolder); // ensure the directory exists<br><br>    var cliContext = new CliContext<br>    {<br>        Name = settings.Name,<br>        UserKey = settings.UserKey,<br>        Secret = settings.Secret<br>    };<br><br>    var cliContextCollection = new ContextModel<br>    {<br>        CurrentContext = cliContext.Name,<br>        DefinedContexts = { { cliContext } }<br>    };<br><br>    var content = JsonSerializer.Serialize(cliContextCollection, new JsonSerializerOptions<br>    {<br>        PropertyNamingPolicy = JsonNamingPolicy.KebabCaseLower<br>    });<br><br>    File.WriteAllText(targetFile, content);<br><br>    AnsiConsole.MarkupLineInterpolated($&quot;Created a new CLI context [green bold]{cliContext.Name}[/]&quot;);<br>    AnsiConsole.Write(new Table()<br>        .AddColumns(&quot;property&quot;, &quot;value&quot;)<br>        .AddRow(&quot;userkey&quot;, settings.UserKey)<br>        .AddRow(&quot;secret&quot;, settings.Secret)); // probably shouldn&#39;t write it back<br>    AnsiConsole.Write(&quot;created at: &quot;);<br>    AnsiConsole.Write(new TextPath(targetFile).RootStyle(new Style(foreground: Color.Red))<br>        .SeparatorStyle(new Style(foreground: Color.Green))<br>        .StemStyle(new Style(foreground: Color.Blue))<br>        .LeafStyle(new Style(foreground: Color.Yellow)));<br><br><br>    return Task.FromResult(0);<br>}</pre><p>As I’ve state, this code is naive:</p><ul><li>there are no input validations</li><li>we are assuming there are no contexts available</li><li>the is not protection from fault — was the directory created? was the file written?</li><li>The CLI logic and the business logic are mixed.</li></ul><p>We will leave this implementation as it is for a while. Lets pipe it all together and then refactor.</p><p>In order for our command to be useable in our app we have to register it. Let’s go back to the program.cs file and edit it a bit</p><pre>var app = new CommandApp(registrar);<br><br>app.Configure(app =&gt;<br>{<br>    app.AddBranch(&quot;context&quot;, context =&gt;<br>    {<br>        context.AddCommand&lt;CreateContextCommand&gt;(&quot;create&quot;)<br>            .WithDescription(&quot;this commands create a new context for our awesome app&quot;)<br>            .WithExample(new[] { &quot;--name&quot;, &quot;test-context&quot;, &quot;--user-key&quot;, &quot;test-user&quot;, &quot;--user-secret&quot;, &quot;test-secret&quot; });<br>    });<br>});<br><br>await app.RunAsync(args);</pre><p>now if we run our application</p><pre>dotnet run -- context create --name test-context --user-key test-user --user-secret test-secret</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*xzHjV_c90xz7bNi9it_zPA.png" /><figcaption>running the command in powershell</figcaption></figure><p>if we go to the path we’ll find:</p><pre>{<br>  &quot;current_context&quot;: &quot;test-context&quot;,<br>  &quot;defined_contexts&quot;: [<br>    {<br>      &quot;name&quot;: &quot;test-context&quot;,<br>      &quot;user_key&quot;: &quot;test-user&quot;,<br>      &quot;secret&quot;: &quot;test-secret&quot;<br>    }<br>  ]<br>}</pre><p>Awesome. Now lets refactor.</p><h3>Using Mediatr to handle commands</h3><p>We are now going to tend to the issues outlined earlier with the naive code. We will begin by decoupling the user-interface code, from the business logic code. This is also a great opportunity to shuffle around the code, so that it is a bit more tidy.</p><p>Let’s create out first command handler and move some of the business logic from the command implementation into the handler implementation:</p><pre>public record CreateContextSuccessResponse(CliContext context, string CreatedAt);<br>public record CreateContextErrorResponse(string Error, string Path);<br>public record CreateContextRequest(string Name, string UserKey, string Secret) :<br>    IRequest&lt;Either&lt;CreateContextSuccessResponse, CreateContextErrorResponse&gt;&gt;;<br><br>internal class CreateContextHandler <br>    : IRequestHandler&lt;CreateContextRequest, Either&lt;CreateContextSuccessResponse, CreateContextErrorResponse&gt;&gt;<br>{<br>    public async Task&lt;Either&lt;CreateContextSuccessResponse, CreateContextErrorResponse&gt;&gt; Handle(CreateContextRequest request, CancellationToken cancellationToken)<br>    {<br>        const string cliFolder = &quot;.awesome_cli&quot;;<br>        const string configFileName = &quot;.awesome_cli.config&quot;;<br>        var targetFolder = Path.Combine(GetFolderPath(SpecialFolder.UserProfile), cliFolder);<br>        var targetFile = Path.Combine(targetFolder, configFileName);<br><br>        var dirInfo = Directory.CreateDirectory(targetFolder); // ensure the directory exists<br>        if (!dirInfo.Exists)<br>            return new CreateContextErrorResponse(&quot;Target directory does not exist&quot;, targetFolder);<br><br>        var cliContext = new CliContext<br>        {<br>            Name = request.Name,<br>            UserKey = request.UserKey,<br>            Secret = request.Secret<br>        };<br><br>        var cliContextCollection = new ContextModel<br>        {<br>            CurrentContext = cliContext.Name,<br>            DefinedContexts = { { cliContext } }<br>        };<br><br>        var content = JsonSerializer.Serialize(cliContextCollection, new JsonSerializerOptions<br>        {<br>            PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,<br>            WriteIndented = true<br>        });<br><br>        // probably should add some protection here as well<br>        await File.WriteAllTextAsync(targetFile, content, cancellationToken);<br><br>        return new CreateContextSuccessResponse(cliContext, targetFile);<br>    }<br>}</pre><p>We will create a request record CreateContextRequest and we will also create 2 response records: one for success and one for failure</p><pre>public record CreateContextSuccessResponse(CliContext context, string CreatedAt);<br>public record CreateContextErrorResponse(string Error, string Path);</pre><p>I’m going a little wild here, but we should keep in mind, that we are building a big CLI tool for a big system, some struts are required to keep it stable. The last bolt in the handler is the response type. I’ve elected to go with the Either&lt;TLeft, TRight&gt; type from the <a href="https://github.com/louthy/language-ext">language-ext</a> library. The reasoning being is that I want to be able to return as much information as possible in case of an error and I prefer not to throw exceptions all around.</p><p>Because our code has moved, there are some changes in the CreateContextCommand as well. We will add a constructor, so that we could inject the mediator component</p><pre>public CreateContextCommand(IMediator mediator)<br>{<br>    _mediator = mediator;<br>}</pre><p>and we will also refactor the whole ExecuteAsync command:</p><pre>public override async Task&lt;int&gt; ExecuteAsync(CommandContext commandContext, CreateContextArgument settings) <br>  =&gt; await _mediator.Send(new CreateContextRequest(settings.Name, settings.UserKey, settings.Secret))<br>      .ToAsync()<br>      .Match(<br>          success =&gt;<br>          {<br>              var (cliContext, targetFile) = success;<br>  <br>              AnsiConsole.MarkupLineInterpolated($&quot;Created a new CLI context [green bold]{cliContext.Name}[/]&quot;);<br>              AnsiConsole.Write(new Table()<br>                  .AddColumns(&quot;property&quot;, &quot;value&quot;)<br>                  .AddRow(&quot;userkey&quot;, settings.UserKey)<br>                  .AddRow(&quot;secret&quot;, settings.Secret)); // probably shouldn&#39;t write it back<br>              AnsiConsole.Write(&quot;created at: &quot;);<br>              AnsiConsole.Write(new TextPath(targetFile).RootStyle(new Style(foreground: Color.Red))<br>                  .SeparatorStyle(new Style(foreground: Color.Green))<br>                  .StemStyle(new Style(foreground: Color.Blue))<br>                  .LeafStyle(new Style(foreground: Color.Yellow)));<br>  <br>              return 0;<br>          },<br>          error =&gt;<br>          {<br>              var (msg, targetFile) = error;<br>  <br>              AnsiConsole.MarkupLine($&quot;[red]Failed to create context at path:[/]&quot;);<br>              AnsiConsole.Write(new TextPath(targetFile).RootStyle(new Style(foreground: Color.Red))<br>                  .SeparatorStyle(new Style(foreground: Color.Green))<br>                  .StemStyle(new Style(foreground: Color.Blue))<br>                  .LeafStyle(new Style(foreground: Color.Yellow)));<br>              AnsiConsole.MarkupLineInterpolated($&quot;[yellow]{msg}[/]&quot;);<br>  <br>              return -1;<br>          });</pre><p>It has been refactored into a more functional style. I’m just having fun =)</p><p>We’ve handled the code mish-mash we had with the user interface code and the business logic. Let’s sprinkle a bit of validation for the command input. For that we will simply override the Validate method or our command class, and use the whatever validation library we want. I’ll go with plain and simple if statements, to keep it simple.</p><pre>public override ValidationResult Validate(CommandContext context, CreateContextArgument settings)<br>{<br>    if (settings.Name == &quot;this-is-a-test-string-to-fail-the-validation&quot;)<br>        return ValidationResult.Error(&quot;context name must not be \&quot;this-is-a-test-string-to-fail-the-validation\&quot;&quot;);<br>    if (string.IsNullOrWhiteSpace(settings.Name))<br>        return ValidationResult.Error(&quot;context name must not be null or empty&quot;);<br>    if (string.IsNullOrWhiteSpace(settings.UserKey))<br>        return ValidationResult.Error(&quot;context user key must not be null or empty&quot;);<br>    if (string.IsNullOrWhiteSpace(settings.Secret))<br>        return ValidationResult.Error(&quot;context user secret must not be null or empty&quot;);<br><br>    return ValidationResult.Success();<br>}</pre><p>Now, running our code with a missing parameter will great us with the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*JRksfNgDwsJRAUba1BSNpg.png" /></figure><p>There is still the matter of handling the case where contexts already exist and we would really like to keep the existing contexts while adding a new one.</p><h3>Services to manage your domain entities</h3><p>Let’s move the logic concerning reading the context, storing the context, retrieving the context, validating the context to a service. The handler won’t know how and where the service stores the data, and it shouldn’t care :)</p><p>I’ll be reusing the same context model from before, just wrapping the persistence and retrieval logic into a service. Some justifications for the move are:</p><ul><li><strong>Decouple concerns</strong> the context persistence and loading concerns from the business logic.</li><li><strong>Improved testability</strong>: we could easily mock out the context management, which will allow us to easily test the request handlers.</li><li><strong>Swappable backend:</strong> In the demo implementation I’m writing a simple json file, but since the logic is decoupled, I could easily move the persistence to SQLite or anything else.</li><li><strong>Caching and resilience:</strong> instead of constantly reading the state to ensure its fresh, we could read it once on each run and persist it only when it changes.</li></ul><p>So lets define our service interface</p><pre>internal interface IContextService<br>{<br>    public Task&lt;Option&lt;CliContext&gt;&gt; GetCurrentContextAsync();<br><br>    public Task&lt;Option&lt;CliContext&gt;&gt; GetContextAsync(string name);<br><br>    public Task&lt;ContextModel&gt; GetAllContextsAsync();<br><br>    public Task&lt;Either&lt;(string error, string path), (CliContext ctx, string path)&gt;&gt; AddContextAsync(string name, string userkey, string secret);<br><br>    public Task&lt;Option&lt;CliContext&gt;&gt; SetCurrentContextAsync(string name);<br><br>    public Task&lt;Option&lt;CliContext&gt;&gt; DeleteContextAsync(string name);<br>}</pre><p>and we’ll implement it, I’ll keep only the constructor and the AddContextAsync methods for brevity, you will be able to find the rest in <a href="https://github.com/EugeneKrapivin/MyAwesomeCLI">the repo</a>.</p><pre>internal class FileSystemContextService : IContextService<br>{<br>    private readonly string _targetFolder;<br>    private readonly string _targetFile;<br>    private readonly ContextModel _context;<br>    private const string _cliFolder = &quot;.awesome_cli&quot;;<br>    private const string _configFileName = &quot;.awesome_cli.config&quot;;<br><br>    public FileSystemContextService(string folderPath = &quot;&quot;)<br>    {<br>        _targetFolder = Path.Combine(CalculateTargetFolder(folderPath), _cliFolder);<br>        _targetFile = Path.Combine(_targetFolder, _configFileName);<br><br>        var dirInfo = Directory.CreateDirectory(_targetFolder);<br><br>        if (!dirInfo.Exists)<br>            throw new Exception($&quot;Target directory \&quot;{_targetFolder}\&quot;does not exist&quot;);<br><br>        var contents = File.ReadAllText(_targetFile);<br>        _context = JsonSerializer.Deserialize&lt;ContextModel&gt;(contents, new JsonSerializerOptions<br>        {<br>            PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower<br>        }) ?? new();<br>    }<br><br>    private static string CalculateTargetFolder(string folderPath) <br>        =&gt; string.IsNullOrWhiteSpace(folderPath) <br>            ? GetFolderPath(SpecialFolder.UserProfile) <br>            : folderPath;<br><br>    private void WriteState()<br>    {<br>        var contents = JsonSerializer.Serialize(_context, new JsonSerializerOptions<br>        {<br>            PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,<br>            WriteIndented = true<br>        });<br><br>        File.WriteAllText(_targetFile, contents);<br>    }<br><br>    public async Task&lt;Either&lt;(string error, string path), (CliContext ctx, string path)&gt;&gt; AddContextAsync(string name, string userkey, string secret)<br>    {<br>        if (_context.DefinedContexts.Any(x =&gt; x.Name == name))<br>        {<br>            return ($&quot;Context with name {name} is already defined.&quot;, _targetFile);<br>        }<br><br>        var ctx = new CliContext<br>        {<br>            Name = name,<br>            Secret = secret,<br>            UserKey = userkey<br>        };<br><br>        _context.DefinedContexts.Add(ctx);<br>        if (string.IsNullOrEmpty(_context.CurrentContext))<br>        {<br>            _context.CurrentContext = name;<br>        }<br><br>        WriteState();<br><br>        return (ctx, _targetFile);<br>    }<br>    // the rest is reducted for brevity.<br>}</pre><p>Now, since we once again moved the logic, we’ll have to refactor our CreateContextHandler</p><pre>internal class CreateContextHandler <br>    : IRequestHandler&lt;CreateContextRequest, Either&lt;CreateContextErrorResponse, CreateContextSuccessResponse&gt;&gt;<br>{<br>    private readonly IContextService _contextService;<br><br>    public CreateContextHandler(IContextService contextService)<br>    {<br>        _contextService = contextService;<br>    }<br><br>    public async Task&lt;Either&lt;CreateContextErrorResponse, CreateContextSuccessResponse&gt;&gt; Handle(CreateContextRequest request, CancellationToken cancellationToken) <br>        =&gt; await _contextService.AddContextAsync(request.Name, request.UserKey, request.Secret)<br>            .ToAsync()<br>            .Case switch<br>            {<br>                (CliContext ctx, string path) =&gt; new CreateContextSuccessResponse(ctx, path),<br>                (string error, string path) =&gt; new CreateContextErrorResponse(error, path),<br>                _ =&gt; throw new NotImplementedException()<br>            };<br>}</pre><p>Surprisingly, it got empty. The reason being is that we do not have any real business logic with regards to this operation. However, if we choose to exchange the userkey and secret for an access token the logic would go into here.</p><p>So let’s just do that. We’ll add another service CredentialsExchangeService which will simulate credentials exchange flow (again, think of how kubectl logs you into a cluster using oidc) and we’ll refactor the CliContext to store the access token instead of the clear text credentials.</p><pre>internal interface IExchangeCredentials<br>{<br>    Task&lt;string&gt; GetCredentialsAsync(string userkey, string secret);<br>}<br><br>public class CredentialsExchangeService : IExchangeCredentials<br>{<br>    // THIS IS NOT REALLY A VALID JWT CREATION FUNCTION, IT IS FOR DEMO PURPOSES ONLY!!!<br>    public Task&lt;string&gt; GetCredentialsAsync(string userkey, string secret)<br>    {<br>        var header = Serialize(new { typ = &quot;at&quot;, alg = &quot;fake&quot; });<br>        var body = Serialize(new<br>        {<br>            iss = &quot;https://your.awesome.idp.provider/&quot;,<br>            aud = &quot;https://your.awesome.cli.backend.service/&quot;,<br>            sub = userkey,<br>            scope = &quot;read write&quot;,<br>            iat = Epoch(DateTime.UtcNow),<br>            exp = Epoch(DateTime.UtcNow.AddDays(30))<br>        });<br>        var signature = SHA256.HashData(Encoding.UTF8.GetBytes($&quot;{header}.{body}&quot;));<br><br>        return Task.FromResult($&quot;{ToB64(header)}.{ToB64(body)}.{Convert.ToBase64String(signature)}&quot;);<br>    }<br><br>    private static string ToB64(string s) =&gt; Convert.ToBase64String(Encoding.UTF8.GetBytes(s));<br>    <br>    private static readonly DateTime _epoch = new(1970, 1, 1, 1, 0, 0, 0, DateTimeKind.Utc);<br>    <br>    private static long Epoch(DateTime dt) =&gt; (long)(dt - _epoch).TotalMilliseconds;<br><br>    private static string Serialize&lt;T&gt;(T obj) =&gt; JsonSerializer.Serialize(obj, Opts);<br><br>    private static JsonSerializerOptions Opts =&gt; new()<br>    {<br>        WriteIndented = true,<br>        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,<br>    };<br>}</pre><p>Register this class in the DI</p><pre>services.AddSingleton&lt;IExchangeCredentials, CredentialsExchangeService&gt;();</pre><p>and refactor the handler a bit to accommodate this business logic:</p><pre>public CreateContextHandler(IContextService contextService, IExchangeCredentials exchangeCredentials)<br>{<br>    _contextService = contextService;<br>    _exchangeCredentials = exchangeCredentials;<br>}<br><br>public async Task&lt;Either&lt;CreateContextErrorResponse, CreateContextSuccessResponse&gt;&gt; Handle(CreateContextRequest request, CancellationToken cancellationToken)<br>{<br>    var creds = await _exchangeCredentials.GetCredentialsAsync(request.UserKey, request.Secret);<br><br>    return await _contextService.AddContextAsync(request.Name, creds)<br>        .ToAsync()<br>        .Case switch<br>        {<br>            (CliContext ctx, string path) =&gt; new CreateContextSuccessResponse(ctx, path),<br>            (string error, string path) =&gt; new CreateContextErrorResponse(error, path),<br>            _ =&gt; throw new NotImplementedException()<br>        };<br>}</pre><p>some minor refactoring is needed to compensate for the model change, but thats minor. You can find a working version of the code (after all the refactoring) in <a href="https://github.com/EugeneKrapivin/MyAwesomeCLI">the repo</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*gqzPByGYkMy6Op121upNNQ.png" /><figcaption>Successfully add a context</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*lihfYubvlOtva1V06zsa1A.png" /><figcaption>Failure - adding an already existing context</figcaption></figure><h3>Summary</h3><p>In this, rather lengthy, post I’ve shown my method of developing CLIs in C#. The idea is really simple:</p><ol><li>Choose a robust library for your CLI parsing and command routing.</li><li>Decouple the user-interface concerns (prompts, prints, etc.) from the business logic.</li><li>Use the mediator pattern to implement #2</li><li>Write services to encapsulate logic components that aren’t directly related to the business logic (data persistence, remote API access, etc.)</li><li>Implement your business logic (#3) using the services (#4)</li></ol><p>This approach really isn’t really much different from what you’d see in many web applications where you have a UI layer, API layer, Business logic layer and finally data access layer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d84fe8da735" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup your dotnet project with test coverage reporting]]></title>
            <link>https://medium.com/@nocgod/how-to-setup-your-dotnet-project-with-a-test-coverage-reporting-6ff1903f7240?source=rss-5c3971e71656------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ff1903f7240</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[coverage]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Eugene Krapivin]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 08:36:39 GMT</pubDate>
            <atom:updated>2022-12-27T14:54:59.246Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>You all probably use Visual Studio Test coverage analysis, <a href="https://www.jetbrains.com/dotcover/">ReSharper dotCover</a> or <a href="https://www.jetbrains.com/rider/">JetBrains Rider</a> and quite happy with it. But there is an another option, which could become quite appealing when working on CI pipelines, or if you want to do it yourself.</p><p>I want to talk about <a href="https://github.com/coverlet-coverage/coverlet">Coverlet </a>and <a href="https://reportgenerator.io/">ReportGenerator</a>, and maybe show you some interesting MSBuild tricks along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_wRS3iyzQuPNaNBKZE4qg.png" /></figure><h3>Coverlet</h3><blockquote>Coverlet is a cross platform code coverage framework for .NET, with support for line, branch and method coverage. It works with .NET Framework on Windows and .NET Core on all supported platforms.</blockquote><p>It ticks some of my personal boxes for being an interesting project:</p><ul><li>Part of the <a href="https://dotnetfoundation.org/">.NET Foundation</a></li><li>free, opensource, cross-platform</li><li>174+ Million downloads on nuget</li><li>2.6K stars on Github</li><li>has 90+ contributors</li><li>awesome documentation</li><li>built-in support with MSBuild</li></ul><p>So what does it do? Gathers coverage metrics of your tests and exports them to one of many supported formats. quite simple. It’s a gross simplification of the tool but it will suffice.</p><h3>Let’s wire it up</h3><blockquote>Quick note on compatibility: Coverlet supports .NET and .NET Framework. However, it strictly requires <a href="https://docs.microsoft.com/en-us/visualstudio/msbuild/how-to-use-project-sdk?view=vs-2019">SDK-style projects.</a></blockquote><p>Add the following package references to the following packages to your test project:</p><ul><li><a href="https://www.nuget.org/packages/coverlet.collector">coverlet.collector</a></li><li><a href="https://www.nuget.org/packages/coverlet.msbuild">coverlet.msbuild</a></li></ul><pre>&lt;Project&gt;<br>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;coverlet.collector&quot; Version=&quot;3.2.0&quot;&gt;<br>      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers&lt;/IncludeAssets&gt;<br>    &lt;/PackageReference&gt;<br>    &lt;PackageReference Include=&quot;coverlet.msbuild&quot; Version=&quot;3.2.0&quot;&gt;<br>      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers&lt;/IncludeAssets&gt;<br>    &lt;/PackageReference&gt;<br>  &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p>Notice that we have to include also the assets. they are build time assets, so no worries. use the terminal of your choice to run it</p><pre>dotnet test --collect:&quot;XPlat Code Coverage&quot;</pre><p>or… since we have MSBuild integration lets have some fun 😄<br>lets edit the test csproj file and add:</p><pre>&lt;Project&gt;<br>&lt;!-- added --&gt;<br> &lt;PropertyGroup&gt;<br>  &lt;CollectCoverage&gt;true&lt;/CollectCoverage&gt;<br>  &lt;CoverletOutput&gt;../coverage/projects/$(MSBuildProjectName)/&lt;/CoverletOutput&gt;<br>  &lt;CoverletOutputFormat&gt;opencover&lt;/CoverletOutputFormat&gt;<br> &lt;/PropertyGroup&gt;<br>&lt;!-- end   --&gt;<br> &lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;coverlet.collector&quot; Version=&quot;3.2.0&quot;&gt;<br>   &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>   &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers&lt;/IncludeAssets&gt;<br>  &lt;/PackageReference&gt;<br>  &lt;PackageReference Include=&quot;coverlet.msbuild&quot; Version=&quot;3.2.0&quot;&gt;<br>   &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>   &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers&lt;/IncludeAssets&gt;<br>  &lt;/PackageReference&gt;<br> &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p>Now, coverlet will be used every time to collect test coverage metrics when you run this test project. In this example, the results will be created in opencover format and stored at ../coverage/projects/$(MSBuildProjectName)/ path.</p><p>Kinda nice… but we ain’t done yet.</p><p>Since you probably have more than a single test project (unit tests, functional tests, integration tests), you should probably avoid putting this code in each an every test project csproj, and instead prefer using the Directory.Build.props</p><p>In short, the Directory.Build.props is a file that MSBuild uses to amend your csproj files. When building a csproj file, MSBuild will actively look for a Directory.Build.props file in the current directory, recursively, until the first one is found.</p><pre>&lt;Project&gt;<br>  &lt;Import Project=&quot;$([MSBuild]::GetPathOfFileAbove(&#39;Directory.Build.props&#39;, &#39;$(MSBuildThisFileDirectory)../&#39;))&quot; /&gt;<br>  &lt;PropertyGroup&gt;<br>    &lt;CollectCoverage&gt;true&lt;/CollectCoverage&gt;<br>    &lt;CoverletOutput&gt;../coverage/projects/$(MSBuildProjectName)/&lt;/CoverletOutput&gt;<br>    &lt;CoverletOutputFormat&gt;opencover&lt;/CoverletOutputFormat&gt;<br>  &lt;/PropertyGroup&gt;<br>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;coverlet.collector&quot;&gt;<br>      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers&lt;/IncludeAssets&gt;<br>    &lt;/PackageReference&gt;<br>    &lt;PackageReference Include=&quot;coverlet.msbuild&quot;&gt;<br>      &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;<br>      &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers&lt;/IncludeAssets&gt;<br>    &lt;/PackageReference&gt;<br>    &lt;PackageReference Include=&quot;ReportGenerator&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p>adding this file to the ./tests directory (assuming you have one to contain all the test projects) will apply those properties and packages to all projects located beneath it.</p><p>The first line ensures that if you have a Directory.Build.props file above this one, it will be included as well. For more information about how the props and targets files work please visit the <a href="https://learn.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2022#directorybuildprops-and-directorybuildtargets">Microsoft MSBuild documentation</a>. After running the tests we see a nice console print out:</p><pre>Passed!  - Failed:     0, Passed:    23, Skipped:     0, Total:    23, Duration: 131 ms - DemoSolution.UnitTests.dll (net6.0)<br><br><br>Calculating coverage result...<br>  Generating report &#39;..\coverage\projects\DemoSolution.UnitTests\coverage.net6.0.opencover.xml&#39;<br><br><br>+-------------------------+--------+--------+--------+<br>| Module                  | Line   | Branch | Method |<br>+-------------------------+--------+--------+--------+<br>| DemoSolution.Core       | 62.31% | 58.33% | 56.41% |<br>+-------------------------+--------+--------+--------+<br><br><br>+---------+--------+--------+--------+<br>|         | Line   | Branch | Method |<br>+---------+--------+--------+--------+<br>| Total   | 62.31% | 58.33% | 56.41% |<br>+---------+--------+--------+--------+<br>| Average | 62.31% | 58.33% | 56.41% |<br>+---------+--------+--------+--------+</pre><p>but we also have some reports in our report folders.</p><blockquote>Code exclusion from coverage is achieved by using the standard ExcludeCodeFromCoverage attribute. Please <a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.excludefromcodecoverageattribute?view=net-7.0">see documentation</a>.</blockquote><p>Those reports are a bit hard to read, they aren’t targeted for human readers . Instead they target CI tools (like <a href="https://www.jenkins.io/">Jenkins</a> or <a href="https://www.jetbrains.com/teamcity/">TeamCity</a>) and code quality analyzers (<a href="https://www.codacy.com/">Codacy</a>, <a href="https://about.codecov.io/">CodeCov</a>, <a href="https://www.sonarqube.org/">SonarQube</a>).</p><blockquote>A note on integration: Coverlet doesn’t provide out-of-the-box Visual Studio integration, which makes it a bit of a bummer to use if you want to know which parts of the code are not covered. There are, however, various <a href="https://github.com/the-dext/RunCoverletReport">Visual Studio plugins</a> to achieve such functionality.</blockquote><h3>ReportGenerator</h3><blockquote>ReportGenerator converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.</blockquote><p><a href="https://github.com/danielpalme/ReportGenerator">ReportGenerator</a> could be used to aggregate the separate reports created by Coverlet. The created report has some awesome features, I will leave you to discover them on your own in their <a href="https://github.com/danielpalme/ReportGenerator">Github repo</a>, but I will talk about a few.</p><p>ReportGenerator could be used as a <a href="https://www.nuget.org/packages/dotnet-reportgenerator-globaltool">dotnet tool</a> simply by installing it globally</p><pre>dotnet tool install --global dotnet-reportgenerator-globaltool</pre><p>It could also be easily imported as part of the project (i.e. to ensure it exists on the developer machine).</p><pre>&lt;PackageReference Include=&quot;ReportGenerator&quot; Version=&quot;5.1.13&quot; /&gt;</pre><blockquote><strong>Note</strong>: use the most up to date version at the time of reading, not specifically this one.</blockquote><p>In this example I’ll assume you have it as a global tool.</p><p>Again, using your trusty terminal lets run the tool (the ` is powershell newline escape — for bash use backslash \ character instead)</p><pre>reportgenerator `<br>  -reports:./tests/reports/project/*/*.xml `<br>  -targetdir:./tests/coverage/report/ `<br>  -reporttypes:Html_Dark `<br>  -sourcedirs:./src/ `<br>  -historydir:./tests/coverage/history</pre><p>we’ll get something like this printed out on our console screen</p><pre>Arguments<br> -reports:./tests/coverage/projects/*/*.xml<br> -targetdir:./tests/coverage/report/<br> -reporttypes:Html_Dark<br> -sourcedirs:./src/<br> -historydir:./tests/coverage/history<br>Reading historic reports<br>Parsing historic file &#39;./tests/coverage/history\2022-12-18_17-06-46_CoverageHistory.xml&#39;<br>Parsing historic file &#39;./tests/coverage/history\2022-12-18_17-09-57_CoverageHistory.xml&#39;<br>Parsing historic file &#39;./tests/coverage/history\2022-12-19_09-11-27_CoverageHistory.xml&#39;<br>Parsing historic file &#39;./tests/coverage/history\2022-12-19_09-15-22_CoverageHistory.xml&#39;<br>Parsing historic file &#39;./tests/coverage/history\2022-12-19_11-36-25_CoverageHistory.xml&#39;<br>Parsing historic file &#39;./tests/coverage/history\2022-12-19_11-40-53_CoverageHistory.xml&#39;<br>Writing report file &#39;./tests/coverage/report/index.html&#39;<br>Creating history report<br>Report generation took 0.2 seconds</pre><p>Now go to your ./tests/coverage/report/ folder and open the index.html file… that’s nice, ain’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3ybrLCTKLTfTNjhF9GnvQ.png" /><figcaption>Coverage resolution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gjns2d3l4S-dLO27ik6m2A.png" /><figcaption>Per class report</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lY2GDdXjdPE34ynSph9MCQ.png" /><figcaption>Lines of code outline</figcaption></figure><p>Now for the final trickery step. Even though the ReportGenerator tool has MSBuild integration it is a bit flawed. <a href="https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-targets?view=vs-2022">Targets</a> in MSBuild are jobs, ran by MSBuild to do the build process. Every piece of logic running in the context of a build is a target. The thing is, targets are ran in the scope of a csproj that is why when testing. Every csproj is tested separately. So when running ReportGenerator as a MSBuild target in a solution with 3 test projects, it will run 3 times. Which could be problematic:</p><ul><li>If we run the dotnet test with an /m:1 flag that will restrict MSBuild to work on a single process at once, the ReportGenerator tool will not fail. However, it will create 3 reports, meaning 2 history items, each after a single test run. This solution is fine if you have a single test project, it is a bit less practical for larger projects.</li><li>If we are not opting for the limiter flag — we will have fun with multiple processes accessing the same files concurrently, which will certainly fail the whole process.</li></ul><h3>How do we run it only once per solution?!</h3><p>So, now it is time for some magic. The build process in MSBuild is actually creating a meta project that contains all the targets to build/test/etc the project. You could also drop a binlog of the build process</p><pre>dotnet build -bl:binarylogfilename.binlog</pre><p>and use <a href="https://live.msbuildlog.com/">Bin Log Reader (msbuildlog.com)</a> to see this meta-project.</p><p>I’ll take a trick from their book. We can tie into the process by creating a file called after.&lt;solution name&gt;.sln.targets this file will be included in the end of the “virtual csproj” file, meaning it will happen only once. More information on that magic could be found in the <a href="https://learn.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2022#customize-the-solution-build">MSBuild documentation</a>.</p><p>So lets create such a file after.DemoSolution.sln.targets and fill it with some joy:</p><pre>&lt;Project&gt;<br> &lt;Target Name=&quot;GenerateHtmlCoverageReport&quot; AfterTargets=&quot;VSTest&quot;&gt;<br>  &lt;Exec Command=&quot;ReportGenerator -reports:./tests/coverage/projects/*/*.xml -targetdir:./tests/coverage/report/ -reporttypes:Html_Dark -sourcedirs:./src/ -historydir:./tests/coverage/history&quot; /&gt;<br> &lt;/Target&gt;<br>&lt;/Project&gt;</pre><p>We are creating a new Target called GenerateHtmlCoverageReport (think of it as a function) that will run after the <a href="https://github.com/microsoft/vstest/blob/main/src/Microsoft.TestPlatform.Build/Microsoft.TestPlatform.targets#L27">VSTest target</a>. This target will use the <a href="https://learn.microsoft.com/en-us/visualstudio/msbuild/exec-task?view=vs-2022">Exec task</a> to call the ReportGenerator global tool.</p><p>and Voilà! We have an automated process to augment your testing experience, with metrics, historic metrics, trends, hot-points for testing, code coverage drill-down. All cross-platform, all free and very fast.</p><p>Alternatively, if your projects already use <a href="https://nuke.build/">Nuke </a>, <a href="https://cakebuild.net/">Cake</a> or <a href="https://fake.build/">Fake</a>, you’d be happy to know that ReportGenerator has integrations into those build systems.</p><p>Of course not everybody feels at home with such customizations to the build process. It’s ok to keep it simple and just create a small script to run the tests using dotnet test and then run the ReportGenerator tool… it’s probably better this wayany 😄</p><h3>Summary</h3><p>We’ve seen how to wire-up your solution with code coverage tooling (Coverlet) and reporting (ReportGenerator).</p><p>The next step is integrate your Github Actions with those deliveries and push them to <a href="https://about.codecov.io/">CodeCov</a> to get deep analysis of your coverage and code quality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ff1903f7240" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>