<?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 Tomas M on Medium]]></title>
        <description><![CDATA[Stories by Tomas M on Medium]]></description>
        <link>https://medium.com/@tomas.madajevas?source=rss-25429ec7fb3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VmJDx_06y7vToZPr</url>
            <title>Stories by Tomas M on Medium</title>
            <link>https://medium.com/@tomas.madajevas?source=rss-25429ec7fb3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:34:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomas.madajevas/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[Performance of n-gram filtering with PowerShell and C#]]></title>
            <link>https://medium.com/@tomas.madajevas/performance-of-n-gram-filtering-with-powershell-and-c-b46a406dce5f?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46a406dce5f</guid>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[ngrams]]></category>
            <category><![CDATA[powershell]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 04:51:46 GMT</pubDate>
            <atom:updated>2026-10-15T04:51:46.236Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>I had a large log file. It contained 90+K lines; among those, some valuable information might have been found, but because of unfamiliarity, I wished not to read/search it myself. A natural choice was to outsource this job to an LLM. Simply putting this file in the context blew it quickly.</p><p>A quick look at the top and the bottom of the log file showed quite a few lines having the same content, but slightly different log dates, or just a single different word. It looked like some filtering is necessary.</p><p>I know I could have probably just let the agent filter that file itself; however, as an exercise, I decided to implement <a href="https://en.wikipedia.org/wiki/N-gram">n-gram</a> filtering with <a href="https://en.wikipedia.org/wiki/Jaccard_index">Jaccard similarity</a> using PowerShell:</p><pre>Function Get-NGram {<br>    param(<br>        [Parameter(Mandatory = $true)]<br>        [string]$String,<br>        [Parameter()]<br>        [int]$Length = 2<br>    )<br><br>    for ($i = 0; $i -le ($String.Length - $Length); $i++) {<br>        Write-Output $String.Substring($i, $Length).ToLower()<br>    }<br>}<br><br>Function Get-JaccardSimilarity {<br>    param(<br>        [string[]]$Set1,<br>        [string[]]$Set2<br>    )<br><br>    $intersection = $Set1 | Where-Object { $Set2 -contains $_ }<br>    $union = ($Set1 + $Set2) | Select-Object -Unique<br><br>    if ($union.Count -eq 0) { return 0; } # no empty lines in my use case<br><br>    return $intersection.Count / $union.Count<br>}<br><br>Filter Filter-Ngram {<br>    param(<br>        [Parameter(Mandatory,ValueFromPipeline)]<br>        [string]$Line,<br>        [Parameter()]<br>        [int]$Length = 2,<br>        [Parameter()]<br>        [double]$Threshold = 0.5<br>    )<br><br>    begin {<br>        $lastLine = @()<br>    }<br><br>    process {<br>        if (-not $Line) {<br>            return;<br>        }<br><br>        if ($lastLine.Length -eq 0) {<br>            Write-Output $_<br>            $lastLine = Get-NGram -String $Line -Length $Length | Select-Object -Unique<br>        } else {<br>            $thisLine = Get-NGram -String $Line -Length $Length | Select-Object -Unique<br><br>            $similarity = Get-JaccardSimilarity -Set1 $lastLine -Set2 $thisLine<br>            if ($similarity -lt $Threshold) {<br>                Write-Output $_<br>            }<br><br>            $lastLine = $thisLine<br>        }<br>    }<br>}</pre><p>And it was really slow. It took me a while to get the similarity parameters in order, fix a bug or two, and get a result that an LLM can inspect for me.</p><h3>C# port</h3><p>PowerShell modules can be implemented using C#. I got interested if it could crunch faster through all those lines. There would still be a pipeline to receive log lines from, a pipeline to output lines that are not similar enough, and to store in another log file. So this module is just one (presumably the largest) part of the process.</p><pre>[Cmdlet(&quot;Filter&quot;, &quot;Ngram&quot;)]<br>public class FilterNGramSubstrings : Cmdlet<br>{<br>    [ValidateNotNullOrEmpty]<br>    [Parameter(ValueFromPipeline = true)]<br>    public string Line { get; set; } = string.Empty;<br><br>    [ValidateRange(1, 32)]<br>    [Parameter]<br>    public ushort Length { get; set; } = 2;<br><br>    [ValidateRange(0.1, 1)]<br>    [Parameter]<br>    public double Threshold { get; set; } = 0.5;<br><br>    private HashSet&lt;string&gt; lastLineNgram = [];<br><br>    protected override void ProcessRecord()<br>    {<br>        if (string.IsNullOrWhiteSpace(Line))<br>        {<br>            return;<br>        }<br><br>        if (Line.Length &lt; Length)<br>        {<br>            WriteObject(Line);<br>        }<br><br>        var currentLineNgram = new HashSet&lt;string&gt;(Line.Length - Length + 1);<br>        for (var i = 0; i &lt;= Line.Length - Length; i++)<br>        {<br>            currentLineNgram.Add(Line.Substring(i, Length).ToLower());<br>        }<br><br>        if (lastLineNgram.Count == 0)<br>        {<br>            WriteObject(Line);<br>            lastLineNgram = currentLineNgram;<br>            return;<br>        }<br><br>        var intersection = currentLineNgram.Intersect(lastLineNgram).Count();<br>        var union = currentLineNgram.Union(lastLineNgram).Count();<br>        var jaacardSimilarity = (double)intersection / union;<br>        if (jaacardSimilarity &lt; Threshold)<br>        {<br>            WriteObject(Line);<br>        }<br><br>        lastLineNgram = currentLineNgram;<br>    }<br>}</pre><p>As the section title states, this is mostly a port. Of course, here everything is happening in a single function, and HashSet&lt;string&gt; is utilized to get rid of duplicates. Nothing that could be tagged as a performance optimization, and yet it works 120x faster that PowerShell&#39;s implementation. (benchmarkdotnet finds 187x speed increase and and 112x less memory allocated. Such drastic result must come from a randomized dataset (not testing against multi thousand lines file) - changing the seed changes results outside of the error range.) This alone can be considered a good enough performance optimization (what previously required more than 7 minutes, now completes in just bellow 4 seconds). But I feel there is more performance optimizations available, so, for both fun and learning experience I explored a bit more. I will keep this one as a baseline while working through other optimizations so those would not be dwarfed by this 120x improvement.</p><h3>Using Span&lt;char&gt;</h3><p>An easy first candidate is to use spans instead of allocating strings. Unfortunately, comparing IReadOnlySpan&lt;char&gt; to another one is not happening out of the box, and a custom comparer, which is being called multiple times for every single n-gram just makes things worse. But it is not mandatory to compare strings(char arrays) - hashes(of n-grams) could be calculated upfront, and simple integer comparison should be blazingly fast. And, indeed, performance is increased, and memory allocations reduced (strings are well optimized; the improvement is not too big). And yet, hashing introduces another issue: collisions. I have calculated the collision rate of 2, 3 and 4 length n-grams (basic latin minus control chars), and it exceeds 50% easily (have not gone into details as it is already unreasonably high even for an implementation that needs to be mostly correct). The collision issue can be dealt with using XxHash32.HashToUInt32 from System.IO.Hashing. It had not a single collision with previously defined sets.</p><pre>public class FilterNGramSpansAndHashes : Cmdlet<br>{<br>    [ValidateNotNullOrEmpty]<br>    [Parameter(ValueFromPipeline = true)]<br>    public string Line { get; set; } = string.Empty;<br><br>    private const ushort defaultLength = 2;<br>    [ValidateRange(1, 32)]<br>    [Parameter]<br>    public ushort Length<br>    {<br>        get =&gt; field;<br>        set<br>        {<br>            field = value;<br>            maxByteCount = (ushort)Encoding.UTF8.GetMaxByteCount(value);<br>        }<br>    } = defaultLength;<br>    private ushort maxByteCount = (ushort)Encoding.UTF8.GetMaxByteCount(defaultLength); // 1️⃣<br><br>    [ValidateRange(0.1, 1)]<br>    [Parameter]<br>    public double Threshold { get; set; } = 0.5;<br><br>    private HashSet&lt;uint&gt; lastLineHashes = [];<br><br>    protected override void ProcessRecord()<br>    {<br>        if (string.IsNullOrWhiteSpace(Line))<br>        {<br>            return;<br>        }<br><br>        if (Line.Length &lt; Length)<br>        {<br>            WriteObject(Line);<br>        }<br><br>        var currentLineHashes = new HashSet&lt;uint&gt;(Line.Length - Length + 1);<br>        for (var i = 0; i &lt;= Line.Length - Length; i++)<br>        {<br>            Span&lt;char&gt; lower = stackalloc char[Length];<br>            Line.AsSpan(i, Length).ToLower(lower, culture: null); // 2️⃣<br>            Span&lt;byte&gt; target = stackalloc byte[maxByteCount];<br>            Encoding.UTF8.TryGetBytes(lower, target, out var bytesWritten); // 3️⃣<br>            currentLineHashes.Add(XxHash32.HashToUInt32(target.Slice(0, bytesWritten))); // 4️⃣<br>        }<br><br>        if (lastLineHashes.Count == 0)<br>        {<br>            WriteObject(Line);<br>            lastLineHashes = currentLineHashes;<br>            return;<br>        }<br><br>        var intersection = currentLineHashes.Intersect(lastLineHashes).Count();<br>        var union = currentLineHashes.Union(lastLineHashes).Count();<br>        var jaacardSimilarity = (double)intersection / union;<br>        if (jaacardSimilarity &lt; Threshold)<br>        {<br>            WriteObject(Line);<br>        }<br><br>        lastLineHashes = currentLineHashes;<br>    }<br>}</pre><p>Since this implementation does many things in memory, it is necessary to known maximum number of bytes an n-gram will take in bytes (1️⃣). During processing, the code iterates over n-grams, lowercases them (2️⃣, the algorithm is case-insensitive), converts them to bytes (3️⃣), and gets their hash code (4️⃣). Even if it looks like more steps to take, spans and hashes version is still at least 5% faster (results further on).</p><h3>Using value enumerators</h3><p>Another applied performance improvement is the usage of value enumerators from ZLinq NuGet package. Not going to show any code here: it is just a matter of calling .AsValueEnumerable() before union and intersection. We get another ~4% percents in execution mean time and more than a third of allocations removed.</p><h3>Pooling HashSet&lt;uint&gt;</h3><p>The last successful optimization that I came up with was pooling HashSet&lt;uint&gt;. One is being allocated for every line the commandlet processes, so with tens of thousands of lines we get the same number of allocations that could be avoided. To make pooling easier, I&#39;ve introduced an extension method:</p><pre>internal static class HashSetPool&lt;T&gt;<br>{<br>    public static ObjectPool&lt;HashSet&lt;T&gt;&gt; Pool = new DefaultObjectPool&lt;HashSet&lt;T&gt;&gt;(new HashSetPoolPolicy&lt;T&gt;());<br><br>    internal class HashSetPoolPolicy&lt;TItem&gt; : PooledObjectPolicy&lt;HashSet&lt;TItem&gt;&gt;<br>    {<br>        public override HashSet&lt;TItem&gt; Create() =&gt; new HashSet&lt;TItem&gt;();<br><br>        public override bool Return(HashSet&lt;TItem&gt; obj)<br>        {<br>            obj.Clear();<br>            return true;<br>        }<br>    }<br>}<br><br>internal static class HashSetExtensions<br>{<br>    extension&lt;T&gt;(HashSet&lt;T&gt;)<br>    {<br>        public static ObjectPool&lt;HashSet&lt;T&gt;&gt; Pool =&gt; HashSetPool&lt;T&gt;.Pool;<br>    }<br>}</pre><p>Instead of constructing a new HashSet&lt;uint&gt;, it is retrieved from this pool:</p><pre>    protected override void ProcessRecord()<br>    {<br>        // ... checks as before<br><br>        var currentLineHashes = HashSet&lt;uint&gt;.Pool.Get();<br><br>        // ... processing as before<br><br>        HashSet&lt;uint&gt;.Pool.Return(lastLineHashes);<br>        lastLineHashes = currentLineHashes;<br>    }</pre><p>Pooling was least impactful on processing time (0–2% depending on n-gram length), yet allocations were reduced significantly.</p><h3>Results</h3><p>Benchmarkdotnet results (Length is length of n-gram):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*7QHZ5ZasExDbdLVlf2bOOQ.png" /></figure><p>Testing against an actual file shows a 128x improvement in speed. It was 120x with the substrings version.</p><p>So was this optimization worth it? It was, as always, fun to make things go faster and learn something along the way. Other than that, a simple implementation in C# would have done the trick for me. Maybe if a file with tens of millions of lines comes along, those +8x will prove themselves valuable :).</p><h3>Why PowerShell is so slow</h3><p>The last remaining question I had is why there is such a dramatic difference in performance. I hoped that the launched profiler would just show me where the overhead was. All it did is show that the majority of the time is spent in system.private.corelib.dll. Not really helpful :). With a lack of a better profiling tool, I&#39;ve tried modifying the script to come up with a hypothesis. So, my assumption for this speed difference is the fact that PowerShell is interpreted, not compiled like C# is and a heavy usage of the pipeline. Just replacing Get-NGram with a for loop (and keeping PS native collection (@())) removes a quarter of the processing time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46a406dce5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency injection in NUnit]]></title>
            <link>https://medium.com/@tomas.madajevas/dependency-injection-in-nunit-9f969c737d3f?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f969c737d3f</guid>
            <category><![CDATA[nunit]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 17:43:16 GMT</pubDate>
            <atom:updated>2026-07-08T17:43:16.384Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are using NUnit to run your integration tests, you might have wished to have dependency injection there. With <a href="https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-10.0&amp;pivots=nunit">TestHost</a> this is partially available, but it is more of a service locator than dependency injection. If those integration tests runs against multiple services/processes/deployments, even TestHost is not really an option.</p><p>Leaving all of the services initialization aside, lets see how dependency injection could be enabled on NUnit test classes starting with dependencies setup and then moving on to injection into classes.</p><h3>Dependency registration</h3><p>In many cases <a href="https://docs.nunit.org/articles/nunit/writing-tests/attributes/setupfixture.html">SetUpFixtureAttribute</a> is a good entry point to make preparations for tests in a namespace (or even the whole tests assembly). However, its one time setup is being executed too late, after tests discovery where <a href="https://docs.nunit.org/articles/nunit/writing-tests/attributes/testfixturesource.html">TestFixtureSourceAttribute</a> (which will be used in next section) is being executed (to discover all tests). To overcome this, we can fallback to <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.moduleinitializerattribute?view=net-10.0">ModuleInitializerAttribute</a>:</p><pre>[SetUpFixture]<br>public class Initializer<br>{<br>    internal static ServiceProvider provider;<br><br>    [ModuleInitializer]<br>    [OneTimeSetUp]<br>    public static void RegisterDependencies()<br>    {<br>        if (provider != null) // 1️⃣<br>        {<br>            return;<br>        }<br><br>        // 2️⃣<br>        var services = new ServiceCollection();<br>        services.AddHttpClient&lt;MyServiceHttpClient&gt;(client =&gt; client.BaseAddress = new Uri(&quot;http://localhost:5000&quot;));<br>        provider = services.BuildServiceProvider();<br>    }<br><br>    [OneTimeTearDown]<br>    public void TearDown()<br>    {<br>        provider.Dispose(); // 3️⃣<br>    }<br>}</pre><p>Here, initializer is still decorated with SetUpFixtureAttribute to enable cleanup 3️⃣. NUnit analyzer complains about disposable provider field, so dependency registration method must be decorated with OneTimeSetUpAttribute and double execution prevented 1️⃣. Dependency registration is as mundane as it can be.</p><h3>Dependency injection into test class</h3><p>With dependencies registered and provider exposed internally we can move on to injection into tests. As I have already mentioned, this can be done with TestFixtureSourceAttribute, or, more precisely, a derived class of it:</p><pre>[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]<br>internal sealed class InjectingTestFixtureSourceAttribute&lt;TTestClass&gt; : TestFixtureSourceAttribute // 1️⃣<br>{<br>    public InjectingTestFixtureSourceAttribute()<br>        : base(typeof(InjectingTestFixtureSourceAttribute&lt;TTestClass&gt;), nameof(Parameters)) // 2️⃣<br>    {}<br><br>    public static IEnumerable&lt;TestFixtureData&gt; Parameters<br>    {<br>        get<br>        {<br>            // 3️⃣<br>            var constructor = typeof(TTestClass).GetConstructors().Single();<br>            var parameters = constructor.GetParameters()<br>                .Select(p =&gt; Initializer.provider.GetRequiredService(p.ParameterType))<br>                .ToArray();<br><br>            yield return new TestFixtureData(parameters)<br>            {<br>                TestName = typeof(TTestClass).Name // 4️⃣<br>            };<br>        }<br>    }<br>}</pre><p>To figure out test class’s constructor arguments, attribute must get a hold of class type, which is easy to do with generic parameter (1️⃣). Then, it piggy backs on one of the base class constructors by providing itself as a source class and it’s property name as a source name where to take arguments from (2️⃣). All what is left is to resolve constructor parameters from service provider (3️⃣) and return them as single return value. Test name can be overridden (4️⃣) to hide injected services from test class name.</p><h3>Usage</h3><p>To utilize all the above, test class has to be decorated with attribute just created, and necessary registered services added as constructor parameters:</p><pre>[InjectingTestFixtureSource&lt;Tests1&gt;]<br>internal class Tests1(MyServiceHttpClient client)<br>{<br>    [Test]<br>    public void CheckDependency()<br>    {<br>        Assert.That(client, Is.Not.Null);<br>        <br>        // calls to injected client and its results assertions<br>    }<br>}</pre><h3>Conclusion</h3><p>Not that long ago I was looking for solution like this with no success. At the time i did not understand that it may be enabled with so little effort. Solution is not battle tested, but hopefully it will provide some answers to others looking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f969c737d3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Source generated dependent tests]]></title>
            <link>https://medium.com/@tomas.madajevas/source-generated-dependent-tests-d829e5407fb3?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d829e5407fb3</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[source-generator]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 09:31:14 GMT</pubDate>
            <atom:updated>2026-02-08T09:31:14.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Yp4u6KDL7fFtmczgnAv-HQ.png" /><figcaption>Sample test with dependencies managed</figcaption></figure><p>There is an opinion that tests must be independent of each other; however, when it comes to integration tests, I often find the best way to structure those as if they would be telling a user story. And that involves multiple tests, each telling and verifying its own bit of a larger flow, laying grounds for the next step to build on (dependencies in between them). For example, testing server side rendered form in this approach could look like so:</p><pre>class SubmitForWithFailureTests<br>{<br>    private HttpClient client;<br>    private string getContent;<br>    private string errorContent;<br><br>    [SetUp]<br>    public void SetUpApplication<br>    {<br>        WebApplicationFactory&lt;Program&gt; factory = // ...<br>        client = factory.CreateClient();<br>    }<br><br>    [Test, Order(0)]<br>    public async Task NavigateToInputForm_MakeSureItRendered()<br>    {<br>        var response = await client.GetAsync(&quot;/the-form&quot;);<br>        response.EnsureSuccessStatusCode();<br>        getContent = await response.Content.ReadAsStringAsync();<br><br>        // assert snapshot or parse html...<br>    }<br><br>    [Test, Order(1)]<br>    public async Task PostInvalidValue_ObserveErrorDisplayed()<br>    {<br>        var xsrf = // extract from getContent<br>        var form = new FormUrlEncodedContent(/*xsrf + invalid payload*/);<br>        var response = await client.PostAsync(&quot;/the-form&quot;, form);<br>        errorContent = await response.Content.ReadAsStringAsync();<br><br>        // assert error...<br>    }<br><br>    [Test, Order(2)]<br>    public async Task PostCorrectValue_ObserveSuccessMessage()<br>    {<br>        // ...<br>    }<br>}</pre><blockquote><em>An attribute can be created to prevent tests from running if one in the chain fails. I am source generating it in my </em><a href="https://github.com/Madajevas/VariousTests/blob/master/TestsGenerator/MultistepAttribute.cs"><em>POC</em></a><em>.</em></blockquote><p>I find this quite nice: code (and operations) duplication can be kept to a minimum and reading just test names shows probable user flow (actions taken and outcomes). But, if you are like me, small, obscure (mostly copying) errors may creep in from time to time: using an incorrect instance field for the test. In the example above, I have staged getContent and errorContent fields to illustrate this. When copying XSRF extraction code to subsequent test it is easy to forget to update where that token must be extracted from! This prompted me to try to solve this problem using a source generator.</p><h3>Desired outcome</h3><p>Continuing with the previous example, I would like to enable myself to write tests like this:</p><pre>class SubmitForWithFailureTests<br>{<br>    private HttpClient client;<br><br>    // setup as before<br><br>    [Test]<br>    public async Task&lt;string&gt; NavigateToInputForm_MakeSureItRendered()<br>    {<br>        // extraction, assertion as before<br><br>        return getContent; // 1️⃣<br>    }<br><br>    [Test]<br>    public async Task&lt;string&gt; PostInvalidValue_ObserveErrorDisplayed<br>      (string getContent) // 2️⃣<br>    {<br>        // extraction, assertion as before<br><br>        return errorContent; // 1️⃣<br>    }<br><br>    [Test]<br>    public async Task PostCorrectValue_ObserveSuccessMessage<br>      (string errorContent) // 2️⃣<br>    {<br>        // ...<br>    }<br>}</pre><p>No instance fields to mix up, test methods return state(1️⃣), and methods acting on top of that state inject it (2️⃣).</p><h3>Source generator</h3><p>NUnit (my framework of choice) does not allow returning from test methods (unless expected value is specified which does not work for this), and even if it did, how not to lose track of that value and use it where necessary? It implies that for this to work, NUnit’s test attributes cannot be used directly; methods must be wrapped. So, a partial class with wrapper methods needs to get source generated:</p><pre>partial class SubmitForWithFailureTests<br>{<br>    private string returnedFromNavigateToInputForm_MakeSureItRendered; // 1️⃣<br>    [Test, Order(0)]<br>    public async Task NavigateToInputForm_MakeSureItRendered_Generated()<br>    {<br>        returnedFromNavigateToInputForm_MakeSureItRendered =<br>            await NavigateToInputForm_MakeSureItRendered(); // 2️⃣<br>    }<br><br>    private string returnedFromPostInvalidValue_ObserveErrorDisplayed; // 1️⃣<br>    [Test, Order(1)]<br>    public async Task PostInvalidValue_ObserveErrorDisplayed_Generated()<br>    {<br>        returnedFromPostInvalidValue_ObserveErrorDisplayed =        // 2️⃣<br>            await PostInvalidValue_ObserveErrorDisplayed<br>              (returnedFromNavigateToInputForm_MakeSureItRendered); // 3️⃣<br>    }<br>}</pre><p>Of course, implementation cannot get by without any medium to store test results, here class fields with test names are chosen (1️⃣). They are generated and out of sight — no mixing them up. Value returned from test (where real test logic happens) is assigned to the generated field (2️⃣) and later injected (3️⃣) to next test that requires it. Looks simple enough. Now onto the generator.</p><blockquote><em>This is my personal pet project with an incomplete, opinionated, and not optimized implementation, where I was both validating the idea of tests state management and learning source generation. Source generators in general has enough coverage online, so there is no point to repeat theory (marker attributes, etc) or show generic parts of code. Personally, I liked </em><a href="https://andrewlock.net/creating-a-source-generator-part-1-creating-an-incremental-source-generator/"><em>Andrew Lock’s series</em></a><em> on the subject.</em></blockquote><p><a href="https://github.com/Madajevas/VariousTests/blob/master/SourceGeneration/DependantTests/TestsGenerator/MultistepTestsSourceGenerator.cs">Tests source generator</a> has three distinct parts:</p><ul><li>Extract methods that participate in the overall flow;</li><li>Build dependency tree;</li><li>Generate a partial class as above.</li></ul><p>There is not much to say about test methods extraction: just find all methods in the class decorated with the marker attribute. The only thing worth mentioning is that, due to design choice, tests must be in order of declaration (hence extracting from ClassDeclarationSyntax). Chosen this approach because it is more natural and easier to just expect methods to be in order instead of figuring out what methods must execute before another, with results wired correctly (some special kind of hoisting :)).</p><p>Building a dependency tree serves a dual purpose. First, it assembles <em>method-*parameter-dependent method</em> map and, second, validates the input class. Here is how it works:</p><pre>var availableForInjection = new Dictionary&lt;ITypeSymbol, IMethodSymbol&gt;(new AsyncOrNotSymbolEqualityComparer());<br>var dependencyGraph =<br>    new OrderedDictionary&lt;IMethodSymbol, OrderedDictionary&lt;IParameterSymbol, IMethodSymbol&gt;&gt;(SymbolEqualityComparer.Default);<br>foreach (var test in tests) // tests extracted before<br>{<br>    dependencyGraph[test] = new OrderedDictionary&lt;IParameterSymbol, IMethodSymbol&gt;(SymbolEqualityComparer.Default);<br>    foreach (var parameter in test.Parameters)<br>    {<br>        // 1️⃣<br>        if (!availableForInjection.TryGetValue(parameter.Type, out var dependency))<br>        {<br>            // report diagnostic<br>            continue;<br>        }<br>        availableForInjection.Remove(parameter.Type);   // 2️⃣<br><br>        dependencyGraph[test].Add(parameter, dependency);<br>    }<br><br>    <br>    if (!test.ReturnsVoid)<br>    {<br>        // 3️⃣<br>        if (availableForInjection.ContainsKey(test.ReturnType))<br>        {<br>            // report diagnostic<br>            continue;<br>        }<br><br>        availableForInjection.Add(test.ReturnType, test);<br>    }<br>}</pre><p>It goes through all tests and their parameters, checks whether parameters needed for the test are already known (1️⃣) (test seen before must have produced it), if not — error is reported, otherwise — parameter is consumed (2️⃣) and a map record is added connecting the parameter to the test. (Again, this is just my design decision to allow the returned value be used once.) Lastly, if the test being processed returns something and that something is causing no ambiguity (3️⃣), it is included in the lookup for the following iterations.</p><p>Partial class is only generated when no errors are found, allowing the user to focus on actionable things and not getting bogged down with compilation errors from source generated file. Other than that, there is nothing extraordinary in this <a href="https://github.com/Madajevas/VariousTests/blob/d4c4d3d/SourceGeneration/DependantTests/TestsGenerator/MultistepTestsSourceGenerator.cs#L125-L204">part</a>.</p><h3>Conclusion</h3><p>So, what can be considered boilerplate aside, there is not that much logic to implement to get tests dependencies managed. At least with the decisions and number of features I’ve chosen to pursue. And it is humbling how enabling source generators can be. Repetitive, error prone code can be deterministically generated, which saves on keystrokes and reduces those small, annoying errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d829e5407fb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IEnumerable to manage disposable resources for developers with chest hair]]></title>
            <link>https://medium.com/@tomas.madajevas/ienumerable-to-manage-disposable-resources-for-developers-with-chest-hair-f33987e0778a?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f33987e0778a</guid>
            <category><![CDATA[idisposable]]></category>
            <category><![CDATA[ienumerable]]></category>
            <category><![CDATA[resource-management]]></category>
            <category><![CDATA[pattern-generator]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 12:17:03 GMT</pubDate>
            <atom:updated>2025-12-07T12:17:03.703Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are a lib author, internal or not, how do you force consumers of your IDisposable resources not to forget to call dispose? Force an analyzer? Implement finalizer with <a href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/dispose-pattern">dispose pattern</a>? Or maybe a third, more &quot;colorful&quot; version to do just that exists?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*hyIXKFOa-uKLr9KItIYRug.png" /></figure><h3>Problem</h3><p>In particular, I am appealing to the code like this:</p><pre>IEnumerable&lt;IDisposable&gt; resources = ...; // get it from somewhere<br>foreach (var resource in resources)<br>{<br>    using var _ = resource;<br>    ...; // do something with resource<br>}</pre><blockquote><em>Let’s assume that resources are produced one by one, as with the generator pattern.</em></blockquote><p>In addition to the need not to forget to dispose of resources, another question may be raised: what if consuming code does not need to know that disposable resources are even being used? An example of that could be creating a new service scope, resolving DbContext from it, and, with filters, projections, or without, returning an IEnumerable of objects. We would either need to inline such code (may violate single responsibility, not test friendly), cache results in a list (not ideal for a large number of items), or return some wrapper which needs to be disposed of.</p><h3>Solution</h3><p>My “colorful” proposal is to hide disposable resources behind an IEnumearble generator:</p><pre>private IEnumerable&lt;MyResource&gt; GetResources()<br>{<br>    using (var resource1 = new MyResource())<br>    {<br>        // resource needs not to be explicitly IDisposable<br>        yield return resource1;<br>    }<br>    <br>    using (var resource2 = new MyResource())<br>    {<br>        yield return resource2;<br>    }<br>}</pre><p>Or an example with IServiceScopeFactory:</p><pre>private IEnumerable&lt;MyResource&gt; GetResources()<br>{<br>    using var scope = serviceScopeFactory.CreateScope();<br>    var dbContext = scope.ServiceProvider.GetService&lt;DbContext&gt;();<br>    var resources = dbContext.AsNoTracking().Resources.Where(r =&gt; !r.Deleted);<br>    foreach (var resource in resources)<br>    {<br>        yield return resource;<br>    }<br>}</pre><p>Any consuming code stays oblivious of, now internal, disposable resources, logic may be split into classes with separate concerns, reasoned and covered with tests more easily.</p><p>However, it is not so obvious how this works, and it comes to understanding lowering to understand the examples above. Let’s focus on the first one without DbContext and the loop. GetResources method will be lowered to a more primitive language constructs. Since some state is necessary here, a class will be generated to store it. Also, it will implement IEnumerable&lt;MyResource&gt; to be compatible with what consuming code expects, as well as to enable switching between states and performing resource creation and disposal. I will not bother you with disassembled code, just with a simplified version of what would need to be created if the compiler did not do that for us:</p><pre>class MyResources : IEnumerable&lt;MyResource&gt;, IEnumerator&lt;MyResource&gt;<br>{<br>    // 1️⃣<br>    private const short INITIAL = 0;<br>    private const short SECOND = 1;<br>    private const short CLEAN  = 2;<br><br>    private short state; 2️⃣<br><br>    public MyResources() : this(-1) { } // 3️⃣<br><br>    private MyResources(short state)<br>    {<br>        this.state = state;<br>    }<br><br>    public MyResource Current { get; private set; }<br><br>    public IEnumerator&lt;MyResource&gt; GetEnumerator()<br>    {<br>        return new MyResources(INITIAL); // 4️⃣<br>    }<br><br>    public bool MoveNext()<br>    {<br>        switch (state)<br>        {<br>            case INITIAL:<br>                Current = new MyResource(); // 5️⃣<br>                state = SECOND;<br>                return true;<br>            case SECOND:<br>                Current.Dispose();  // 6️⃣<br>                Current = new MyResource();<br>                state = CLEAN;<br>                return true;<br>            case CLEAN:<br>                Current.Dispose();  // 7️⃣<br>                return false;<br>            default:<br>                return false;<br>        }<br>    }<br><br>    public void Dispose()<br>    {<br>        Current?.Dispose(); 8️⃣<br>    }<br><br>    object IEnumerator.Current =&gt; Current;<br><br>    public void Reset() =&gt; throw new NotSupportedException();<br><br>    IEnumerator IEnumerable.GetEnumerator()<br>    {<br>        return GetEnumerator();<br>    }<br>}</pre><p>I have named(1️⃣) states here so it would be easier to understand. The current state is stored in class field(2️⃣) and initially is set to an invalid value(3️⃣). It’s GetEnumerator method must be called (foreach does this for us) to get it into initial, correct state(4️⃣). Then, iterating over a collection will create the first disposable resource(5️⃣), moving to another item will dispose of the resource created before, and provide another for consumption. When items exceed, only the cleanup of the last created resource is left(7️⃣). Class must still implement IDisposable, so in case of premature termination (consuming code throws), the created resource would get cleared(8️⃣).</p><p>On the consuming side, foreach will get lowered to a while loop over the enumerator:</p><pre>var enumerable = new MyResources();<br>using var enumerator = enumerable.GetEnumerator();<br>while (enumerator.MoveNext())<br>{<br>    var resource = enumerator.Current;<br>    ...; // do something with it<br>}</pre><p>Lets illustrate this flow with a diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*-II1_spGZahdLl2W6pzyAA.png" /></figure><p>In the diagram, it is clearly visible when resources are created and destroyed. If loops were used, as with the database example, implementation and flow would be different, only single disposal would be needed (of service scope). Lucky for us, the compiler does the heavy lifting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f33987e0778a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Server data ingestion performance tips]]></title>
            <link>https://medium.com/@tomas.madajevas/sql-server-data-injection-performance-tips-6a604d934ff2?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a604d934ff2</guid>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[batch-processing]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 14:08:53 GMT</pubDate>
            <atom:updated>2025-11-02T06:59:53.454Z</atom:updated>
            <content:encoded><![CDATA[<p>Here, I will provide a few techniques I have utilized while working on my learning/pet, project where a large amount of data needed to be ingested into SQL Server’s graph tables.</p><h3>SqlBulkCopy</h3><p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlbulkcopy?view=netframework-4.8.1&amp;viewFallbackFrom=net-9.0">SqlBulkCopy</a> offers orders of magnitude better performance compared to executing insert statements (especially in a loop with many round-trips). To illustrate this with code here is an example with a loop:</p><pre>foreach (var movie in movies)<br>{<br>    const string insertSql = &quot;&quot;&quot;<br>        INSERT INTO movie (ID, name, year, length)<br>        OUTPUT Inserted.$node_id<br>        VALUES (@Id, @Name, @Year, @Length)<br>        &quot;&quot;&quot;;<br>    var nodeId = await connection.ExecuteScalarAsync&lt;string&gt;(insertSql, movie, transaction);<br>}</pre><p>Performance optimized version is quite a bit more verbose:</p><pre>var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction)<br>{<br>    DestinationTableName = &quot;movie&quot;,<br>    BatchSize = 200,<br>};<br>// 1️⃣<br>sqlBulkCopy.ColumnMappings.Add(nameof(Movie.Id), &quot;ID&quot;);<br>sqlBulkCopy.ColumnMappings.Add(nameof(Movie.Name), &quot;name&quot;);<br>sqlBulkCopy.ColumnMappings.Add(nameof(Movie.Year), &quot;year&quot;);<br>sqlBulkCopy.ColumnMappings.Add(nameof(Movie.Length), &quot;length&quot;);<br>// 2️⃣<br>var table = new DataTable();<br>table.Columns.Add(nameof(Movie.Id), typeof(int));<br>table.Columns.Add(nameof(Movie.Name), typeof(string));<br>table.Columns.Add(nameof(Movie.Year), typeof(uint));<br>table.Columns.Add(nameof(Movie.Length), typeof(uint));<br><br>foreach (var movie in movies)<br>{<br>    var row = table.NewRow();<br>    row[nameof(Movie.Id)] = movie.Id;<br>    row[nameof(Movie.Name)] = movie.Name;<br>    row[nameof(Movie.Year)] = movie.Year is uint year ? year : DBNull.Value;<br>    row[nameof(Movie.Length)] = movie.Length is uint len ? len : DBNull.Value;<br>    table.Rows.Add(row);    // 3️⃣<br>}<br><br>await sqlBulkCopy.WriteToServerAsync(table);</pre><p>Now, instead of reaching into the database with each iteration, DataTable(2️⃣) is used to first add data to it(3️⃣) and later save it in one go. If database field names do not match model property names, they may be mapped as shown at 1️⃣.</p><p>In this particular case, usage of SqlBulkCopy improved performance ~6x.</p><h3>Special case when return values are important</h3><p>A keen eye might have noticed that the first example was retrieving the $node_id of the inserted node. It is used in the following query (not shown here) to connect a movie to a genre using an edge table. With bulk copy, we cannot have output, but there is a workaround - a temporary table followed by an <em>INSERT INTO SELECT</em> statement with $node_id(1️⃣) output:</p><pre>await connection.ExecuteAsync(&quot;&quot;&quot;<br>    CREATE TABLE #movie<br>    (<br>        [ID] int not NULL,<br>        [name] varchar(1000) NULL,<br>        [year] smallint NULL,<br>        [length] int NULL<br>    ); <br>    &quot;&quot;&quot;, transaction: transaction);<br>var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction)<br>{<br>    DestinationTableName = &quot;#movie&quot;,<br>    BatchSize = 200,<br>};<br>// ... prepare and save data as above<br>const string outputSql = &quot;&quot;&quot;<br>    INSERT INTO movie (ID, name, year, length)<br>    OUTPUT Inserted.$node_id    -- 1️⃣<br>    SELECT ID, name, year, length FROM #movie -- 2️⃣<br>    &quot;&quot;&quot;;<br>var nodeIds = await connection.QueryAsync&lt;string&gt;(outputSql, transaction: transaction);</pre><p>So, with only two changes (creating and inserting into a temp table and <em>INSERT INTO SELECT</em>), the necessary output can be restored. The cost of inserting into a temporary table first is almost negligible.</p><h3>DbBatch</h3><p>SqlBulkCopy cannot be used when $node_ids to connect nodes with the edge table are not known. An advertised approach is to use INSERT INTO with a subquery:</p><pre>const string insertActorSql = &quot;&quot;&quot;<br>    INSERT INTO starred_in<br>    SELECT <br>        (SELECT $node_id FROM person WHERE ID = @PersonId),<br>        (SELECT $node_id FROM movie WHERE ID = @MovieId),<br>        @Character<br>    WHERE EXISTS (SELECT 1 FROM person WHERE ID = @PersonId)<br>      AND EXISTS (SELECT 1 FROM movie WHERE ID = @MovieId)<br>    &quot;&quot;&quot;;<br>foreach (var job in jobs)<br>{<br>    await connection.ExecuteAsync(insertActorSql, job, transaction);<br>}</pre><p>Needless to say, this creates a lot of round-trips and for tens of millions of rows to be inserted becomes more than measurable.</p><p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbbatch?view=net-9.0">DbBatch</a> allows executing arbitrary commands in a single round-trip:</p><pre>using var batch = connection.CreateBatch();<br>batch.Transaction = transaction;<br><br>foreach (var job in jobs)<br>{<br>    var command = batch.CreateBatchCommand();<br>    command.CommandText = insertActorSql;       // sql same as above<br><br>    var personIdParameter = command.CreateParameter();<br>    personIdParameter.ParameterName = &quot;@PersonId&quot;;<br>    personIdParameter.Value = job.PersonId;<br>    command.Parameters.Add(personIdParameter);<br><br>    var movieIdParameter = command.CreateParameter();<br>    movieIdParameter.ParameterName = &quot;@MovieId&quot;;<br>    movieIdParameter.Value = job.MovieId;<br>    command.Parameters.Add(movieIdParameter);<br><br>    var characterParameter = command.CreateParameter();<br>    characterParameter.ParameterName = &quot;@Character&quot;;<br>    characterParameter.Value = job.Character ?? (object)DBNull.Value;<br>    command.Parameters.Add(characterParameter);<br>}<br><br>await batch.ExecuteNonQueryAsync();</pre><p>Again, code is a lot more verbose, but performance is improved 4–5 fold.</p><h3>Conclusion</h3><p>Just a few tips, but both were very welcome time savers for me. Maybe they will help somebody else, too. My often-changing source code can be found <a href="https://github.com/Madajevas/graph_database_tryout/blob/main/GraphDatabaseTryout/GraphDatabaseTryout/Data/Repositories/MoviesRepository.cs">here</a>, along with other attempts to improve performance, like loading data in parallel and using DataFlow blocks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a604d934ff2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aggregating debounce decorator]]></title>
            <link>https://medium.com/@tomas.madajevas/aggregating-debounce-decorator-b0b8774cc220?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b8774cc220</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[debounce]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 13:12:12 GMT</pubDate>
            <atom:updated>2025-08-24T13:12:12.760Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*HvOrJsAs_xEr0WtwUiCkxg.png" /></figure><p><a href="https://developer.mozilla.org/en-US/docs/Glossary/Debounce">Debounce</a> is a quite well-known concept, and, as I imagine, often utilized as a <a href="https://www.typescriptlang.org/docs/handbook/decorators.html">decorator</a>. Implementations of this concept ignore all invocations over the time period but the latest. This way, arguments of previous invocations get lost. But what if arguments matter while invocation is considered to be expensive? Would it be difficult to aggregate those arguments and invoke the debounced function only once with all of them?</p><h3>Aggregating debounce</h3><p>In the following code snippet, aside from ordinary debounce functionality, there is a collection(1️⃣) to store arguments. Set is used here to eliminate duplicates, and, while generic arguments suggest generic implementation, this makes it a bit use-case specific. Next, in addition to resetting the timeout, arguments have to be preserved (2️⃣), and, when a time period with no invocations passes, it needs to prepare(3️⃣) for a new set of arguments.</p><pre>function aggregatingDebounce&lt;T&gt;(delay: number) {<br>    return (target: (arg: T[]) =&gt; void, ctx: ClassMethodDecoratorContext) =&gt; {<br>        let timeoutRef: number | undefined;<br>        let aggregatedArgs: Set&lt;T&gt; = new Set();         // 1️⃣<br>        let instance: any;<br><br>        const executeAndCleanUp = () =&gt; {<br>            target.call(instance, [...aggregatedArgs]);<br>            aggregatedArgs = new Set();                 // 3️⃣<br>        }<br><br>        return function (this: any, arg: T[]) {<br>            instance = this;<br>            arg.forEach(a =&gt; aggregatedArgs.add(a));    // 2️⃣<br>            clearTimeout(timeoutRef);<br>            timeoutRef = setTimeout(executeAndCleanUp, delay);<br>        }<br>    }<br>}</pre><p>To show how it works, imagine a logger class that accepts string events to be sent to a server or written to a file on disk. A shell of such class with a decorator utilized is shown in the following test:</p><pre>class Logger {<br>    constructor(private save: (events: string[]) =&gt; void){ }<br><br>    @aggregatingDebounce&lt;string&gt;(50)<br>    public log(events: string[]) {<br>        this.save(events);<br>    }<br>}<br><br>Deno.test(<br>    &quot;Calling debounced function twice in short succession invokes it once, with arguments aggregated&quot;,<br>    async () =&gt; {<br>        const saveMock = spy&lt;any, string[][]&gt;();<br>        const logger = new Logger(logMock);<br><br>        // 1️⃣<br>        logger.log([&#39;test#1&#39;]);<br>        logger.log([&#39;test#2&#39;]);<br><br>        await delay(50);<br>        assertSpyCalls(saveMock, 1);<br>        assertEquals(saveMock.calls[0].args[0], [&#39;test#1&#39;, &#39;test#2&#39;]);   // 2️⃣<br>});</pre><p>Test is calling the log method twice(1️⃣), one call right after the other with different arguments, and, later, it is checked that only a single call was made with arguments aggregated(2️⃣).</p><h3>Handling return values</h3><p>This is going to resemble the debounce concept description even less, but what if the method in question has a return value? How could arguments still be aggregated and corresponding return values be returned to call sites?</p><p>When a method returns a value and the operation is guaranteed to be asynchronous (will only execute when no calls are made for some time), the contract must be changed to promise returning (1️⃣). Then, building on the previous sample, not only must arguments be stored, but also a “batch promise”(2️⃣), which represents that single actual invocation is needed. Each invocation will subscribe(3️⃣) to this promise so that when the actual method is executed and the batch promise is resolved(4️⃣) (or rejected), call sites will be notified. Lastly, and this is again use case specific, return values must be mapped(5️⃣) to what specific invocation requested.</p><pre>function aggregatingDebounceWithReturn&lt;TIn, TOut&gt;(delay: number) {<br>    return (target: (arg: TIn[]) =&gt; Promise&lt;Map&lt;TIn, TOut&gt;&gt; /*1️⃣*/, ctx: ClassMethodDecoratorContext) =&gt; {<br>        let timeoutRef: number | undefined;<br>        let aggregatedArgs: Set&lt;TIn&gt; = new Set();<br>        let instance: any;<br><br>        // 2️⃣<br>        let resolve: (value: Map&lt;TIn, TOut&gt;) =&gt; void, reject: (reason: any) =&gt; void;<br>        let promise = new Promise&lt;Map&lt;TIn, TOut&gt;&gt;((res, rej) =&gt; {<br>            resolve = res;<br>            reject = rej;<br>        });<br><br>        const executeAndCleanUp = () =&gt; {<br>            const args = [...aggregatedArgs];<br>            aggregatedArgs = new Set();<br>            // reset promise<br>            const [res, rej] = [resolve, reject];<br>            promise = new Promise&lt;Map&lt;TIn, TOut&gt;&gt;((res, rej) =&gt; {<br>                resolve = res;<br>                reject = rej;<br>            });<br><br>            // 4️⃣<br>            target.call(instance, args)<br>                .then(results =&gt; res(results))<br>                .catch(reason =&gt; rej(reason));<br>        }<br><br>        return function (this: any, arg: TIn[]) {<br>            instance = this;<br>            arg.forEach(a =&gt; aggregatedArgs.add(a));<br>            clearTimeout(timeoutRef);<br>            timeoutRef = setTimeout(executeAndCleanUp, delay);<br><br>            return promise<br>                .then(results =&gt; {  // 3️⃣<br>                    const invocationResults: Map&lt;TIn, TOut&gt; = new Map();<br>                    for (const [key, value] of results) {<br>                        if (arg.includes(key)) {    // 5️⃣<br>                            invocationResults.set(key, value);<br>                        }<br>                    }<br>                    return invocationResults;<br>                });<br>        }<br>    }<br>}</pre><p>As a use case scenario, an endpoint returning whether feature flag is enabled or not can be used. Let’s also assume that determining flag status may be expensive; maybe some internal state can be shared for different flags.</p><pre>class FeatureFlags {<br>    constructor(private check: (names: string[]) =&gt; Promise&lt;Map&lt;string, &#39;enabled&#39; | &#39;disabled&#39;&gt;&gt;){ }<br><br>    @aggregatingDebounceWithReturn&lt;string, &#39;enabled&#39; | &#39;disabled&#39;&gt;(50)<br>    public getFeatureFlags(names: string[]) {<br>        return this.check(names);<br>    }<br>}<br><br>Deno.test(&#39;Each invocation receives part of response relevant to it&#39;, async () =&gt; {<br>    const flagsResolverMock = spy&lt;any, string[][], Promise&lt;Map&lt;string, &#39;enabled&#39; | &#39;disabled&#39;&gt;&gt;&gt;(<br>        (names) =&gt; Promise.resolve(new Map(names.map(n =&gt; [n, &#39;enabled&#39;]))));<br>    const flags = new FeatureFlags(flagsResolverMock);<br><br>    const [first, second] = await Promise.all(<br>        [<br>            flags.getFeatureFlags([&#39;test#1&#39;]),<br>            flags.getFeatureFlags([&#39;test#2&#39;])<br>        ]);<br><br>    assertEquals([...first.keys()], [&#39;test#1&#39;]);<br>    assertEquals([...second.keys()], [&#39;test#2&#39;]);<br>});</pre><h3>Conclusion</h3><p>With arguments aggregation and dealing with return values, the debounce definition might have been bent a little bit here. However, this pattern has the potential to reduce load, even though each use case may need a partially unique implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b8774cc220" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power server on and off on schedule]]></title>
            <link>https://medium.com/@tomas.madajevas/power-server-on-and-off-on-schedule-a8d0e2818e8c?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8d0e2818e8c</guid>
            <category><![CDATA[crontab]]></category>
            <category><![CDATA[ubuntu-server]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 11:39:28 GMT</pubDate>
            <atom:updated>2025-07-19T11:39:28.019Z</atom:updated>
            <content:encoded><![CDATA[<p>I play Minecraft with friends. To ease getting on the same world and to enable us to play when any of us wishes to, not aligning play time with the host, our world is hosted on an Intel NUC running Ubuntu server. Needless to say, it isn’t using much power. While idle, it averages at 3.5W, and when playing, I have not observed it going above 8.5W. However, as <a href="https://www.urbandictionary.com/define.php?term=effectionist">effectionist</a> that I am, I wanted to cut its uptime only to hours that any one of us working men is free.</p><p>To achieve that, I have used <a href="https://man7.org/linux/man-pages/man8/rtcwake.8.html">rtcwake</a> to shutdown and set the time to wake up, and <a href="https://man7.org/linux/man-pages/man5/crontab.5.html">crontab</a> to execute rtcwake at a specific time. All this can be configured in crontab (crontab -e), and with weekends being a special case (longer uptime), the configuration looks like this:</p><pre># Mon–Thu: shutdown at 11PM, wake next day at 5 PM<br>0 23 * * 1-4 /usr/sbin/rtcwake -m off -t $(date +\%s -d &#39;17:00 tomorrow&#39;)<br><br># Friday: shutdown at 11 PM, wake next day at 9 AM (Saturday)<br>0 23 * * 5 /usr/sbin/rtcwake -m off -t $(date +\%s -d &#39;09:00 tomorrow&#39;)<br><br># Saturday: shutdown at 11 PM, wake next day at 9 AM (Sunday)<br>0 23 * * 6 /usr/sbin/rtcwake -m off -t $(date +\%s -d &#39;09:00 tomorrow&#39;)<br><br># Sunday: shutdown at 11 PM, wake next day at 5 PM (Monday)<br>0 23 * * 0 /usr/sbin/rtcwake -m off -t $(date +\%s -d &#39;17:00 tomorrow&#39;)</pre><p>Don’t forget that this schedule will run in the server’s timezone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8d0e2818e8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic search locally]]></title>
            <link>https://medium.com/@tomas.madajevas/semantic-search-locally-4c4fa994bbac?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c4fa994bbac</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[onnx]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 17:31:52 GMT</pubDate>
            <atom:updated>2025-07-01T17:31:52.119Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing semantic search in the cloud while accessing LLM through API would be a faster and more convenient way (with a price attached) to do semantic search. However, having stuff hidden behind APIs also hides its inner workings. I have a mentality of understanding how things work under the surface, at least a little bit. With this goal in mind, I’ve implemented a fictional semantic search project using tools I know, and am sharing it as a tutorial for anyone curious.</p><h3>Tools</h3><ul><li>Microsoft.ML.OnnxRuntime to host the model for embedding. Tried using pipeline as described <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.ml.textcatalog.applywordembedding?view=ml-dotnet-preview">here</a>, but none of the models I&#39;ve tried appear to be working well with sentences and paragraphs.</li><li><a href="https://github.com/georg-jung/FastBertTokenizer">FastBertTokenizer</a> to convert text into tokens.</li><li>intfloat/e5-large-v2 ONNX model from <a href="https://huggingface.co/intfloat/e5-large-v2">Hugging Face</a> for embedding. Haven&#39;t tried many models. This one seems to work to my satisfaction.</li><li>IMDB moves dataset from <a href="https://www.kaggle.com/api/v1/datasets/download/ashpalsingh1525/imdb-movies-dataset">Kaggle</a> as testing data.</li><li>SQL Server 2025 to store embedding along with embedded data.</li></ul><h3>Exercise</h3><p>For exercise, I came up with an idea of searching movies by their overview, plot, etc. Data set found provides overviews of ~10K movies.</p><h3>Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*L2r9lRmEEthDpcRuMW_pCA.png" /></figure><p>To be able to search, first database to search in has to be prepared, and to do that text to vector (embedding) functionality is needed.</p><h3>Embedding</h3><p>The following code will serve for both data loading and searching.</p><pre>// 1️⃣<br>var session = new InferenceSession(@&quot;&lt;path to model&gt;\onnx\model.onnx&quot;);<br><br>// 2️⃣<br>var tokenizer = new BertTokenizer();<br>using var tokenJsonStream = File.OpenRead(@&quot;&lt;path to model&gt;\tokenizer.json&quot;);<br>tokenizer.LoadTokenizerJson(tokenJsonStream);<br><br>string text = &quot;&quot;; // prompt user for search phrase or use text from dataset<br>var (inputIds, attentionMask, tokenTypeIds) = tokenizer.Encode(text);   // 3️⃣<br>attentionMask = Normalize(attentionMask);                               // 4️⃣<br>var inputIdsTensor = new DenseTensor&lt;long&gt;(Normalize(inputIds), [1, 128]);<br>var attentionMaskTensor = new DenseTensor&lt;long&gt;(attentionMask, [1, 128]);<br>var tokenTypeIdsTensor = new DenseTensor&lt;long&gt;(Normalize(tokenTypeIds), [1, 128]);<br>var inputs = new List&lt;NamedOnnxValue&gt;<br>{<br>    NamedOnnxValue.CreateFromTensor(&quot;input_ids&quot;, inputIdsTensor),<br>    NamedOnnxValue.CreateFromTensor(&quot;attention_mask&quot;, attentionMaskTensor),<br>    NamedOnnxValue.CreateFromTensor(&quot;token_type_ids&quot;, tokenTypeIdsTensor)<br>};<br><br>using var output = session.Run(inputs);     // 5️⃣<br><br>var result = output.First().AsTensor&lt;float&gt;();<br>var meanEmbedding = CalculateMean(result, attentionMask.Span);  // 6️⃣</pre><p>Here:</p><ul><li>1️⃣ Load the model for embedding.</li><li>2️⃣ Prepare the tokenizer. Same model (most, maybe all) comes with tokenizers.</li><li>Then, with the movie overview (or user’s query) encode it as tokens 3️⃣.</li><li>Next, it’s best practice to normalize 4️⃣ model input lengths (trim or pad with zeros) to the same length. Different sentences results in different number of tokens. I’ve chosen 128, which appeared to be more than the output length of quite a few overviews tried.</li><li>5️⃣ Get results from model.</li><li>Lastly, the model result must be averaged. The result is a matrix of all input tokens over all hidden layers, and what is needed here is a single vector. I don’t understand this well enough to explain better, and will not bore you with details. My implementation is <a href="https://github.com/Madajevas/SemanticSearch/blob/0ca82c670022f77e84ec8b437600086fe222083d/EmbeddingsService/TextEmbedder.cs#L113">here</a>.</li></ul><h3>Storing</h3><p>SQL Server 2025 has a <a href="https://learn.microsoft.com/en-us/sql/t-sql/data-types/vector-data-type?view=sql-server-ver17&amp;tabs=csharp">vector</a> data type. The model used produces output of 1024 dimensions, so to store minimal info of movies table is necessary:</p><pre>CREATE TABLE movies (<br>    id INT IDENTITY (1,1),<br>    name VARCHAR(500) NOT NULL,<br>    description TEXT NOT NULL,<br>    vector VECTOR(1024) NOT NULL<br>);</pre><p>Unfortunately, Dapper does not (yet?) support vector, so string interpolation will have to suffice:</p><pre>var movie = new { Title = &quot;...&quot;, Description = &quot;...&quot;, }; // 1️⃣<br>var embedding = GetEmbedding(movie.Description);         // 2️⃣<br>var sql = $&quot;&quot;&quot;<br>INSERT INTO movies (name, description, vector)<br>VALUES (<br>    @Title,<br>    @Description,<br>    CAST(JSON_ARRAY({string.Join(&#39;,&#39;, embedding)}) AS VECTOR(1024)) -- 3️⃣<br>)<br>&quot;&quot;&quot;;<br>await connection.ExecuteAsync(sql, movie, transaction);</pre><p>Movie (1️⃣) variable represents data loaded from the dataset. For embedding (2️⃣) code shown before is used. For what I’ve tried, materializing embedding as JSON array and casting (3️⃣) it to a vector was the fastest way to make SQL server understand data provided.</p><h3>Searching</h3><p>At this point, text can be embedded, data to search is prepared, leaving the last building block — search:</p><pre>var search = &quot;&lt;prompt for movie to look for&gt;&quot;<br>var searchVector = GetEmbedding(search);<br>var query = $&quot;&quot;&quot;<br>SELECT TOP (10)<br>    name,<br>    description,<br>    VECTOR_DISTANCE(    -- 1️⃣<br>        &#39;cosine&#39;,<br>        CAST(JSON_ARRAY({string.Join(&#39;,&#39;, searchVector)}) AS VECTOR(1024)), -- 2️⃣<br>        vector<br>    ) AS distance<br>FROM movies<br>ORDER BY distance   -- 3️⃣<br>&quot;&quot;&quot;;<br>var results = await connection.QueryAsync&lt;(string, string, float)&gt;(query);</pre><p>Here <a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/vector-distance-transact-sql?view=sql-server-ver17">VECTOR_DISTANCE</a> (1️⃣) function is used. Search phrase, embedded as before, is cast to a vector. The closer vectors are to each other, the more semantically similar the phrases are, hence results are ordered by distance (3️⃣).</p><p>So, given the dataset, when I search for “fight against robots”, the results are:</p><ol><li>Robot Overlords</li><li>The Last of Us — No Escape</li><li>Ron’s Gone Wrong</li><li>Shark Side of the Moon</li><li>Pacific Rim</li><li>Rock on Fire</li><li>Cyborg X</li><li>The Transformers: The Movie</li><li>Singularity</li><li>Next Gen</li></ol><p>Titles alone shows that search works, at least to some extent (The last of us is a little surprising).</p><h3>Conclusion</h3><p>While results are definitely leaning in a correct direction, those can still be improved, maybe with a different model, or maybe there is an error in something I’ve done. Optimizing may become another weekend’s project. In this text, I have only presented the most interesting code parts. The whole solution is on <a href="https://github.com/Madajevas/SemanticSearch/tree/v1">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c4fa994bbac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When REST and JSON are everywhere, give a try to named pipe]]></title>
            <link>https://medium.com/@tomas.madajevas/when-rest-and-json-are-everywhere-give-a-try-to-named-pipe-4d94bece0847?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d94bece0847</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[named-pipes]]></category>
            <category><![CDATA[interprocesscommunication]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 06:57:20 GMT</pubDate>
            <atom:updated>2025-06-06T06:57:20.326Z</atom:updated>
            <content:encoded><![CDATA[<p>REST with JSON payloads dominates web communication. It is even used between servers. It’s not the most efficient, but with widespread adoption and numerous optimizations, it has become easy to implement and perform well enough for most use cases. However, I got a bit tired of it and when an opportunity to try something else presented itself, I took it.</p><h3>Context</h3><p>To begin with, I’ll set some context. It will help with the examples below.</p><p>With all the AI and related stuff hype, I got around to trying semantic(vector) search. Since all this is just to learn, instead of just offloading it all to the cloud and LLM providers I do it all on the device, text embedding included. Embedding, it turns out, is quite memory intensive and to load a model takes time which increases feedback loop and slows me down. A natural solution is just to host a model in another process that would not have to be restarted often. Here is where the idea to use a named pipe for inter-process communication appeared: all I need is to upload text and download a float array(vector). Why wrap it in JSON and send HTTP headers around that would play no role here?</p><h3>Protocol</h3><p>With named pipes when a client connects to a server in duplex mode, we have a bidirectional stream. Streams, as we know, operate on bytes and without reopening it for each request (keeping it open improves performance) it would not be clear where one message ends and another starts. To solve this, the stream must be framed — some protocol to interpret the bytes must be applied.</p><p>Given the context, it should be enough to send the length of text (the other end must know how much data to expect) to be embedded from client size, followed by that text, then, after reading it and embedding it on the server, length of vector (different models produces different length) can be written, followed by vector itself, and, lastly client reads vector length and vector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*mcHVvm5XuTzY5xCPVNh51w.png" /></figure><h3>Implementation</h3><p>Client side:</p><pre>var client = new NamedPipeClientStream(&quot;.&quot;, &quot;testpipe&quot;, PipeDirection.InOut); // 1️⃣<br>await client.ConnectAsync();<br><br>async Task&lt;float[]&gt; GetEmbeddingAsync(string text, CancellationToken cancellationToken)<br>{<br>    // 2️⃣<br>    var payload = Encoding.UTF8.GetBytes(text);<br>    await client.WriteAsync(BitConverter.GetBytes(payload.Length), cancellationToken);<br>    await client.WriteAsync(payload, 0, payload.Length, cancellationToken);<br><br>    var lengthBuffer = ArrayPool&lt;byte&gt;.Shared.Rent(sizeof(int));<br>    // 3️⃣<br>    await client.ReadExactlyAsync(lengthBuffer, 0, sizeof(int), cancellationToken);<br>    var length = BitConverter.ToInt32(lengthBuffer, 0);<br>    ArrayPool&lt;byte&gt;.Shared.Return(lengthBuffer);<br><br>    var vectorBuffer = ArrayPool&lt;byte&gt;.Shared.Rent(sizeof(float) * length);<br>    // 4️⃣<br>    await client.ReadExactlyAsync(vectorBuffer, 0, sizeof(float) * length, cancellationToken);<br>    var vector = new float[length];<br>    Buffer.BlockCopy(vectorBuffer, 0, vector, 0, sizeof(float) * length); // 5️⃣<br>    ArrayPool&lt;byte&gt;.Shared.Return(vectorBuffer);<br><br>    return vector;<br>}</pre><ol><li>Opening bidirectional pipe. Not shown here, but it is important to dispose of it once done.</li><li>In a method designed to process multiple requests, text is converted to bytes and written to stream: length first, then text.</li><li>After the request is sent, we start expecting a response. As per defined protocol, the size of the vector should arrive first, so the code waits for exactly four bytes.</li><li>Now, with the number of array elements known, the code waits for that amount of data to be available,</li><li>And converts it to an array of floats.</li></ol><p>Server code kind of mirrors clients:</p><pre>var server = new NamedPipeServerStream(&quot;testpipe&quot;, PipeDirection.InOut);<br>await server.WaitForConnectionAsync(stoppingToken);<br><br>while (server.IsConnected)<br>{<br>    var lengthBuffer = ArrayPool&lt;byte&gt;.Shared.Rent(sizeof(int));<br>    // 1️⃣<br>    await server.ReadExactlyAsync(lengthBuffer, 0, sizeof(int), cancellationToken);<br>    var length = BitConverter.ToInt32(lengthBuffer, 0);<br>    ArrayPool&lt;byte&gt;.Shared.Return(lengthBuffer);<br><br>    var payloadBuffer = ArrayPool&lt;byte&gt;.Shared.Rent(length);<br>    // 2️⃣<br>    await server.ReadExactlyAsync(payloadBuffer, 0, length, cancellationToken);<br>    var text = System.Text.Encoding.UTF8.GetString(payloadBuffer, 0, length);<br>    ArrayPool&lt;byte&gt;.Shared.Return(payloadBuffer);<br><br>    var payload = GetRandom().ToArray();<br>    // 3️⃣<br>    await server.WriteAsync(BitConverter.GetBytes(payload.Length), cancellationToken);<br><br>    var bufferSize = sizeof(float) * payload.Length;<br>    var buffer = ArrayPool&lt;byte&gt;.Shared.Rent(bufferSize);<br>    // 4️⃣<br>    Buffer.BlockCopy(payload, 0, buffer, 0, bufferSize);<br>    await server.WriteAsync(buffer, 0, bufferSize, cancellationToken);<br>    ArrayPool&lt;byte&gt;.Shared.Return(buffer);<br><br>    await server.FlushAsync(cancellationToken);<br>}<br><br>IEnumerable&lt;float&gt; GetRandom()<br>{<br>    for (var i = 0; i &lt; 900; i++)<br>    {<br>        yield return Random.Shared.NextSingle();<br>    }<br>}</pre><p>Random “vector” generation aside (it is not the point here):</p><ol><li>The server waits for the size of the payload,</li><li>Reads and interprets it as text,</li><li>Sends the length of the vector back to the client</li><li>Followed by vector.</li></ol><p>This definitely looks more difficult and verbose than hosting an endpoint and consuming it via HTTP client, However steps are clear and can be adapted to other use cases. Lastly, lets compare performance.</p><h3>Performance</h3><p>I kept http variant to a minimum: single endpoint accepting text in query and returning array of floats.</p><pre>app.MapGet(&quot;/&quot;, ([FromQuery]string text) =&gt;<br>{<br>    IEnumerable&lt;float&gt; GetRandom()<br>    {<br>        for (var i = 0; i &lt; 900; i++)<br>        {<br>            yield return Random.Shared.NextSingle();<br>        }<br>    }<br><br>    return GetRandom();<br>});</pre><p>Benchmarking inter-process communication with <a href="https://benchmarkdotnet.org/">BenchmarkDotNet</a> is not the right choice, so with the spirit of trying something new, I opted for <a href="https://nbomber.com/">NBomber</a>. Here is its scenario for http:</p><pre>using var httpClient = new HttpClient();<br>var scenario = Scenario.Create(&quot;http&quot;, async context =&gt;<br>{<br>    // 1️⃣<br>    var text = LoremNET.Lorem.Words(3);<br>    var vector = await httpClient<br>        .GetFromJsonAsync&lt;IEnumerable&lt;float&gt;&gt;($&quot;http://localhost:5084/?text={text}&quot;);<br><br>    return Response.Ok&lt;IEnumerable&lt;float&gt;&gt;(vector.ToArray()/*2️⃣*/);<br>})<br>    .WithoutWarmUp()<br>    .WithLoadSimulations(Simulation.KeepConstant(1, TimeSpan.FromSeconds(30))); // 3️⃣</pre><p>Quite a simple loop that sends random text(1️⃣) and expects a collection of floats back. Materializing collection to array(2️⃣) just to make sure that data is actually processed. The scenario is allowed to run for 30s, a single request at a time.</p><p>You already saw the code for the named pipe server. To test performance it was just wrapped in a hosted service to be started with the console app. Client-side scenario uses GetEmbeddingAsync method from above:</p><pre>var scenario = Scenario.Create(&quot;named_pipe&quot;, async context =&gt;<br>{<br>    var text = LoremNET.Lorem.Words(3);<br>    var vector = await GetEmbeddingAsync(text);<br><br>    return Response.Ok&lt;IEnumerable&lt;float&gt;&gt;(vector);<br>})<br>    .WithoutWarmUp()<br>    .WithLoadSimulations(Simulation.KeepConstant(1, TimeSpan.FromSeconds(30)));</pre><p>Executing both scenarios results in the http variant averaging at around 2834 requests per second while the named pipe reaches 9812 requests per second, a substantial improvement.</p><h3>Conclusion</h3><p>It appears that with a bit of effort to implement a custom protocol exchanging data can happen a lot faster using named pipes (those can work over the network too). Of course, I left quite a lot of safety mechanisms out that help performance, but on the other hand, there still is potential to reduce allocations. I’ve also tried multi-threaded scenario with somewhat the same results. My testing code is at <a href="https://github.com/Madajevas/NamedPipesTest">github</a> for anyone interested.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d94bece0847" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The case against IAsyncEnumerable<T>]]></title>
            <link>https://medium.com/@tomas.madajevas/the-case-against-iasyncenumerable-t-eab57b8cc5d1?source=rss-25429ec7fb3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eab57b8cc5d1</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Tomas M]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 17:38:58 GMT</pubDate>
            <atom:updated>2025-03-04T17:38:58.515Z</atom:updated>
            <content:encoded><![CDATA[<p>While title sounds bold, the actual case is much shallower one: returning it as WEB API response.</p><h3>Example</h3><p>In .NET before version 9, what do you think endpoint will return?</p><pre>app.MapGet(&quot;/weather-quiz&quot;, async () =&gt;<br>{<br>    async IAsyncEnumerable&lt;WeatherForecast&gt; StronglyTypeMe()<br>    {<br>        var summaries = new[]<br>        {<br>            &quot;Freezing&quot;, &quot;Bracing&quot;, &quot;Chilly&quot;, &quot;Cool&quot;, &quot;Mild&quot;, &quot;Warm&quot;, &quot;Balmy&quot;, &quot;Hot&quot;, &quot;Sweltering&quot;, &quot;Scorching&quot;<br>        };<br><br>        yield return new WeatherForecast<br>        (<br>            DateOnly.FromDateTime(DateTime.Now),<br>            Random.Shared.Next(-20, 55),<br>            summaries[Random.Shared.Next(summaries.Length)]<br>        );<br><br>        throw new InvalidOperationException(&quot;Failure is always an option&quot;); // BOOM<br>    }<br><br>    return StronglyTypeMe();<br>});</pre><p>If your guess is valid JSON of error details (assuming those are wired) you would be right. Now, with release of .NET 9 that is no longer the case, something rather strange would be returned (indentation added for clarity):</p><pre>[<br>    {<br>        &quot;date&quot;:&quot;2025-03-04&quot;,<br>        &quot;temperatureC&quot;:-17,<br>        &quot;summary&quot;:&quot;Cool&quot;,<br>        &quot;temperatureF&quot;:2<br>    }<br>    {<br>        &quot;type&quot;:&quot;https://tools.ietf.org/html/rfc9110#section-15.6.1&quot;,<br>        &quot;title&quot;:&quot;An error occurred while processing your request.&quot;,<br>        &quot;status&quot;:500<br>    }</pre><p>So response is invalid in at least two ways:</p><ul><li>JSON is invalid — collection is not closed</li><li>It contains not only weather objects as advertised (OpenAPI or something). Status code is correct (it is not a header) but figuring out issue might not be fun.</li></ul><p>Giving it a second thought, it is not so strange. Actually, it is stranger why it was not working this way before. If IAsyncEnumerable&lt;T&gt; is provided, it is only natural to start writing it to stream and saving on memory. Nothing can guarantee that retrieving first or one hundredth item along the way won`t fail.</p><p>So, my case against IAsyncEnumerable&lt;T&gt;: we should be careful using it as API return value. While on many levels it makes perfect sense, there are few considerations (list not exhaustive):</p><ul><li>How to communicate to client that error may happen at any time? Discriminated unions?</li><li>And how client can know what to do with values already received (maybe read as stream)? Are those to be discarded?</li><li>If error happens, is there a “correct” way to inform client? Maybe provide some mitigation guidelines. Headers are already flushed. Saying just read the last item and assume it is error sounds hacky…</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab57b8cc5d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>