<?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 Adrian Mos on Medium]]></title>
        <description><![CDATA[Stories by Adrian Mos on Medium]]></description>
        <link>https://medium.com/@adimosh?source=rss-51fbcdcad700------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1O1mMEPxh85RL022Gj-RgA.jpeg</url>
            <title>Stories by Adrian Mos on Medium</title>
            <link>https://medium.com/@adimosh?source=rss-51fbcdcad700------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:43:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adimosh/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 pitfalls of a common developer practice]]></title>
            <link>https://medium.com/codex/performance-pitfalls-of-a-common-developer-practice-16dd263c935b?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/16dd263c935b</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[antipattern]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 12:41:57 GMT</pubDate>
            <atom:updated>2023-07-27T12:41:57.428Z</atom:updated>
            <content:encoded><![CDATA[<p>Every developer, old and young, at some point in life, is going to stumble over code similar to the one below:</p><pre>public int ProcessStuff(IEnumerable&lt;int&gt; stuffToProcess)<br>{<br>    var itemsCache = stuffToProcess.ToArray();<br><br>    foreach (var item in itemsCache)<br>    {<br>        if (Count &gt; 15)<br>        {<br>            RemoveLastItem();<br>        }<br><br>        var (success, result) = ProcessValue(item);<br>        if (success)<br>        {<br>            AddItem(item);<br>            <br>            if (Count == 0) SetBaseline(result);<br>        }<br>        <br>        AddResultToResultsCollection(result);<br><br>        if (Count &gt; 2)<br>        {<br>            UpdateAverages();<br>            UpdateMedianDeviationValue();<br>            ReevaluateWithBaseline();<br>        }<br>    }<br><br>    return _medianDeviation;<br>}</pre><p>Did you catch an anti-pattern? If yes, congratulations, you are probably experienced, maybe even senior, and are well-versed in reading code that can be improved. But for those that haven’t, let’s add some context, in the sense that we should know what the Count is:</p><pre>public int Count { get; private set; }</pre><p>Ok, if you still cannot spot the anti-pattern, do not worry. It is a common occurrence to see this happening in all codebases. I, for one, have yet to see a codebase entirely rid of this issue. Let’s highlight, for clarity:</p><pre>public int ProcessStuff(IEnumerable&lt;int&gt; stuffToProcess)<br>{<br>    var itemsCache = stuffToProcess.ToArray();<br><br>    foreach (var item in itemsCache)<br>    {<br>        // Count is accessed here...<br>        if (Count &gt; 15)<br>        {<br>            RemoveLastItem();<br>        }<br><br>        var (success, result) = ProcessValue(item);<br>        if (success)<br>        {<br>            AddItem(item);<br>            <br>            // ...and here...<br>            if (Count == 0) SetBaseline(result);<br>        }<br>        <br>        AddResultToResultsCollection(result);<br><br>        // ...and here!<br>        if (Count &gt; 2)<br>        {<br>            UpdateAverages();<br>            UpdateMedianDeviationValue();<br>            ReevaluateWithBaseline();<br>        }<br><br>    // Did you remember that this was a foreach loop?<br>    }<br><br>    return _medianDeviation;<br>}</pre><p>That’s right, the Count property is called again and again within the same method.</p><h3>Why it’s an anti-pattern</h3><p>First and foremost, because a property getter is not field access. A property getter works much like a method that returns a value of the same type as the property.</p><p>As a funny fact, one of my first projects was a GUI app that had to leverage Microsoft Visio. Back then, Visio’s API was seriously limited, and, since it was implemented mostly as a COM wrapper that had to be compatible with some obscure standards, it didn’t have property support. Instead, if you had a Count property, you would actually have two methods exposed:</p><pre>int get_Count();<br><br>void set_Count(int value);</pre><p>This, of course, resulted in both some funny discussions during code review, but it was also a rather important lesson in how we can understand properties.</p><p>This has major implications in our example, because, although the result of the property getter is used much like a field, there is no actual guarantee that it is going to be the same every time. In our case, yes, it is, but that is because we know what the getter does, as we can see it, and we know that it is side-effect-free. We cannot know that an outside library doesn’t, perchance, have a property whose getter is not side-effect-free (in itself an anti pattern), or whose getter simply does a lot of extra work for no reason at all (which is not necessarily an anti-pattern, but still not performant).</p><p>Also, we have a very obvious second issue: performance. Since the runtime treats the getter like a method, it will not offer you the same speed as a local field. The compiler cannot guess that the multiple calls are actually intended to be used as field access, and will not cache the return value anywhere. This means that, for each property call, there is the added cost of calling the getter, whatever that may entail.</p><p>Third issue, and also the mightiest, has to do with synchronized multi-threaded access. If you access the getter multiple times, and the state that the getter depends on is updated in-between calls by multiple threads, what’s to say that the result won’t change between calls? Clearly in our example there is no indication that any guarding against such an issue was even attempted.</p><h3>But how bad is it, performance-wise?</h3><p>Obviously, a couple of accesses is generally not going to hurt, nor is it going to be a major performance improvement if we cache he value there (of course, depending on the side effects of the getter).</p><p>But, really, how bad is it? Let’s find out with a few simple scenarios, and a trusty benchmark.net console app.</p><h4>The test system</h4><p>I used my current developer machine for this test, specced as follows:</p><pre>BenchmarkDotNet=v0.13.5, OS=Windows 11 (10.0.22621.1928/22H2/2022Update/SunValley2)<br>AMD Ryzen 9 3900X, 1 CPU, 24 logical and 12 physical cores<br>  [Host]     : .NET Framework 4.8.1 (4.8.9166.0), X64 RyuJIT VectorSize=256<br>  Job-GAFOEP : .NET 6.0.18 (6.0.1823.26907), X64 RyuJIT AVX2<br>  Job-LCYYTK : .NET 7.0.7 (7.0.723.27404), X64 RyuJIT AVX2<br>  Job-FXSAZS : .NET Framework 4.8.1 (4.8.9166.0), X64 RyuJIT VectorSize=256<br><br>RunStrategy=Throughput</pre><p>As you can see, I am using the .NET 4.8.1 runtime as a baseline, and testing for the .NET 6 and .NET 7 as well.</p><h4>The test project</h4><p>The test project is composed of a simple console application, with the benchmark.net NuGet package added (official site <a href="https://benchmarkdotnet.org/">here</a>, quick start <a href="https://benchmarkdotnet.org/articles/guides/getting-started.html">here</a>, documentation <a href="https://benchmarkdotnet.org/articles/overview.html">here</a>). Inside, we have an object that holds properties, named SimpleClassWithProperties, and the benchmark class, named TestRepeatedPropertyCalls.</p><p>The benchmark class aims to benchmark a few scenarios, such as:</p><ol><li>A simple property access, in which an int property is accessed in a loop</li><li>The same scenario, but the property value is cached and only accessed once outside the loop</li><li>A property which calls a lazy field behind and gets its value (an otherwise rather common pattern)</li><li>The same scenario, but in which the property value is cached between calls</li></ol><p>We’ll use, for the purpose of our test, loops of 1 000, 10 000, 100 000 and 1 000 000 iterations.</p><h4>The set-up</h4><p>I’ve used, in a typical benchmark.net fashion, a setup for my tests:</p><pre>[SimpleJob(RunStrategy.Throughput, runtimeMoniker: RuntimeMoniker.Net481, baseline: true)]<br>[SimpleJob(RunStrategy.Throughput, runtimeMoniker: RuntimeMoniker.Net60)]<br>[SimpleJob(RunStrategy.Throughput, runtimeMoniker: RuntimeMoniker.Net70)]<br>[RPlotExporter]<br>public class TestRepeatedPropertyCalls<br>{<br>    private readonly SimpleClassWithProperties _props = new();<br><br>    private int _field = 1;<br>    <br>    [Params(1000, 10000, 100000, 1000000)] public int Iterations { get; set; }<br><br>    [GlobalSetup]<br>    public void Setup()<br>    {<br>        _props.Initialize();<br>    }<br><br>// ... The benchmarks go here<br>}</pre><h3>First results</h3><p>The first scenario serves as a good benchmark. It is simple, it is by far the most common use of the anti-pattern, and a rather easy to miss problem in code.</p><pre>[Benchmark]<br>public void RepeatedSimpleCall()<br>{<br>    var props = _props;<br>    for (var i = 0; i &lt; Iterations; i++)<br>    {<br>        // public int SimpleValueProperty =&gt; 1;<br>        int q = props.SimpleValueProperty;<br>        q++;<br>    }<br>}</pre><pre>|             Method |              Runtime | Iterations |           Mean |        Error |      StdDev | Ratio | RatioSD |<br>|------------------- |--------------------- |----------- |---------------:|-------------:|------------:|------:|--------:|<br>| RepeatedSimpleCall |             .NET 6.0 |       1000 |       254.1 ns |      2.44 ns |     2.28 ns |  0.52 |    0.01 |<br>| RepeatedSimpleCall |             .NET 7.0 |       1000 |       243.7 ns |      0.98 ns |     0.92 ns |  0.50 |    0.00 |<br>| RepeatedSimpleCall | .NET Framework 4.8.1 |       1000 |       484.1 ns |      2.95 ns |     2.76 ns |  1.00 |    0.00 |<br>|                    |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCall |             .NET 6.0 |      10000 |     2,427.2 ns |     34.44 ns |    32.21 ns |  0.51 |    0.01 |<br>| RepeatedSimpleCall |             .NET 7.0 |      10000 |     2,403.2 ns |     32.47 ns |    30.38 ns |  0.50 |    0.01 |<br>| RepeatedSimpleCall | .NET Framework 4.8.1 |      10000 |     4,793.3 ns |     25.10 ns |    23.48 ns |  1.00 |    0.00 |<br>|                    |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCall |             .NET 6.0 |     100000 |    23,972.2 ns |    197.94 ns |   175.47 ns |  0.50 |    0.00 |<br>| RepeatedSimpleCall |             .NET 7.0 |     100000 |    23,900.3 ns |    265.07 ns |   234.98 ns |  0.50 |    0.01 |<br>| RepeatedSimpleCall | .NET Framework 4.8.1 |     100000 |    47,712.1 ns |    180.07 ns |   168.44 ns |  1.00 |    0.00 |<br>|                    |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCall |             .NET 6.0 |    1000000 |   243,836.9 ns |  2,915.52 ns | 2,727.18 ns |  0.51 |    0.01 |<br>| RepeatedSimpleCall |             .NET 7.0 |    1000000 |   240,423.8 ns |  3,204.80 ns | 2,997.78 ns |  0.50 |    0.01 |<br>| RepeatedSimpleCall | .NET Framework 4.8.1 |    1000000 |   479,850.0 ns |  4,859.77 ns | 4,545.83 ns |  1.00 |    0.00 |</pre><p>As we can see, even at 1 000 iterations, we can see a huge difference between .NET 4.8.1 and .NET 6, and a smaller one between .NET 6 and .NET 7. This goes to show the amount of work that went into .NET 6 and 7, and how fast the runtimes are nowadays. A testament to the .NET team.</p><p>The property doesn’t even access a field behind the scenes, it just returns a constant. Let’s see, however, what happens if we do access a field.</p><pre>[Benchmark]<br>public void RepeatedSimpleCallWithBackingField()<br>{<br>    var props = _props;<br>    for (var i = 0; i &lt; Iterations; i++)<br>    {<br>        // public int SimpleFieldProperty =&gt; _field;<br>        int q = props.SimpleFieldProperty;<br>        q++;<br>    }<br>}</pre><pre>|                             Method |              Runtime | Iterations |           Mean |        Error |      StdDev | Ratio | RatioSD |<br>|----------------------------------- |--------------------- |----------- |---------------:|-------------:|------------:|------:|--------:|<br>| RepeatedSimpleCallWithBackingField |             .NET 6.0 |       1000 |       245.1 ns |      0.70 ns |     0.58 ns |  1.00 |    0.01 |<br>| RepeatedSimpleCallWithBackingField |             .NET 7.0 |       1000 |       245.6 ns |      1.76 ns |     1.64 ns |  1.00 |    0.01 |<br>| RepeatedSimpleCallWithBackingField | .NET Framework 4.8.1 |       1000 |       245.9 ns |      1.40 ns |     1.24 ns |  1.00 |    0.00 |<br>|                                    |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCallWithBackingField |             .NET 6.0 |      10000 |     2,395.7 ns |     16.24 ns |    15.19 ns |  1.00 |    0.01 |<br>| RepeatedSimpleCallWithBackingField |             .NET 7.0 |      10000 |     2,383.7 ns |     10.73 ns |     8.37 ns |  1.00 |    0.01 |<br>| RepeatedSimpleCallWithBackingField | .NET Framework 4.8.1 |      10000 |     2,392.6 ns |      9.84 ns |     9.20 ns |  1.00 |    0.00 |<br>|                                    |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCallWithBackingField |             .NET 6.0 |     100000 |    24,162.7 ns |    463.42 ns |   533.68 ns |  1.00 |    0.03 |<br>| RepeatedSimpleCallWithBackingField |             .NET 7.0 |     100000 |    23,803.0 ns |    120.81 ns |    94.32 ns |  0.98 |    0.03 |<br>| RepeatedSimpleCallWithBackingField | .NET Framework 4.8.1 |     100000 |    24,271.6 ns |    484.19 ns |   557.59 ns |  1.00 |    0.00 |<br>|                                    |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCallWithBackingField |             .NET 6.0 |    1000000 |   238,677.4 ns |  2,587.81 ns | 2,294.02 ns |  0.99 |    0.02 |<br>| RepeatedSimpleCallWithBackingField |             .NET 7.0 |    1000000 |   238,182.7 ns |  1,726.83 ns | 1,530.79 ns |  0.99 |    0.02 |<br>| RepeatedSimpleCallWithBackingField | .NET Framework 4.8.1 |    1000000 |   240,777.6 ns |  4,150.65 ns | 3,882.52 ns |  1.00 |    0.00 |</pre><p>Now, let’s test the method accessing the field directly, without the use of a property:</p><pre>[Benchmark]<br>public void RepeatedBackingField()<br>{<br>    for (var i = 0; i &lt; Iterations; i++)<br>    {<br>        int q = _field;<br>        q++;<br>    }<br>}</pre><pre>|               Method |              Runtime | Iterations |           Mean |        Error |      StdDev | Ratio | RatioSD |<br>|--------------------- |--------------------- |----------- |---------------:|-------------:|------------:|------:|--------:|<br>| RepeatedBackingField |             .NET 6.0 |       1000 |       249.6 ns |      5.00 ns |     4.68 ns |  1.02 |    0.02 |<br>| RepeatedBackingField |             .NET 7.0 |       1000 |       246.5 ns |      2.08 ns |     1.84 ns |  1.01 |    0.01 |<br>| RepeatedBackingField | .NET Framework 4.8.1 |       1000 |       244.5 ns |      1.35 ns |     1.19 ns |  1.00 |    0.00 |<br>|                      |                      |            |                |              |             |       |         |<br>| RepeatedBackingField |             .NET 6.0 |      10000 |     2,384.9 ns |     14.12 ns |    11.79 ns |  0.99 |    0.01 |<br>| RepeatedBackingField |             .NET 7.0 |      10000 |     2,410.9 ns |     24.77 ns |    23.17 ns |  1.00 |    0.01 |<br>| RepeatedBackingField | .NET Framework 4.8.1 |      10000 |     2,399.8 ns |     19.73 ns |    18.45 ns |  1.00 |    0.00 |<br>|                      |                      |            |                |              |             |       |         |<br>| RepeatedBackingField |             .NET 6.0 |     100000 |    23,884.3 ns |    166.91 ns |   156.13 ns |  1.00 |    0.01 |<br>| RepeatedBackingField |             .NET 7.0 |     100000 |    24,117.7 ns |    460.60 ns |   582.51 ns |  1.02 |    0.03 |<br>| RepeatedBackingField | .NET Framework 4.8.1 |     100000 |    23,884.1 ns |    195.06 ns |   172.91 ns |  1.00 |    0.00 |<br>|                      |                      |            |                |              |             |       |         |<br>| RepeatedBackingField |             .NET 6.0 |    1000000 |   238,962.3 ns |  1,106.20 ns |   923.72 ns |  1.01 |    0.00 |<br>| RepeatedBackingField |             .NET 7.0 |    1000000 |   240,825.0 ns |  4,556.26 ns | 4,474.85 ns |  1.02 |    0.02 |<br>| RepeatedBackingField | .NET Framework 4.8.1 |    1000000 |   237,235.7 ns |  1,274.31 ns | 1,129.65 ns |  1.00 |    0.00 |</pre><p>And finally, let’s see what happens if we access the property once, then cache the result in a local variable, and use it further down the road:</p><pre>[Benchmark]<br>public void RepeatedSimpleCallWithCachedValue()<br>{<br>    var props = _props;<br>    // public int SimpleValueProperty =&gt; 1;<br>    int q = props.SimpleValueProperty;<br>    for (var i = 0; i &lt; Iterations; i++)<br>    {<br>        q++;<br>    }<br>}</pre><pre>|                            Method |              Runtime | Iterations |           Mean |        Error |      StdDev | Ratio | RatioSD |<br>|---------------------------------- |--------------------- |----------- |---------------:|-------------:|------------:|------:|--------:|<br>| RepeatedSimpleCallWithCachedValue |             .NET 6.0 |       1000 |       247.3 ns |      1.85 ns |     1.73 ns |  0.98 |    0.03 |<br>| RepeatedSimpleCallWithCachedValue |             .NET 7.0 |       1000 |       248.3 ns |      4.26 ns |     4.18 ns |  0.99 |    0.03 |<br>| RepeatedSimpleCallWithCachedValue | .NET Framework 4.8.1 |       1000 |       252.4 ns |      5.01 ns |     5.57 ns |  1.00 |    0.00 |<br>|                                   |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCallWithCachedValue |             .NET 6.0 |      10000 |     2,400.8 ns |     13.57 ns |    12.03 ns |  1.00 |    0.01 |<br>| RepeatedSimpleCallWithCachedValue |             .NET 7.0 |      10000 |     2,402.8 ns |     20.51 ns |    19.18 ns |  1.00 |    0.01 |<br>| RepeatedSimpleCallWithCachedValue | .NET Framework 4.8.1 |      10000 |     2,400.0 ns |      9.35 ns |     8.75 ns |  1.00 |    0.00 |<br>|                                   |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCallWithCachedValue |             .NET 6.0 |     100000 |    23,822.2 ns |    134.62 ns |   125.93 ns |  1.00 |    0.01 |<br>| RepeatedSimpleCallWithCachedValue |             .NET 7.0 |     100000 |    23,942.8 ns |    133.21 ns |   104.00 ns |  1.00 |    0.01 |<br>| RepeatedSimpleCallWithCachedValue | .NET Framework 4.8.1 |     100000 |    23,914.0 ns |    237.39 ns |   210.44 ns |  1.00 |    0.00 |<br>|                                   |                      |            |                |              |             |       |         |<br>| RepeatedSimpleCallWithCachedValue |             .NET 6.0 |    1000000 |   242,126.0 ns |  3,900.67 ns | 3,457.84 ns |  1.02 |    0.02 |<br>| RepeatedSimpleCallWithCachedValue |             .NET 7.0 |    1000000 |   243,313.0 ns |  4,712.39 ns | 4,628.19 ns |  1.02 |    0.02 |<br>| RepeatedSimpleCallWithCachedValue | .NET Framework 4.8.1 |    1000000 |   238,232.4 ns |  1,425.86 ns | 1,263.99 ns |  1.00 |    0.00 |</pre><p>Let’s think about these results for a second.</p><p>We can clearly see the linearity in growth, relative to the iterations count. We do indeed get the general sense that 100 000 iterations is 100 times more time-consuming than 1 000 iterations and 10 times less time-consuming than 1 000 000 iterations. So there’s nothing hanky going on in the background, or, at least, not yet.</p><p>Next, we get the sense that there’s really not that much difference in performance when it comes to different ways of doing our work, with the notable exception of the “simple” call in .NET Framework. This deals with not how the values work, but more like how .NET Framework treats constant values, something which has been greatly improved in .NET Core and beyond.</p><p>So far, though, it almost seems like the anti-pattern that I’m talking about isn’t really that bad at all, is it? Let’s see when we get the second set of results.</p><h3>More complex tasks</h3><p>Let’s imagine a more complex pattern, which is still one of the most widely-used ones across the .NET world: accessing a property getter that returns a lazily-initialized field. Not a significantly more complex operation, not yet one with arcane side-effects, but still one that might get heavy. How heavy, you ask? Well…</p><pre>[Benchmark]<br>public void RepeatedLazyCall()<br>{<br>    var props = _props;<br>    for (var i = 0; i &lt; Iterations; i++)<br>    {<br>        // private readonly Lazy&lt;int&gt; _intLazy = new(() =&gt; 1);<br>        // public int LazyValueProperty =&gt; _intLazy.Value;<br>        int q = props.LazyValueProperty;<br>        q++;<br>    }<br>}</pre><pre>|           Method |              Runtime | Iterations |           Mean |        Error |      StdDev | Ratio | RatioSD |<br>|----------------- |--------------------- |----------- |---------------:|-------------:|------------:|------:|--------:|<br>| RepeatedLazyCall |             .NET 6.0 |       1000 |       492.1 ns |      3.45 ns |     3.23 ns |  0.20 |    0.00 |<br>| RepeatedLazyCall |             .NET 7.0 |       1000 |       733.5 ns |      7.68 ns |     7.18 ns |  0.30 |    0.01 |<br>| RepeatedLazyCall | .NET Framework 4.8.1 |       1000 |     2,439.7 ns |     34.70 ns |    32.46 ns |  1.00 |    0.00 |<br>|                  |                      |            |                |              |             |       |         |<br>| RepeatedLazyCall |             .NET 6.0 |      10000 |     4,856.4 ns |     22.03 ns |    19.53 ns |  0.20 |    0.00 |<br>| RepeatedLazyCall |             .NET 7.0 |      10000 |     4,874.7 ns |     25.70 ns |    24.04 ns |  0.20 |    0.00 |<br>| RepeatedLazyCall | .NET Framework 4.8.1 |      10000 |    24,029.2 ns |     69.25 ns |    64.78 ns |  1.00 |    0.00 |<br>|                  |                      |            |                |              |             |       |         |<br>| RepeatedLazyCall |             .NET 6.0 |     100000 |    72,443.7 ns |    397.80 ns |   372.10 ns |  0.30 |    0.00 |<br>| RepeatedLazyCall |             .NET 7.0 |     100000 |    48,631.2 ns |    371.58 ns |   347.58 ns |  0.20 |    0.00 |<br>| RepeatedLazyCall | .NET Framework 4.8.1 |     100000 |   242,897.8 ns |  1,269.98 ns | 1,187.94 ns |  1.00 |    0.00 |<br>|                  |                      |            |                |              |             |       |         |<br>| RepeatedLazyCall |             .NET 6.0 |    1000000 |   488,006.0 ns |  3,229.68 ns | 3,021.05 ns |  0.20 |    0.00 |<br>| RepeatedLazyCall |             .NET 7.0 |    1000000 |   487,949.1 ns |  2,684.41 ns | 2,379.66 ns |  0.20 |    0.00 |<br>| RepeatedLazyCall | .NET Framework 4.8.1 |    1000000 | 2,408,080.8 ns | 10,460.44 ns | 9,784.70 ns |  1.00 |    0.00 |</pre><p>Oooooook, well, that was quite educational. Not only do we have an interesting variability (especially if you look at the .NET 6 results), but we have a huuuuuuuuge difference between the 238 milliseconds of the local field access in the last test and the 2.4 seconds in the .NET Framework’s test. Even the .NET 7, which is almost across the board faster, is still around double in time consumed. That just gives you an indication as to how much of an anti-pattern this is for anything other than the simple properties (think auto-properties).</p><p>But did these carry over over local field access? I believe you’ll be completely not surprised to find out that they obviously didn’t, as this kind of test was simply put here as a showcase for developers at the beginning of their career:</p><pre>[Benchmark]<br>public void RepeatedLazyCallWithCachedValue()<br>{<br>    var props = _props;<br>    int q = props.LazyValueProperty;<br>    for (var i = 0; i &lt; Iterations; i++)<br>    {<br>        q++;<br>    }<br>}</pre><pre>|                          Method |              Runtime | Iterations |           Mean |        Error |      StdDev | Ratio | RatioSD |<br>|-------------------------------- |--------------------- |----------- |---------------:|-------------:|------------:|------:|--------:|<br>| RepeatedLazyCallWithCachedValue |             .NET 6.0 |       1000 |       262.9 ns |      2.92 ns |     2.59 ns |  1.00 |    0.01 |<br>| RepeatedLazyCallWithCachedValue |             .NET 7.0 |       1000 |       272.0 ns |      2.24 ns |     2.10 ns |  1.04 |    0.01 |<br>| RepeatedLazyCallWithCachedValue | .NET Framework 4.8.1 |       1000 |       262.8 ns |      1.96 ns |     1.74 ns |  1.00 |    0.00 |<br>|                                 |                      |            |                |              |             |       |         |<br>| RepeatedLazyCallWithCachedValue |             .NET 6.0 |      10000 |     2,436.0 ns |     20.96 ns |    18.58 ns |  1.00 |    0.01 |<br>| RepeatedLazyCallWithCachedValue |             .NET 7.0 |      10000 |     2,446.6 ns |     29.89 ns |    24.96 ns |  1.01 |    0.01 |<br>| RepeatedLazyCallWithCachedValue | .NET Framework 4.8.1 |      10000 |     2,429.9 ns |     13.19 ns |    11.69 ns |  1.00 |    0.00 |<br>|                                 |                      |            |                |              |             |       |         |<br>| RepeatedLazyCallWithCachedValue |             .NET 6.0 |     100000 |    24,085.5 ns |    224.20 ns |   209.72 ns |  0.99 |    0.01 |<br>| RepeatedLazyCallWithCachedValue |             .NET 7.0 |     100000 |    24,274.8 ns |    272.75 ns |   227.76 ns |  0.99 |    0.01 |<br>| RepeatedLazyCallWithCachedValue | .NET Framework 4.8.1 |     100000 |    24,398.5 ns |    184.29 ns |   172.38 ns |  1.00 |    0.00 |<br>|                                 |                      |            |                |              |             |       |         |<br>| RepeatedLazyCallWithCachedValue |             .NET 6.0 |    1000000 |   244,722.8 ns |  1,662.51 ns | 1,555.11 ns |  1.01 |    0.01 |<br>| RepeatedLazyCallWithCachedValue |             .NET 7.0 |    1000000 |   248,581.2 ns |  4,916.05 ns | 6,037.35 ns |  1.02 |    0.02 |<br>| RepeatedLazyCallWithCachedValue | .NET Framework 4.8.1 |    1000000 |   242,355.5 ns |  1,202.67 ns | 1,124.98 ns |  1.00 |    0.00 |</pre><h3>Conclusion</h3><p>First off, we get a sense of just how faster .NET 6 is than .NET Framework 4.8.1. While it’s true that this is happening on an anti-pattern, after all, we’re talking about property getters and lazy initialization, and there are many legitimate scenarios in which frequent use of them makes a lot of sense. Improving that area can make a great difference.</p><p>So there you have it. One of the most basic complications of property getters already gets you into trouble with repeated calls, performance-wise. I’ll leave you to your imagination to find out just how bad things get when we’re dealing with side-effects or even WTF moments like database reads.</p><p>I guess the main reason why I wish to point out this anti-pattern is that it’s both an easy anti-pattern to follow, and it’s also a very easy one to get rid of. Even tools like ReSharper can help you automatically replace all your property getter calls, and it’s one of the things most easily picked up by IntelliCode.</p><p>I’m sure going to be glad when serious AI rolls out, as it will most probably make short work of this anti-pattern.</p><p>While today’s .NET environments have greatly improved over what used to be the norm in an already-fast environment, fostering a culture of avoiding anti-patterns and performance-oriented coding can only help in the long run. Of course you can have code that is not really optimal, but it’s fast to write, but, really, with examples like the repeated property getter anti-pattern, exactly how much developer time do you save?</p><p>That is, unless, if you code multi-threaded applications, in which case, by thinking ahead and not following this anti-pattern, you’ll almost be certain to be saving a TON of time in debugging race conditions and improperly-synchronized field accesses across threads. Ask me how I know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16dd263c935b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/performance-pitfalls-of-a-common-developer-practice-16dd263c935b">Performance pitfalls of a common developer practice</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking a central heating system for efficiency]]></title>
            <link>https://adimosh.medium.com/hacking-a-central-heating-system-for-efficiency-202f38c761b0?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/202f38c761b0</guid>
            <category><![CDATA[smart-home]]></category>
            <category><![CDATA[heating]]></category>
            <category><![CDATA[carbon-emissions]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 09:46:30 GMT</pubDate>
            <atom:updated>2023-02-13T09:46:30.079Z</atom:updated>
            <content:encoded><![CDATA[<h4>Turning a centralized building heating system into your own personal boiler</h4><p>In Europe (at least), the winter of 2022–2023 brought nothing but higher heating bills, instability, and worry about adequate stocks of fuel (due to the Ukraine crisis).</p><p>I live in a block of flats, and am lucky enough to have an efficient, centralized heating system, with only one point where my meters are, and where the heating agent flow pipes come in. Therefore, an ideal setup to modify according to my own specifications, in order to make things as efficient as they can be.</p><p><em>Please note that this article contains affiliate links for the Romanian market.</em></p><h3>Original design</h3><p>Let’s first take a look at the original design:</p><figure><img alt="The original layout of the apartment heating system" src="https://cdn-images-1.medium.com/max/800/1*TqE28PVDVn2hzNiEyFQH8g.png" /><figcaption>Figure 1: The original layout of the heating system</figcaption></figure><p>As you can see, the layout is not overly complicated. But, four heating circuits, five rooms to heat. This, in itself, is a problem.</p><p>You see, the two rooms serviced by the same circuit have a H-type connector at the base of each radiator. This allows the two radiators to work independently, but also has the downside of not being able to fully shut off heating through the house if it is unnecessary. The only way in which the two H-type connectors can work independently is if there is a specific flow amount through both, regardless of whether or not the radiators are on.</p><p>So I needed to find a way to close off everything.</p><h3>Step 1: the global shut-off</h3><p>For the global shut-off, I chose a valve controlled by a thermal actuator. These valve and actuator combos have the advantage of being able to operate in the hot environment that is the distributor box, and have the added advantage of sturdiness and durability.</p><p>The actuator is an on/off style thermal engine, meaning that, if it receives power, it is in one state, and if it doesn’t, it transitions to the other state.</p><p>Normally, there are two main configurations on such a valve/actuator combo: normally closed (NC) and normally open (NO). Normally closed (which is also the configuration that I chose) means that the valve is in a closed position by default, not letting water through, and it needs action from the actuator to open. Similarly, the actuator is not acting on the valve if it has no power, and it is acting on the valve if it does have power. Conversely, the normally open configuration is the exact opposite: letting water through by default, and stopping it if necessary.</p><p>One further advantage of the actuator is that, while it acts sufficiently fast, it is slow by human action standards, and thus has a low risk of creating water hammers.</p><p>Then, the configuration looked like this:</p><figure><img alt="The layout of the heating system once the valve is on" src="https://cdn-images-1.medium.com/max/800/1*IWbKJQ5nzS3IVnZKSj_v3w.png" /><figcaption>Figure 2: The layout of the heating system once the valve is on</figcaption></figure><p>I chose to have the installation of the valve done by a professional plumber. I, myself, am not a plumber, nor do I have the tools that a plumber would normally use for such an operation. While it looks simple enough to do myself, I decided to trust a plumber, as they would surely know how to better handle combinations of metal and plastic pipes as to not break them, and also make the joints strong enough to not leak.</p><p>The installation, in the end, looks like this:</p><figure><img alt="Final installation of the shut-off valve and actuator" src="https://cdn-images-1.medium.com/max/1024/1*wc8Zd_0_ht8eaD4tkeEHuQ.jpeg" /><figcaption>Final installation of the shut-off valve and actuator</figcaption></figure><p>Used materials:</p><ul><li>One <a href="https://spishop.ro/ventile-cu-doua-si-trei-cai/1003957-vana-cu-2-cai-12-pn-16-213112p-cu-etansare-plana.html">planar valve, diameter of 1/2 inches, by Watts, model 213112P</a></li><li>One<a href="https://spishop.ro/ventile-cu-doua-si-trei-cai/1003765-electromotor-cu-2-fire-pt-vana-cu-2-sau-3-cai-22cx230nc2.html"> thermal wax engine actuator, also by Watts, model 22CX230NC2</a></li></ul><h3>Step 2: the actuator controls</h3><p>To control all of the above, I chose to create a custom control box to power the actuator of the shut-off valve.</p><p>While the main control unit behind the project (which we will talk about at step 4) appears to be able to supply enough current to the actuator, I wanted to offer the control unit some extra protection, and put it behind the control box.</p><p>First off, I installed a 16-amp circuit breaker. This is used as a gateway for everything electric.</p><p>Next, in the same box, I have a contact relay. It draws power through the circuit breaker, and has the input from the control unit. The output goes to the actuator, all according to the following schematic:</p><figure><img alt="Electrical control circuit for the valve’s actuator" src="https://cdn-images-1.medium.com/max/541/1*Y5lE36eKViGU5sikLsh6Og.png" /><figcaption>Figure 3: Electrical control circuit for the valve’s actuator. Note: the Netatmo relay is described in Step 4</figcaption></figure><p>Of course, the connections at the actuator level are placed inside an IP65-rated junction box, in order to not have any surprises on the electrical part.</p><p>Used materials:</p><ul><li>One <a href="https://l.profitshare.ro/l/11418740">rail-mounted 16-amp circuit breaker, by Comtec</a></li><li>One rail-mounted contact relay, also by Comtec</li><li>One <a href="https://l.profitshare.ro/l/11418739">breaker box, with rail, also by Comtec</a></li><li>Cables to run to and from (2*0.75 mm2, flexible copper)</li><li>Wires for the internal connections in the breaker box (2.5 mm2, solid copper)</li><li>An IP65-rated junction box</li></ul><h3>Step 3: the radiator controls</h3><p>Once the valve/actuator and the electric box were ready, it was time to move on to the radiators.</p><p>Since two circuits served bathrooms, I chose to not do anything special about them. One of the bathrooms is an internal one close to the center of the building (and also where the heating distributor is, so I just shut off that circuit completely. The other one I’ve left with its default thermostatic valve on, and whenever the controller turns the heat on, it has the chance to heat up the bathroom. So far, this proved enough.</p><p>Now, for the room with two radiators, I chose to close off the bypass in the H-type connectors, so that one radiator flows into the second one. As such, only one smart valve was needed altogether.</p><p>The rooms with one radiator each get their own smart valve, and their H-type connectors have their bypass open, so that they can release heat independently.</p><figure><img alt="The old radiator controls" src="https://cdn-images-1.medium.com/max/1024/1*nCYs7qFJkiJpllgVA5e_qw.jpeg" /><figcaption>The old radiator controls, which are still in use in the bathroom that doesn’t have a smart control valve</figcaption></figure><figure><img alt="The new radiator controls" src="https://cdn-images-1.medium.com/max/1024/1*S3BPOTtX5caz3HdEp6qA-w.jpeg" /><figcaption>The new radiator controls, installed in the rooms</figcaption></figure><p>And after this upgrade, the layout looked like this:</p><figure><img alt="The layout of the heating system once all elements are in place" src="https://cdn-images-1.medium.com/max/800/1*cXnv71WCVGYHV86NT2ZKpA.png" /><figcaption>Figure 4: The layout of the heating system once all elements are in place</figcaption></figure><p>Used materials:</p><ul><li>3 <a href="https://l.profitshare.ro/l/11418734">radiator smart valves by Netatmo</a></li></ul><h3>Step 4: the thermostat</h3><p>The “brains” of the whole system, of course, lie in the thermostat to control everything.</p><p>For the thermostat, I chose one that would have the following characteristics:</p><ul><li>It would interact with the smart thermostatic valves</li><li>It would allow me to place it anywhere in the house</li><li>It would allow me to set schedules, as well as to have manual control</li><li>It would seamlessly integrate with my already-existing automation systems</li></ul><p>Since I am an Apple user, and I also have a Home Assistant installation, I needed something that is compatible with both at the same time. I therefore chose the Netatmo platform.</p><p>While I greatly favor local control (and the Home Assistant integration for what I chose doesn’t yet provide that), I accepted, as a compromise, that heating would be handled by proxy on online services, especially since I could easily automate schedules which are good enough, and efficient enough to last well even through a prolonged vacation, just in case it so happened that my Internet connection failed completely while I was away.</p><p>A further advantage of the system is that it has its relay separate from the thermostat itself, meaning that the thermostat can be placed somewhere meaningful (such as on a table in the living room), whereas the relay can be kept close to the actuator control box.</p><p>Used materials:</p><ul><li>One <a href="https://l.profitshare.ro/l/11418733">Netatmo Smart Thermostat NTH-01</a> and its relay</li></ul><h3>Step 5: the automation</h3><p>The whole automation process involved correctly setting up some schedules in the <a href="https://apps.apple.com/ro/app/thermostat-by-netatmo/id730893725">Netatmo Energy app</a>, and some settings for comfort and usability.</p><p>Since I have a work-at-home setup (which I regularly use since the 2020 pandemic), I split the whole day into different bands, depending on what I’m doing, like working, or sleeping, or being away to take my daughter to and from school, etc.</p><figure><img alt="Example of schedule from Netatmo Energy app" src="https://cdn-images-1.medium.com/max/750/1*goB5dxKKi0fX2DY-Ugoh1g.png" /><figcaption>Example of schedule from Netatmo Energy app</figcaption></figure><p>After these schedules are complete, the system regulates temperature and heating so that it meets the specifications of the schedule. Such a heating schedule might look something like this in the graph in the app:</p><figure><img alt="Example of heating graphs in the Netatmo Energy app" src="https://cdn-images-1.medium.com/max/1024/1*1CbFn_gKPeu79PXFP3VldA.png" /><figcaption>Example of heating graphs in the Netatmo Energy app</figcaption></figure><p>The <a href="https://my.netatmo.com/app/energy">Netatmo Energy web application</a> shows an even more detailed graph (also including the outdoor temperature, with zoom controls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6hXHzDHRzLOJLh3NcPFPg.png" /><figcaption>Example of heating graphs in the Netatmo Energy web application</figcaption></figure><h3>Safety considerations</h3><p>I was able to build this custom system because I had followed the security considerations that come with such a system:</p><ul><li>I had mounted the valve on to a place where there originally was a passive connector, keeping all the original ball valves that would isolate the systems intact</li><li>The centralized heating system already has pressure release valves installed</li><li>There are already an extra set of ball valves installed before the valve which I replaced, further enhancing my ability to isolate the system if a problem is found</li></ul><figure><img alt="Installation of the valve and actuator, in context" src="https://cdn-images-1.medium.com/max/1024/1*DHa9bHIWhoJtusZG7lMRrQ.jpeg" /><figcaption>Installation of the valve and actuator, in the context of the existing ball valve (downstream, down left), a flow regulator (upstream, right), a filter (further upstream, right, behind the white sticker) and another ball valve (even further upstream, to the right, off-picture), plus the two visible ball valves on the other pipe (upstream of the entire apartment heating system)</figcaption></figure><ul><li>The electrical side features a circuit breaker that isolates every part of the system that is connected to the mains; in case of a water leak, assuming water could somehow get into the junction box, the breaker cuts off immediately</li></ul><figure><img alt="Installation of the junction box at the top of the box" src="https://cdn-images-1.medium.com/max/1024/1*XET7itQMvLJkN0g0z3PKvw.jpeg" /><figcaption>Installation of the junction box at the top of the box, further ensuring that water will have little chance to get to the electrical parts</figcaption></figure><ul><li>Downstream of the circuit breaker, the circuit the system is on also features a differential circuit breaker, and one more circuit breaker on the way until it gets to the main circuit breaker of the apartment</li></ul><p>With these safety considerations followed, I can confidently say that the system is safe to use, and is not likely to cause any harm to any part of the building.</p><h3>Results</h3><p>Let’s take a look at the results of this project.</p><p>The system was installed in November 2021, as the looming crisis meant that the winter of 2020–2021, which was not particularly hard on us, would seem like a sweet dream compared to the bills that we would be seeing in the 2021–2022 winter.</p><p>As the winter hit, and gas prices doubled, the system really made its point by keeping us warm enough, while, at the same time, keeping our bills acceptably low. They were even slightly lower than the 2020–2021 bills.</p><figure><img alt="Bills, in RON, for heating of an 88 square meter apartment in Cluj-Napoca" src="https://cdn-images-1.medium.com/max/458/1*oBddSl2paR80-IzIvDS92g.png" /><figcaption>Bills, in <a href="https://en.wikipedia.org/wiki/Romanian_leu">RON</a>, for heating of an 88 square meter apartment in Cluj-Napoca</figcaption></figure><p>As you can see, the system made sure to save us of the great increase in gas prices, and I can only imagine how low our costs would have been if the energy crisis hadn’t hit.</p><h3>Conclusions and future work</h3><p>For me and my family, the upgrade was well worth it, and it sparked a further immense investment in automating our house to our convenience.</p><p>The most important investment after this came with sensors within our rooms that measured temperature, carbon dioxide and humidity, which, by showing us the patterns of how these change during the day, have helped us greatly improve how we air the rooms, for how long and when during the day. This has further helped lowering heating bills and improving the quality of our life.</p><p>We also use a <a href="https://l.profitshare.ro/l/11435166">Netatmo Weather Station</a> that further enhances our ability to see various parameters outside, such as humidity, temperature and pollutants, and, in conjunction with an <a href="https://www.ikea.com/ro/ro/p/starkvind-purificator-aer-filtru-gaze-suplimn-alb-s59444217/">Ikea Starkvind</a> air purifier, also helps a lot with eliminating allergens.</p><p>I would greatly recommend that any home which can afford the initial investment go through the process of making its heating system as smart as possible. While the upfront costs are not negligible, I would say that the results are well worth it. In your area, the government or non-profit organizations may even offer subsidies, which make the whole system an even greater deal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=202f38c761b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interpreting mathematical expressions, a practical example]]></title>
            <link>https://medium.com/codex/interpreting-mathematical-expressions-a-practical-example-58c600d37655?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/58c600d37655</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[expression-tree]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 16:53:18 GMT</pubDate>
            <atom:updated>2022-06-02T16:53:18.324Z</atom:updated>
            <content:encoded><![CDATA[<h4>Interpreting advanced, expression-based user input to greatly enhance the usability of your industrial or professional application.</h4><p>As industrial applications develop, more complex user input needs to be interpreted, and it is usually not long until mathematical expressions need to be passed from the user (which is usually an engineer or a machine operator) to the software.</p><p>The big advantage of being able to get complex mathematical input directly from either the end-user or some form of intermediate programmer of the system should be obvious: it can be a great relief for the designers and developers of a software if they can rely on their users to do their own fine-tuning directly via the complexity of mathematical language, rather than having to do everything themselves.</p><p>When attempting to get software to interpret expressions, there are quite a few ways to go about. You could, for instance, write an interpreter that is strictly applicable to a particular domain, you can write an interpreter that hard-codes a certain subset of mathematics, or you can attempt to write a more general computer-recognizable expression parser.</p><p>In attempting to write a general expression parser, I started writing the <a href="https://www.nuget.org/packages/IX.Math/">IX.Math</a> package (source code available on <a href="https://adrianmos.eu/Redirect?label=github-ix.math">GitHub</a>, with documentation available <a href="https://adrianmos.eu/Pages/Projects/ixmath.md">here</a>), initially as a way to exercise mathematics and software development, as well as to provide an easy way to recognize and evaluate mathematics for what I imagined would be my daughter’s future school projects. It was only after a while that the library became incorporated into my commercial work after being used for parsing user input in one major project.</p><p>In this article, I hope to be able to show my approach at recognizing expressions in software, in the hope of shedding a little light on the topic and hopefully inspiring others. At any point in time you wish to see a more in-depth implementation, please refer to the library source code.</p><h3>Preamble: An expression</h3><p>Let’s take a very complex mathematical expression that can showcase as many of our basic parsing needs that we can:</p><blockquote>( x + 7 - 2 + 27*y + sin(x) ) / strlen(“This is a (“ + s + “) string”) = ( min(x, y)*( 37–2^z ) + z ) * 5</blockquote><p>Let’s analyse what the expression contains.</p><p>First off, we have an equation (notice the middle “=” sign) with two sides. On the left, we have functions (<em>sin </em>and <em>strlen</em>), we have an expression block in parentheses, we have strings (including a concatenation of strings), and those strings contain parentheses. On the right, we have multiple levels of parentheses. Both sides contain operators, constant values and variables. This expression showcases a lot of the capabilities that a mathematical expression parser should have.</p><p>When <a href="https://www.nuget.org/packages/IX.Math/">IX.Math</a> encounters this expression, it gets to work in multiple passes, to try and figure out what’s what.</p><h3>First challenge: breaking down to the bare minimum</h3><p>When dealing with complex constant expressions, especially those that come from user input, one of the first tasks to make our life easier is taking out as many complex constants that might, if any error in our algorithms exists down the line, throw our results off.</p><h4>Step one: Constants extraction</h4><p>Looking at the expression, by far the greatest risks are the strings. Not only can the parentheses inside be considered as part of the expression, but who knows what the full disruptive potential of user input can be. So let’s replace the strings with some generated names, and let’s save the strings as separate, constant expressions.</p><blockquote>( x + 7–2 + 27*y + sin(x) ) / strlen(const1 + s + const2) = ( min(x, y)*( 37–2^z ) + z ) * 5</blockquote><blockquote>with:</blockquote><blockquote>const1 = “This is a (“</blockquote><blockquote>const2 = “) string”</blockquote><p>The way this is achieved in IX.Math is via constant extractors — classes whose purpose is to be given expressions and extract as many constants out of them as they can, and are also the first extension point of the library.</p><p>Once we have all our specially-recognized constants, let’s move on to our next challenge: sub-expressions</p><h4>Step two: breaking down into multiple expressions</h4><p>What we see is that we have a complex expression that can be broken down into multiple sub-expressions with relative ease.</p><p>Let’s take the parentheses, for example. Every expression that is within parentheses can be considered as a sub-expression that can generate an expression tree similar to the main expression, and it would clear out our interpretation task. Let’s try and get that done:</p><blockquote>subexpr1 / strlen(subexpr2) = subexpr4 * 5</blockquote><blockquote>with:</blockquote><blockquote>subexpr1 = x + 7–2 + 27*y + sin(x)</blockquote><blockquote>subexpr2 = const1 + s + const2</blockquote><blockquote>subexpr3 = 37–2^z</blockquote><blockquote>subexpr4 = min(x, y)*subexpr3+ z</blockquote><blockquote>const1 = “This is a (“</blockquote><blockquote>const2 = “) string”</blockquote><p>Now, the expressions look a lot easier to manage, don’t they? Let’s move on and identify what we’re seeing.</p><h4>Step three: take out all that we know</h4><p>Let’s look at our main expression, which is now:</p><blockquote>subexpr1 / strlen(subexpr2) = subexpr4 * 5</blockquote><p>Let’s remove all operators that our parser can recognize. We’re left with this:</p><blockquote>subexpr1 strlen(subexpr2) subexpr4 5</blockquote><p>If we remove all that we already recognize, we are left with this:</p><blockquote>strlen( ) 5</blockquote><p>Now let’s look at what we can deduce out of that.</p><p>First, we have a function, which IX.Math can recognize by the tell-tale parentheses immediately after the name. In IX.Math, functions are defined by classes in either the library assembly or any other assembly that is interrogated, decorated with special attributes that tell the library what to look for in expressions, and are the second extension point in IX.Math (further documentation <a href="https://adrianmos.eu/Pages/Projects/ixmath/Functions.md">here</a>). <em>strlen</em>, in this case, resides inside IX.Math, and is recognized as a function.</p><p>Other than that, we are also left with 5, which is a constant that can be easily recognizable as a primitive type, and voila! we’ve recognized our expression. The same, of course, happens for the other sub-expressions.</p><p>One thing to mention here is that, should we have something more complex than “5”, for instance, we need to be able to define some way to see if a certain text is, in fact, a constant, or rather an external parameter. In IX.Math, anything that is not recognized at the end of this step is considered an external parameter, so it makes sense that another extensibility point exists in the library, namely constant interpreters — special classes that receive unrecognized text to figure out if they’re constants or not.</p><p>After this step is done, our expression is left in this situation:</p><blockquote>subexpr1 / subexpr5= subexpr4 * 5</blockquote><blockquote>with:</blockquote><blockquote>subexpr1 = x + 7–2 + 27*y + subexpr6</blockquote><blockquote>subexpr2 = const1 + s + const2</blockquote><blockquote>subexpr3 = 37–2^z</blockquote><blockquote>subexpr4 = subexpr7*subexpr3+ z</blockquote><blockquote>subexpr5 = strlen(subexpr2)</blockquote><blockquote>subexpr6 = sin(x)</blockquote><blockquote>subexpr7 = min(x, y)</blockquote><blockquote>const1 = “This is a (“</blockquote><blockquote>const2 = “) string”</blockquote><blockquote>with parameters: x, y, s, z</blockquote><p>…and we’re ready for the next step.</p><h3>Second challenge: building the expression tree</h3><p>Now that we have our expressions as clean as can be, it’s time to start interpreting them. We do that by transforming all the expressions into expression trees by looking at the operators and splitting the expression into left and right nodes until there is nothing left to split, and then we join all expressions to form one big expression tree in the end.</p><h4>Step four: Building the small trees</h4><p>Every expression and sub-expression that we have can be transformed into a <a href="https://en.wikipedia.org/wiki/Binary_expression_tree">binary expression tree</a> to then be computed. IX.Math achieves this by using a set priority to all operators, and then splitting the expression according to it. Let’s take our initial expression of:</p><blockquote>subexpr1 / subexpr5= subexpr4 * 5</blockquote><p>…and let’s try to find a way to divide it.</p><p>From this point onwards, it will be a lot easier to use drawn images to represent what we want to say.</p><p>Mathematically speaking, the operator with the lowest priority should be the equality operator, as it should be the last to be computed. We can use it as the first split, and we get a split as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*tg9jyWRxscRGeHl0cf--Aw.png" /><figcaption>The first split of our expression</figcaption></figure><p>We can then go on to the next priority, on the left branch, and split by the division operator, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*tY-afzmnos1iXtb_bnjYFQ.png" /><figcaption>The second split of our expression</figcaption></figure><p>And then for the right side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*sCtsq9oj9ZxahrsfgNZrDg.png" /><figcaption>The third split for our expression</figcaption></figure><p>Now that we have our split for the main expression, let’s do the same for all our other expressions, and let’s see our little expression trees all lined up. Please note that I have colorized the nodes according to their purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*mR1zzb8DGw3TdZr0X5yJ_w.png" /><figcaption>The fourth and final split into expressions</figcaption></figure><h4>Step five: building our final tree</h4><p>The last step in our building process is joining all the sub-trees together into one bigger tree:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNEB3hRcisohvEZf51KeMg.png" /><figcaption>The final expression tree</figcaption></figure><p>From this point onwards, it is not difficult to figure out how the whole tree can be solved. Each node is requested to offer its value. Each node, depending on the type of node that is, requests the values of its branches/leaves, and then does some operation on them. In turn, before the parent node can calculate its value, also requests the branches/leaves, if it has any, to calculate their values, and then does some operation according to its type, and so on.</p><p>Looking at the tree above, the sequence of operations is as follows:</p><blockquote>The value of “x” is requested. 7 is added to it, then 2 is subtracted from it.</blockquote><blockquote>7 is multiplied with the requested value of “x”, then the sine of the requested value of “x” is added. The result is added to the previous value.</blockquote><blockquote>“This is a (” is concatenated to the requested value of “s”, and has “) string” concatenated to it. Its length divides the previous value.</blockquote><blockquote>A minimum of the requested values of “x” and “y” is multiplied by the value of 2, subtracting the value of 27 raised to the power of the requested value of “y”, to which the requested value of “z” is added, and it is all multiplied by 5.</blockquote><blockquote>The obtained value is added to the previously-obtained value to get the result.</blockquote><p>In a nutshell, this is the way that the algorithm ends up with an expression tree. But what next?</p><h3>Third challenge: Validating the expression</h3><p>After a tree such as the one above is obtained, the expression needs to be validated, to ensure that it is logically sound, and that it can compute into something useful.</p><h4>Step 6: Validation of possibility</h4><p>Validation of possibility takes place from the base node towards the leaves. Given the expressions that are recognized, each node may be able to serve only a certain range of possibilities, and this should be enforced in the expression tree.</p><p>Take the right branch from the base node, for example. We have a multiplication operator between the result of an addition operator and the numeric constant 5. This, of course, makes no sense unless the result of the addition operator is also numeric. This, in turn, forces the addition operator to have a numeric result, which means that both its left branch (the result of a multiplication operator, which is numeric) and the left leaf (the parameter “z”) must also be numeric (or a numerically-convertible binary). It can make no sense, in this context, that the parameter “z” is a string.</p><p>On the other hand, if we look at the lowermost addition operator from the right branch of the left branch, we have a string constant added to a parameter. In this case, as per the rules of most software that your users will probably be familiar with, the parameter “s” can take on anything: the result will be its string representation appended to the end of the string constant.</p><p>IX.Math does this step, and checks that every node receives (from its base node) what data type(s) can result from it and, in turn, transmits the same to its child nodes. If it is unable to serve such a data type, the node would simply halt the validation process, as in such a case the expression is not logically sound.</p><p>Let’s take one example of an expression that is not logically sound:</p><blockquote>(“Part one of ” + x + “ was great”) ^ 5</blockquote><p>This expression does string concatenation, and attempts to raise the resulting string to the power of 5. Since the power operator cannot work on strings, the expression will not compute into a logically-valid tree.</p><h4>Step 7: Validation of certainty</h4><p>Once the validation of possibility ends, it may leave nodes (especially parameter nodes) still uncertain as to what data type they should contain. Let’s take one simple example:</p><blockquote>x + y</blockquote><p>This expression, as simple as it may look, is actually an interpreter’s nightmare. The addition operator, as per the rules of established mathematical and computer languages, is basically the most versatile operator: It can do mathematical addition, it can do string concatenation, it can do array stitching, etc.</p><p>When such an expression validates possibilities, it leaves both the parameters in an uncertain state, as it will probably be able to take in any parameter set that we can throw at it:</p><ol><li>x = 5, y = 7, Result = 12</li><li>x = 0101110111101001, y = 0000011110001001, Result = 01011101111010010000011110001001</li><li>x = “String is “, y = “beautiful”, Result = “String is beautiful”</li><li>x = 5, y = “ is the number!”, Result = “5 is the number!”</li></ol><p>…and so on.</p><p>It is therefore necessary to also do a bottom-up validation of our tree once we know for certain the data type that our parameters actually have.</p><p>Take example 1 and 3 above. The nature of the operation is entirely different if the operators are numerical types, than if they were string types. Yet the operator has the same symbol.</p><p>IX.Math solves this problem by reversing the flow of its validation once the parameter values are known, and the same process as above repeats in reverse node order. Again, if at any moment, there is an inconsistency between what the node value is and what it can be as per the requirements of its parent node, the whole process halts as, again, the expression cannot be logically sound.</p><h3>Fourth challenge: Computation</h3><h4>Step 8: Translation</h4><p>Once the expression tree is completely interpreted, it needs to be translated into something that can be executed.</p><p>It is by no means a coincidence that mathematical expressions are interpreted as a tree. .NET offers a great way to transform such trees into executable code by way of expression trees.</p><p>Before diving into this chapter, it would be a great idea to gat familiar with the concept of <a href="https://en.wikipedia.org/wiki/Binary_expression_tree">binary expression trees</a> first, and then Microsoft’s .NET implementation of <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/">expression trees</a>, as this knowledge is very important in order to understand what’s happening.</p><p>IX.Math’s trees are not strictly binary expression trees, nor are they Microsoft’s implementation, although they do get, eventually, compiled into them. The complexity of recognizable expressions and the amount of extensibility of the engine is far too great for either to be an option directly. For example, take a function that takes 3 parameters (fully supported in IX.Math): it’s no longer an option to call it a “binary” tree.</p><p>Instead, IX.Math keeps its own set of nodes in a memory cache somewhere, and only translates expressions into their machine-executable equivalent under either of the following situations:</p><ol><li>The expression doesn’t have parameters — it’s a constant expression, in which case a static value is calculated and cached</li><li>The expression only has parameters that can be of a certain specific type — the expression is cached as machine-executable</li><li>The expression has been sufficiently qualified so that there are no parameters that can have multiple data types — this would be the most typical scenario</li></ol><p>You will notice that scenario 1 is an interesting option: if the expression is a static one, then we may be able to statically calculate a value. This is done through a process called simplification: an expression has the chance to simplify itself, if conditions for it are met.</p><p>Let’s take the following expression as an example:</p><blockquote>x+10–2</blockquote><p>This expression is basically equivalent to writing x+8, and, indeed, if the + operator finds a set of leaf nodes that are both constant, it will attempt to simplify itself into a constant expression. By doing so, it may also prompt the node that itself is a leaf of to also simplify into a constant expression, and so on, until the root node gets that chance. Should that last root node be a constant expression as well, the entire expression is cached as a constant value that will be returned whenever the expression is interpreted.</p><p>This, of course, doesn’t happen should there be any nodes that, by definition, don’t offer constant values regardless of their input (like the <em>random</em> function), but that would be material for a different article.</p><p>The third case should be, by far, the most common case, and is also the point of this chapter: what happens when parameters are still ambiguous?</p><p>IX.Math caches expression nodes as the interpretation process has given them. When a set of certain parameter types are known, then an entire copy of the node set is created, long with its parameter registry, which then calculates the resulting type for parameters and for nodes that have them (see step 7). If an expression is reached that is not logically sound, IX.Math caches that invalid result, so that further requests with those parameter types are not interpreted again and again.</p><p>If an expression is reached that is logically sound, then IX.Math requests the root node to turn itself into an expression. That node, in turn, requests all its branches to turn themselves into expressions, and so on, and, when it has all the sub-expressions that it needs, it returns an expression containing them.</p><p>In the end, IX.Math creates a block expression out of the original expression which returns the result of the root expression, and looks inside its parameter registry to see what parameters it needs. The block expression becomes the body of a lambda expression that has the parameters held in the parameter registry as parameters of the expression itself.</p><p>Everything is then stored into a concurrent dictionary keyed by expression and parameter types, and the next step can begin.</p><h4>Step 9: Execution</h4><p>Execution is simple and straightforward: get the lambda expression delegate from the concurrent dictionary, and invoke it using its set of parameters.</p><p>IX.Math does one extra step in this case: if the expression does not appear to be logically sound, it returns the original expression. The logic behind this is that user input is complex, and IX.Math cannot decide on its own whether or not what it sees is an actual expression OR the user just wanted to write something mathematicky and the library just went haywire. So, a decision was made to simply return the original expression, as surely whoever wrote it will know best what to do with it.</p><h3>Conclusion, and further reading</h3><p>This has been all the foray into the world of recognizing mathematical expressions for today. I hope that the whole introduction made it clear that this topic is by no means inaccessible to developers, and may have even got you to try out doing it yourself. While not an easy or quick task, it’s nonetheless doable.</p><p>I will leave some resources for you to try out at the end, so that you can understand and find out more about this topic:</p><ul><li>Binary expression trees concept: <a href="https://en.wikipedia.org/wiki/Binary_expression_tree">https://en.wikipedia.org/wiki/Binary_expression_tree</a></li><li>Microsoft’s implementation of expression trees in .NET: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/">https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/</a></li><li>IX.Math source code: <a href="https://adrianmos.eu/Redirect?label=github-ix.math">https://adrianmos.eu/Redirect?label=github-ix.math</a></li><li>IX.Math documentation: <a href="https://adrianmos.eu/Pages/Projects/ixmath.md">https://adrianmos.eu/Pages/Projects/ixmath.md</a></li><li>IX.Math NuGet package: <a href="https://www.nuget.org/packages/IX.Math/">https://www.nuget.org/packages/IX.Math/</a></li></ul><p>If you would like to have more information on how other people (probably much smarter and more educated than myself) did mathematical expression interpretation, you could check out these resources:</p><ul><li>Edsger Dijkstra’s shunting yard algorithm: <a href="https://en.wikipedia.org/wiki/Shunting_yard_algorithm">Shunting yard algorithm — Wikipedia</a></li><li>Operator precedence parsing: <a href="https://en.wikipedia.org/wiki/Operator-precedence_parser">Operator-precedence parser — Wikipedia</a></li><li>LR parsers: <a href="https://en.wikipedia.org/wiki/LR_parser">LR parser — Wikipedia</a></li><li>Shift-reduce parsers: <a href="https://en.wikipedia.org/wiki/Shift-reduce_parser">Shift-reduce parser — Wikipedia</a></li></ul><p>Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58c600d37655" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/interpreting-mathematical-expressions-a-practical-example-58c600d37655">Interpreting mathematical expressions, a practical example</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software security during war]]></title>
            <link>https://medium.com/codex/software-security-during-war-876bcea6c3f1?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/876bcea6c3f1</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[war]]></category>
            <category><![CDATA[users]]></category>
            <category><![CDATA[software-security]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Thu, 05 May 2022 13:43:10 GMT</pubDate>
            <atom:updated>2022-05-05T13:43:10.609Z</atom:updated>
            <content:encoded><![CDATA[<h4>What software developers should be wary during war times, and a few of the most common attacks</h4><p>Software built by most developers is not designed to withstand techniques and attacks that can be useful during times of war. But insecure software, or even otherwise secure software with insecure use, can be used as a weapon.</p><p>Following are some pieces of advice that aim to minimize how much your software can be used against the people it is supposed to serve.</p><h3>Expect the DDoS</h3><p>One of the simplest attacks against a networked application is a Denial-of-Service attack: an attack that generates a flood of requests, in order to saturate the capacity of your servers. Your servers, just like any computer, have a limited set of resources, so, if they are used to analyse, process and respond to bogus requests, it will have less resources for responding to real ones.</p><p>The bigger brother, Distributed Denial-of-Service, is a more advanced and large-scale attack that involves many bogus clients, distributed across the globe. It is quick to bring smaller applications offline, as they simply cannot deal with the increased amount of traffic and requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYsQKruZk_RttRBZt9aiwg.png" /><figcaption>DDoS, crediting <a href="https://www.bleepstatic.com/images/news/u/1011204/Cryptocurrency/Ddos-attack-ex.png">bleepstatic.com</a> for the image</figcaption></figure><p>More advanced and significantly more effective forms exist, especially if the attacker knows a bit of how your application works, or can at least anticipate. Here is an example:</p><p>Let’s assume that your app serves an API URL that looks like this:</p><p><a href="https://mysite/api/apartments-for-sale/list?limit=30">https://mysite/api/apartments-for-sale/list?limit=30</a></p><p>What does that link tell you?</p><p>If I run it, and see that it does, indeed, return 30 results, the next thing that I’m requesting is:</p><p><a href="https://mysite/api/apartments-for-sale/list?limit=60">https://mysite/api/apartments-for-sale/list?limit=60</a></p><p>…and then:</p><p><a href="https://mysite/api/apartments-for-sale/list?limit=200">https://mysite/api/apartments-for-sale/list?limit=200</a></p><p>If I get back 60, then 200 results, respectively, I will progressively test the <em>limit</em> parameter until I either hit a hard cap, or I have found what I need. Should no hard cap be enforced, a DDoS with this URL:</p><p><a href="https://mysite/api/apartments-for-sale/list?limit=2000000000">https://mysite/api/apartments-for-sale/list?limit=2000000000</a></p><p>…will be absolutely devastating to your app, because it will both saturate your application server with requests, but also your database server and all the bandwidth in between by fetching probably all objects from the database with each request.</p><p>Will it help if you were to protect your application at business level and not allow a knowledgeable attack like described above to go through to the next level? Absolutely. The shorter the execution paths is until you figure out that a request is bogus and should be dropped, the better. If, say, you leave 30 as the default limit in the example above, and your UI will impose a limit of 200, it is safe to assume that normal user operation will not mind if you impose a hard cap on the <em>limit</em> parameter. Better yet, if you figure out that no accepted usage scenario would require more than 200 items, then maybe validating the parameter and returning HTTP 400 Bad Request right away instead of going through with limiting to the hard cap and fetching will aid greatly.</p><p>What about regular DDoS then? Let’s say you have your bases covered. There is still a lot to do, albeit proactively: you could split your traffic across multiple DNS/routing paths, thus meaning that, should you have a DDoS attack coming from, let’s take a completely random country, like Russia, all you need is to block or limit the path serving Russia, until the attack goes away.</p><p>Of course, real-life wartime scenarios are going to be a lot more large-scale than that. If your application is hit from all sides by government-level attacks, you pretty much stand no chance to keep your app still running. Better to just close it, in order to avoid racking up costs.</p><p>And always make sure that your core target audience knows what’s going on: if you are under attack, say so — users are more likely to be understanding with an application that tells them that it is under attack, than with one that works like crap. Of course, do so in a way that doesn’t scare them that their data has been compromised. Even if you have to close — do so knowing that you have tried your best to serve customers, but the attack was simply too much for you to handle.</p><p>And an even better piece of advice, especially for applications that have documents, laws, manuals and other such files: get CDNs and use permalinks. Once you’ve placed a file on the CDN, your application is no longer invisible if it is attacked. Even if the application succumbs to the giant wave of bogus requests, the CDN’s might still live on, and your data will still be served to your users by way of other applications, such as search engines. Your users will certainly appreciate the effort.</p><p>Let’s review a few pieces of advice:</p><ul><li>Protect your database with hard caps on data limits</li><li>Make execution paths as short as possible</li><li>Separate your traffic by region, or by any other meaningful way, even if that doesn’t imply more servers</li><li>Get some proper DDoS protection, such as user gateways, and flexible cloud solutions for serving your app</li><li>Put as much of your content as you can on CDNs — that’s why they exist</li></ul><h3>Updates are your friends</h3><p>One of the most problematic types of attacks on a system is an attack that does not necessarily involve someone doing something wrong, but malware spreading simply because of a flaw in the software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGZBlfqmDo1zsh8WHJ0mkw.png" /><figcaption>An iPhone. Currently up-to-date.</figcaption></figure><p>Back in 2003, when true broadband access was still young and many users were still rosy-cheeked enthusiasts convinced that the Internet is the place to be and nothing could go wrong in the world, a worm named <a href="https://en.wikipedia.org/wiki/Blaster_(computer_worm)">Blaster</a> quickly reminded us all that security should be on our minds. I personally remember how many of my friends’ Windows PCs quickly fell down after getting infected, and they all, in the true spirit of computer newbies, took to reinstalling Windows on their machine, only to be amazed that the worm reappeared quickly afterwards, as if something outside of their computer was spreading it. Hmm…</p><p>I, on the other hand, along with one other person, were unaffected. The other person was using a Linux machine (which was rare at the time, in my part of the world, for consumers), so that left only me: the only user of Windows Server 2003 with NAT and explicit port forwarding enabled. And I had all the updates installed.</p><p>As it turns out, Blaster used a vulnerability in Windows RPC that allowed it to infect other machines that were simply being connected to the Internet or an affected network, if they had the RPC service port open and listening. Of course, back in those times, most consumers did not have a good-enough understanding of ports and their use, and the idea of a firewall was new. I, on the other hand, used NAT, and a strategy to have all ports closed unless they needed to be open.</p><p>Nowadays, such an exploit could no longer take place, but the principle behind it remains: if there’s a flaw in your software, sooner or later it might end up compromising your security.</p><p>But the most important takeaway from the Blaster story, actually, is how it got created in the first place. Microsoft had issued a patch that would fix the exploit on May 28, and a public patch to deal with what Blaster used on July 16. Only afterwards, on August 11, the Blaster worm was released on the Internet. Notice that it had already been almost a month AFTER Microsoft had made their patch available to everyone and had included it in regular updates that the worm even appeared. The speed with which it spread shows exactly what lax attitude most people had about patching their systems and keeping them up-to-date.</p><p>It was only a year later, in 2004, that the worm itself waned from the public eye, finally defeated after massive patching attempts, massive uptake of new “firewall” software, and mostly global uproar.</p><p>And it all goes to prove one thing: keeping your system up-to-date as much as possible, while it may not be pleasant (especially on mission-critical systems) is a good way to ensure that your systems at least don’t have that many usable exploits.</p><p>Let’s review a few pieces of advice:</p><ul><li>Keep your systems up-to-date, at least with respect to security updates</li><li>Employ systems which have proper update channels, and keep up-to-date with those channels</li><li>If you have mission-critical systems that need to be feature-locked, long-term-support (LTS) versions exist on most major operating systems and most pieces of important software</li></ul><h3>Keep your hackers close, and your libs… even closer</h3><p>Libraries are a normal mainstay in software development. No software today, maybe with the exception of simple “Hello world!” applications, can claim to be truly stand-alone (and there’s a debate as to what those apps depend on, anyway, as a Java or .NET “Hello world!” still uses the underlying virtual machine/runtime). All software builds up on top of years of market experience, and relies on many libraries, inheriting their features, and also their bugs. And while, sometimes, the results are hilarious, oftentimes the results are disastrous.</p><p>In 2016, a NPM module named left-pad <a href="https://www.theregister.com/2016/03/23/npm_left_pad_chaos/">was removed from NPM</a>, along with many others, because of a decision by its author. Many major pieces of software would then see their builds failing because either them, or, most importantly, some other modules they depended on, had left-pad as a dependency.</p><p>The consequences of this occurrence were far and wide, many package/module/library repositories deciding that deletion of what has already been published should no longer be allowed. I personally only found out about the whole left-pad debacle after NuGet <a href="https://docs.microsoft.com/en-us/nuget/nuget-org/policies/deleting-packages">decided against package removal</a>, and must admit that, before that moment, I had taken everything for granted, and not once had I considered safeguarding my dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*wHqRmz1WkZNHavLlu9yvrg.png" /><figcaption>Have your dependencies as local as you can</figcaption></figure><p>Obviously, the key takeaway here is to make sure that what you depend on is also accessible. Imagine, if you will, that you lose the ability to retrieve some dependencies because a malicious party has denied access to them. What would you do? Nothing that tragic if it was just a build dependency, but seriously tragic if your application had a dependency that it needed to load from an external source at runtime, like many websites load jQuery or Bootstrap.</p><p>So let’s review a few pieces of advice:</p><ul><li>Always keep a copy of your dependencies. There are many ways to create a federated repository that will create safe copies of your dependencies, such as <a href="https://jfrog.com/artifactory/">jFrog’s Artifactory</a></li><li>Make sure that you have the source code for your open-source dependencies, in case you discover a vector for attack against your software in them, and the original dependency/developer is unavailable</li></ul><h3>Track friendly</h3><p>Now, while the above sections deal with advice that is good in any situation, this section deals specifically with danger that is mostly present during wartimes, or terrorist attacks.</p><p>Never underestimate the power your software has to track things, and never underestimate the power that an attacker can gain if it gets access to that tracking.</p><p>And if your software is being used in a war zone, or in countries that are known for violating basic human rights on ethnic, religious or political grounds, please turn off your tracking. Whatever you gain out of that tracking can only be considered blood money.</p><p>Let’s think of the following scenario: your software keeps track of your users’ location, and whenever they are live, and is helpful for coordinating groups of people. During preparation for a terrorist attack, your software gets compromised, and the attackers get access to the live locations of your users. The result should be obvious.</p><p>It doesn’t even matter, in that scenario, whether or not the attackers get access to continuous real-time location data. It matters that they have access to historical location data, from which they can extrapolate. If your users tend to congregate around a specific landmark every weekday for years, it is highly likely that they will continue to do so. An attacker can extrapolate from this data and seriously refine the list of locations to target.</p><p>Let’s take a different example. Let’s assume that a political cleansing is being planned. Your software is known for tracking user preferences, and attempting to group users together based on shared interests. The offending party wants to ascertain a certain subset of users for that cleansing campaign. By examining algorithms that your software uses (and, believe me, this is not as out-of-reach for an attacking team backed by an entire country’s government as you may think), the offending party will be able to create fake accounts with preferences identical to those which they target, that will then easily be grouped to real ones by your own algorithms. By introducing many fake accounts in many ingress points within your social application, pretty soon the circles of each of those fake accounts will inevitably start to intersect, and their intersection will lead to those people that will be most likely targets: those that are influential-enough to matter on a local or regional scope, or who are of great importance to the political doctrine that is being targeted for cleansing, but are not high-profile-enough that their sudden disappearance would cause an immediate eruption of a scandal or revolution. In other words, don’t target the figureheads, but target those who are actually making the cogs turn.</p><p>But let’s say that your software isn’t a social network or something that can be used as a people tracker. Still, think about it for a second: does every piece of information that you track actually matter? Is the phone number of your users, for instance, that important to you? After all, maybe your app can’t track your users, but maybe somebody else can: in this case, the mobile network operator, which can, given a phone number, either willingly or not, track it to an approximate location, and can even intercept communication. Attackers may not need your software for much, but, in targeting specific people, every piece of information counts.</p><p>Let’s say that you don’t associate a phone number with a person, but you do associate it to an e-mail address, or a screen handle, or any other piece of information. Attackers may not find out the identity of a person from you, but they may find the correlation, and attack a different application which also correlates data, and is able to make the connection to a person they’re targeting. Lo and behold: not one of the applications is single-handedly responsible for the fact that a tyranny was able to successfully target an individual, but all of them, collectively, were.</p><p>Can you do away with not tracking user information in war zones or places with a record of human rights violations? Then you should, because in the vastness of human action, you may never know who needs that one piece of information that you have, but consider trivial.</p><p>Key takeaways:</p><ul><li>Only track as much as you absolutely need to for users coming from war zones; you never know what information might put them in danger</li><li>Correlate as little as you absolutely need to from your users in war zones – any association may end up creating a connection to others, which will, in turn, create another, up until enough connections can be made that a single entity can be identified</li><li>Stop tracking and delete tracking data if a subset of users is suddenly put in danger – you won’t be able to always anticipate when that happens, so take some time to set up a cleansing service for your data, just in case</li><li>Unless critical for your business, or mandated by law, don’t collect that sort of information that can later be used to track or spy on people via other more accessible means, such as phone numbers</li></ul><h3>Everybody counts</h3><p>This is a set of advices that, sadly, many people are completely oblivious to, even though I personally struggle to understand how they are not completely obvious.</p><p>In 2010, software security researchers in Belarus managed to identify what would later be known as <a href="https://en.wikipedia.org/wiki/Stuxnet">Stuxnet</a> — a worm that targeted a very specific SCADA system made by Siemens. The worm would spread through various means and mostly indiscriminately, however it would not do much to the infected machine (apart from rootkitting it), unless it detected a very specific Siemens SCADA software that is mostly used for heavy industrial equipment. If that happened, it would infect that software, and would determine it to put specific code into the PLCs of the devices it was controlling, and would make it interfere with its operation in potentially destructive ways.</p><p>The first indication that this was a product of cyberwarfare was that it was seriously heavy on exploits. It used no less than 4 zero-day exploits in order to spread and infect, which proved the determination of the developer to get that code running on as many target machines as possible, at any cost.</p><p>The second indication was how narrow the surface of attack it had. While it would indiscriminately infect any computer it could, its core action (that of infecting the SCADA system) would only performed if particular software was found, and only if that software was connected to PLCs with specific characteristics, that had specific hardware modules from specific vendors installed, and only if it were operating under certain very specific parameters. Coincidentally, the specific parameters of gas centrifuges used in the process of Uranium enrichment.</p><p>The third clue, and what tied up all of this together, was that it mostly infected computers in Iran, just as Iran was winding up its Uranium enrichment programme.</p><p>But the biggest deal with Stuxnet is actually that it is a worm that managed to jump the air gap — meaning that it could infect computers that are not connected to the Internet. And the story of how that happened is actually the moral of this section. The following paragraph is speculation on how the actual events may have happened, but the main attack path is real.</p><p>It turns out that Iran, being under embargo, could not implement an industrial process of Uranium enrichment on its own, so it resorted to secretly purchasing industrial equipment and also hired specialists from Russia as contractors. Because the Iranian systems were air-gapped and could not be infected, the attackers focused on the more accessible Russian contractors, probably deducing that, since their cultural and operational patterns differed, as well as because they were the ones who needed to set things up, they were more likely to bring their own personal equipment in the air-gapped networks in order to be able to work. The plan was successful, and infected Russian machines generated infected USB drives, which then infected the air-gapped Iranian systems when they were plugged in.</p><p>The infection via USB is a known and proven method of infection, and, while the exact attack path is probably unknown even for the attackers themselves, the above speculation is considered the most likely way in which Iranian air-gapped systems were infected. But there exists an even stranger (albeit far more plausible, even though it is basically just an urban legend) story as to how it may have happened.</p><p>As the legend goes, like pretty much all industrial facilities, the ones in Iran have parking lots. In one of those parking lots, a mole working for a foreign intelligence service “accidentally dropped” a few USB sticks early in the morning here and there, in key locations where they would be certain to be noticed by other people. Unsuspecting employees noticed said USB sticks and picked them up and, trying to figure out who they belonged to, plugged them in to their computers. However, this being in the morning, when employees were going in, they, of course, used their work machines, thus allowing the worm easy access to the air-gapped network.</p><p>Now, of course, the above paragraph is actually just as stated: a legend. Things could not have happened like that in this particular occasion: it can be safely assumed that such facilities are heavily guarded, and someone would notice someone repeatedly “accidentally” dropping USB sticks, and a thorough analysis (like Russian contractors could ask their multiple serious software security firms to do) would have likely exposed the entire thing before it had a chance to do any damage, not to mention outing the mole. But this particular legend did inspire an entire cultural meme, and, at Black Hat 2016, <a href="https://en.wikipedia.org/wiki/Elie_Bursztein">Elie Bursztein</a> presented <a href="https://www.youtube.com/watch?v=ZI5fvU5QKwQ">a study that demonstrated</a> that this type of attack (called a “USB Drop”) is actually very effective against a civilian population.</p><p>Why would this happen? And, more importantly, what can we do to not have this happen?</p><p>There is a tendency to put the blame squarely on the employees that do apparently dumb things that compromise the security of our systems. But, as Jayson E. Street pointed out in a <a href="https://youtu.be/JsVtHqICeKE?t=2180">DEFCON presentation</a> (the link points to the exact segment, but the entire talk is worth watching, albeit only tangent to the point this section is trying to make): it’s time we phased out “stupid users” from our security vocabulary, and it’s time that we started treating everybody as part of the security ensemble of a system. Everyone, meaning workers, both blue- and white-collar, security, management, administration, external contractors, cleaning crew… everyone should be not only prepared to handle possible threats, but also empowered to do so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7-XiiroCy-Xyw4l2Q6riQ.jpeg" /><figcaption><a href="https://www.pexels.com/photo/man-wearing-jacket-and-peaked-cap-grayscale-photo-1119152/">Photo by Brett Sayles</a> from <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><p>Imagine how differently this would have played if, say, the centrifuge contractors would have routinely scanned their computers and devices. How unnoticed do you think network communication, the kind that is required to properly disseminate the worm, would go with a serious setup, assuming that it could go out at all? How unnoticed do you think attempting to install a new device driver (like the worm does) would be if the users that inadvertently did that actually took some time to look towards the screen at what they were installing? How different would the legend play out if people would recognize that a “misplaced” USB stick might be misplaced for a reason, and would simply say “I’ll let IT security handle this, after all, that’s exactly where anyone would think to go if they lost a USB stick”?</p><p>There’s one major point that comes up out of this segment:</p><ul><li>Train and empower anyone that you come into contact with to be security-aware, and to not hesitate to report anything they feel is out of place</li></ul><h3>Wrapping up</h3><p>War is a messy business, there is no doubt of this in anyone’s mind by now. But if you’ve managed to get this far reading this article, you will have noticed that the points I’m trying to make didn’t really talk that much about war, and they didn’t really talk that much about software, either. Why, then, did I present it to you?</p><p>Because what goes unnoticed or barely scratches the peripheral eyesight of the public during times of peace, may end up mattering a lot during times of war.</p><p>I began my article with DDoS for a good reason. At the time of writing this article, <a href="https://en.wikipedia.org/wiki/2022_Russian_invasion_of_Ukraine">Russia’s 2022 invasion of Ukraine</a> is ongoing. On February 15th, I posted this on Facebook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*bsCJzTlDR0eORNGnNoMZ7Q.png" /><figcaption>Educated guess</figcaption></figure><p>As it turns out, I was correct. The invasion was preceded by serious attacks on the IT infrastructure of Ukraine, with blackouts on some sites and overall disturbance, culminating on February 23rd 2022, when data-wiping malware was deployed and the intensity of cyberattacks managed to knock some Ukrainian government websites down. Russia invaded in the early morning of February 24th. What followed, you all know.</p><p>I then repeatedly tried to make the point that anything can be used against you, even if you don’t realize it. In the particular conflict, the Ukrainians learned this fast, and managed to adapt their strategies, and so did all the countries supporting them. Russians, on the other hand, both managed to cause incredible mayhem using well-played social engineering that had been going on for a long time, as well as both brute and elaborate attacks on the cyber-infrastructure of Europe. Thankfully, though, this also worked seriously against them, as their own cybersecurity misadventures led to some pretty embarrassing situations.</p><p>And last, but not least, I was trying to make the point that one may not know what kind of threats to expect, and from whom, and what will come next, so it is always wise to try and instil a proper education and a serious sense of empowerment in your employees (read “citizens” if you are a government representative), in order to get them to, as much as humanly possible, not fall into the wise traps of enemies, whoever they might be.</p><p>In the end, I’m not sure how many lives could have been saved if all of the above advice would have been followed throughout the short and tumultuous history of humans and computers. But I am absolutely certain that the amount would have been worth the effort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=876bcea6c3f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/software-security-during-war-876bcea6c3f1">Software security during war</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Doing away with passwords in ASP.NET]]></title>
            <link>https://medium.com/codex/doing-away-with-passwords-in-asp-net-fa65bd5fb601?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa65bd5fb601</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[password-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[passwordless]]></category>
            <category><![CDATA[aspnet]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 02:03:52 GMT</pubDate>
            <atom:updated>2022-02-24T02:03:52.135Z</atom:updated>
            <content:encoded><![CDATA[<h4>Maybe alternatives should have more traction, and users less headaches.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*wuJW9PC9r7v1KK154LLnzw@2x.jpeg" /><figcaption>By <a href="https://unsplash.com/@moneyphotos">olieman.eth</a> on <a href="https://unsplash.com/photos/r8VbpgMS6Uc">Unsplash</a></figcaption></figure><p>When I first heard about Medium, long before I actually joined, I remember being blown away by its login system. I watched my boss at the time log in to his account by checking his e-mail, and using that link, and I asked “Does it not require any password?”</p><p>Years later, after doing a lot of reading on how to secure websites, applications and devices, I came to appreciate the many advantages that this approach offers to security.</p><h3>Rationale</h3><p>One of the most difficult security tasks for anyone developing an application, a website, or otherwise any other piece of software that deals with authenticating a user is reliably and, especially, securely authenticating that user.</p><p>Handling users’ passwords is an operation that exposes said password to numerous possible vectors of attack:</p><ul><li>A user has to type the password, making it vulnerable to keyloggers</li><li>The client app (be it the browser, or a maybe a mobile app) needs to send the password to the server, so any number of man-in-the-middle- ort evil-twin-like techniques will work, especially if the user isn’t particularly security-savvy</li><li>The server receives and needs to validate passwords, so, at least in one instance, some form of password is stored somewhere in the server memory, making it vulnerable to more advanced vulnerabilities</li><li>The password needs to be either stored, or have a hash stored, so that it can be validated at a later time, thus making it vulnerable to attackers if this operation is not done properly</li></ul><p>It should be obvious by now that the surface of attack for passwords is huge, and, although, in recent times, it has become harder and harder to successfully attack using either of the aforementioned vectors, we are still left with a giant elephant in the room:</p><p>Users.</p><p>It doesn’t matter how secure your password handling mechanism is if the user chooses “password” as his password. It makes no difference that you have a password policy that enforces really strong passwords, if the hapless employees of your client write their passwords on sticky notes, in plain sight. It matters not if you have multi-factor authentication, if your unsavvy users can’t distinguish between an actual login page and a phishing page.</p><p>Of course, this is nothing new. Major players in the field have had real trouble with keeping things secure for their users. And most such players have invested serious amounts of time and effort into securing things as much as humanly possible. Take the power and flexibility of an <a href="https://en.wikipedia.org/wiki/Active_Directory">Active Directory</a> domain, for example, and imagine, by looking a bit through its internal concepts and protocols, how many challenges it has had across the years. Or just take <a href="https://www.facebook.com/">Facebook</a>, with so many major data breaches that there are <a href="https://selfkey.org/facebooks-data-breaches-a-timeline/">pages</a> <a href="https://firewalltimes.com/facebook-data-breach-timeline/">dedicated</a> to <a href="https://www.forbes.com/sites/kateoflahertyuk/2021/04/06/facebook-data-breach-heres-what-to-do-now/">analysing</a> <a href="https://haveibeenpwned.com/PwnedWebsites#Facebook">them</a>. Even Apple, who has emphasised security as one of its top missions, was not immune.</p><p>So any developer of a new application should probably ask themselves: Am I knowledgeable ad experienced enough to figure this out? Can my solution really be on par with authentication solutions with a long and established history? And the answer is, in most cases, probably not.</p><p>Don’t get me wrong, software development and architecture skill is most likely not lacking in anyone brave enough to take on such a challenge. But one developer, or a small team, simply does not have the time or resources to implement (and especially maintain!) secure solutions in the same way as the major players in the field. And having an attitude like “Well, Facebook is huge, who’s going to come after lil’ ol’ Jackson O’Coder’s website?” doesn’t help a bit: keep in mind that Facebook has the resources to survive gigantic data breaches (as it has in the past multiple times), but only one small one may be enough to wipe your business off the face of the Earth. You might end up with nobody thinking that you’re worth their time, but, usually, that usually also means that your software also doesn’t bring in many customers.</p><h3>Why do away with passwords, after all?</h3><p>So, after reading the rationale, you’re still not yet convinced that, should a better option exist than to use passwords, you should definitely take it, let’s go through a set of advantages of doing away with passwords:</p><ol><li>Not using passwords will not expose them in case of a breach. This is a significant advantage for the user, since most people <a href="https://tech.co/news/most-people-reusing-passwords-multiple-sites">reuse</a> <a href="https://www.techspot.com/news/91388-most-people-reuse-passwords-across-multiple-sites.html">their</a> <a href="https://www.techradar.com/news/most-people-reuse-the-same-handful-of-passwords-heres-why-thats-a-problem">passwords</a> on multiple applications, so, chances are good for an attacker that gains access to one password, that they will have gained access to most applications that person is using</li><li>Not using passwords seriously lowers the amount of expended resources, since there is no need for extra encryption and/or hashing, as well as no need to write code for that, or to allot storage space</li><li>Not using passwords does not hinder the ability of any framework to correctly authenticate a user in the slightest, nor does it prevent that user from maintaining a session</li><li>Not using passwords seriously reduces liability in case of data breaches, and also seriously limits the usefulness of data collected by attackers. This is the argument that will most probably get the legal and financial department of any business up from their seats cheering, especially on applications that do not collect much data from their users</li></ol><p>Now, further advantages come from the specific way in which you may choose to do away with passwords. As an ASP.NET developer, like myself, there are ready-made solutions and documentation for external login providers, like <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins">Facebook</a>, <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins">Google</a>, <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/twitter-logins">Twitter</a>, <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins">Microsoft</a>, <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-aspnet-core-webapp">Azure AD</a>, <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth">Windows Authentication</a> or <a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/other-logins">other generic providers</a>, and even multi-factor authentication and TOTP schemes. I won’t go into details here, but suffice to say that delegating authentication to a third party with seriously more horsepower than your team of developers has its advantages, in development efficiency, security and also user engagement.</p><p>However, this article is not about delegating to a third party. There is heap of documentation for that already. But, as advantageous as they are, they have one serious drawback: they are third parties, and, therefore, make your application enter the realm of regulations on data protection, tracking and privacy. And this would be totally fine for your app, so, by all means, go for this approach if it suits your purpose. But if it does not, a separate approach may be needed.</p><h3>Enter personal effects</h3><p>It is safe to assume that, if someone uses your software, they have access to at least one email address, and probably one phone number. And it is almost guaranteed that they will be using a smartphone of some sort.</p><p>One of the greatest security improvements in latest years was the incorporation of the smartphone in everyday life. It made things more secure by many a number of things, but the most important security improvement was actually not a security improvement at all: the ability to have email at everyone’s fingertips.</p><p>As such, gone were the days in which one would hook up laptop, connect it to a password-less, public Wi-Fi hotspot, and navigate to a more-or-less (usually less) secure web page to check their fancy domain e-mail like hotshot69@smartypants-email.com. Most users have since navigated away to a few standardised providers, which could, then, properly start treating the network between a user’s device and their servers like the insecure and most likely hostile environment that it actually is. By focusing security on a few sets of providers, both those providers and the smartphone makers have managed to make even email secure enough.</p><p>And, on top of that, there was the matter of the phone network, with every device guaranteed to have a tightly-regulated communication channel that is seriously difficult to attack in a practical way without serious investment of money and time.</p><p>And, on top of all, there’s the matter of the ongoing competition to make devices as secure as they can possibly be. Sandboxing, locking mechanisms, internal security, encryption, find-my-device techniques, remote nuking options, etc., all of these work in concert to make that one handheld pocket-stored device everyone has the ideal multi-factor-in-one authentication device.</p><h3>So, let’s do it</h3><p>Now that I’ve explained how we’re approaching, I will make a very short code introduction into how to properly do this in ASP.NET. For this purpose, I will assume that we’re using .NET 6, and that you already have some knowledge on how to properly handle a basic ASP.NET application.</p><p>While I will be using e-mail to try to authenticate the user, anything else you might wish to use (such as SMS, TOTP or push notifications) should work using the same principles.</p><h4>First steps</h4><p>We first need to set up services for identity and authorization in our DI container:</p><pre>// Authentication and authorization<br>services.AddIdentity&lt;IdentityUser&lt;int&gt;, IdentityRole&lt;int&gt;&gt;()<br>    .AddEntityFrameworkStores&lt;MyDbContext&gt;()<br>    .AddDefaultTokenProviders();<br> <br>services.AddAuthorization(<br>    options =&gt;<br>    {<br>        options.AddPolicy(&quot;AdministratorsOnly&quot;,<br>            policyBuilder =&gt;<br>            {<br>                policyBuilder.RequireRole(&quot;Administrators&quot;);<br>            });<br>    });</pre><p>Please note that I am using standard IdentityUser and IdentityRole entities with integer primary keys, in an Entity Framework data store with default token providers. Feel free to adapt this to your own situation. In my case, the MyDbContext class was simply defined as:</p><pre>public class MyDbContext : IdentityDbContext&lt;IdentityUser&lt;int&gt;, IdentityRole&lt;int&gt;, int&gt;</pre><p>I am also adding an “AdministratorsOnly” policy as an example policy (checks whether the user is part of the “Administrators” group), which, of course, you can adapt to your own needs.</p><p>Next is to add the required middleware:</p><pre>app.UseAuthentication();<br>app.UseAuthorization();</pre><p>As per middleware indications, in case routing and endpoints are used, these need to be added between the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.endpointroutingapplicationbuilderextensions.userouting">UseRouting</a> and the <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.endpointroutingapplicationbuilderextensions.useendpoints">UseEndpoints</a> or Map… methods (<a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.razorpagesendpointroutebuilderextensions.maprazorpages">MapRazorPages</a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.controllerendpointroutebuilderextensions.mapcontrollers">MapControllers</a>, etc.).</p><p>And that’s all the plumbing, we’re ready to go implementing.</p><h4>Simple login page</h4><p>We need but a simple form with exactly one field to have a login page:</p><pre>&lt;h1&gt;Log in&lt;/h1&gt;<br> <br>&lt;form method=&quot;post&quot; class=&quot;container-fluid&quot;&gt;<br>    &lt;div class=&quot;row&quot;&gt;<br>        &lt;div class=&quot;col-sm-12 col-md-4 col-lg-3 col-xl-2&quot;&gt;<br>            &lt;label for=&quot;email&quot; class=&quot;form-label&quot;&gt;Your e-mail address:&lt;/label&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;col-sm-12 col-md-8 col-lg-9 col-xl-10&quot;&gt;<br>            &lt;input type=&quot;text&quot; name=&quot;email&quot; id=&quot;email&quot; placeholder=&quot;my.name@email.com&quot; class=&quot;form-control&quot; /&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-12 align-content-end&quot;&gt;<br>                &lt;input type=&quot;submit&quot; class=&quot;btn btn-primary&quot; value=&quot;Log in&quot;/&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/form&gt;</pre><p>Mind you, I am using bootstrap classes with responsive layout, which is what a template ASP.NET application uses. Obviously, feel free to adapt this to your own needs.</p><p>The form posts one field exactly, the email address to log in. I am using a Razor page to host this, and a model behind the scenes to capture the email value:</p><pre>public class LoginModel : PageModel<br>{<br>    private readonly LoginValidationService loginService;<br> <br>    public LoginModel(LoginValidationService loginService)<br>    {<br>        Requires.NotNull(out this.loginService, loginService);<br>    }<br> <br>    public void OnGet()<br>    {<br>    }<br> <br>    public async Task&lt;IActionResult&gt; OnPost(<br>        PostModel postModel,<br>        CancellationToken cancellationToken = default)<br>    {<br>        if (!this.ModelState.IsValid)<br>        {<br>            return this.Page();<br>        }<br> <br>        await this.loginService.CommitLogin(postModel.Email, cancellationToken);<br> <br>        return this.RedirectToPage(&quot;LoginMessageSent&quot;);<br>    }<br> <br>    public class PostModel<br>    {<br>        [BindProperty(Name = &quot;email&quot;)]<br>        [MaxLength(255)]<br>        [Required]<br>        public string Email { get; set; }<br>    }<br>}</pre><p>Let’s dissect this a bit.</p><p>First off, we have a LoginValidationService instance (we will be creating this one later on, so let’s just take it as it is for now), which is injected and validated through the constructor.</p><p><em>Note: Requires.NotNull is a contracts-like validation and initialization method part of </em><a href="https://www.nuget.org/packages/IX.StandardExtensions/"><em>IX.StandardExtensions</em></a><em> NuGet package.</em></p><p>We have no reason to do anything special for the GET method, as the magic happens when the form on the page posts back via the POST method.</p><p>When handling the POST method, we get a model containing only the email field (as defined in the PostModel class) and, if the model is valid, invokes the CommitLogin method with the email address, then redirects the user to some page that would tell him to check his email.</p><p>At this stage, we are only interested in getting the user’s email so that we can generate some secret code and a link to send to the user. This is only the first step, and the user’s visit to said link will trigger the second step of the login process.</p><h4>Login and validation controller</h4><p>Simply for the sake of diversity in my example, I chose to implement the login validation link handler as a view-less MVC controller. A Razor page will work just as well, so feel free to adapt as you see fit, but I just felt like it was slightly more work.</p><p>My code looks like this:</p><pre>[Route(&quot;Login&quot;)]<br>public class LoginController : Controller<br>{<br>    private readonly LoginValidationService lvs;<br> <br>    public LoginController(LoginValidationService lvs)<br>    {<br>        Requires.NotNull(out this.lvs, lvs);<br>    }<br> <br> <br>    [HttpGet(&quot;Validate&quot;)]<br>    public async Task&lt;IActionResult&gt; ValidateLogin([FromQuery] string email, [FromQuery] string code)<br>    {<br>        var result = await this.lvs.ValidateLogin(<br>            email,<br>            code);<br> <br>        if (result)<br>        {<br>            return this.Redirect(&quot;~/&quot;);<br>        }<br> <br>        return this.RedirectToPage(&quot;/Forms/Authentication/LoginFailed&quot;);<br>    }<br>}</pre><p>We have the same LoginValidationService injected, and we have the ValidateLogin action method that will invoke its ValodateLogin method with what is received as query string parameters by the user: the code, as well as the email address. We also handle the GET method, as no self-respecting email client will do a proper and secure POST for you without first alerting the user, and we don’t want unnecessary complications.</p><p>After receiving the result of the validation (which, in this case, is a Boolean value), the controller redirects the user to either a page telling him the login failed, or to the home page. Feel free to adapt to your own needs.</p><p>That’s all. Now, let’s move on to the LoginValidationService class.</p><h4>Login validation service</h4><p>Now the real magic happens. But, before it can, we need to define a class with quite a lot of fields:</p><pre>public class LoginValidationService<br>{<br>    private const string LoginValidationKey = &quot;LOGINVALIDATION:{0}&quot;;<br> <br>    private readonly IConfiguration config;<br>    private readonly IWebHostEnvironment host;<br>    private readonly IHttpContextAccessor httpContextAccessor;<br>    private readonly IAppCache cache;<br>    private readonly UserManager&lt;IdentityUser&lt;int&gt;&gt; userManager;<br>    private readonly SignInManager&lt;IdentityUser&lt;int&gt;&gt; signInManager;<br>    private readonly ILogger&lt;LoginValidationService&gt; logger;<br> <br>    public LoginValidationService(<br>        IConfiguration config,<br>        IWebHostEnvironment host,<br>        IHttpContextAccessor httpContextAccessor,<br>        IAppCache cache,<br>        UserManager&lt;IdentityUser&lt;int&gt;&gt; userManager,<br>        SignInManager&lt;IdentityUser&lt;int&gt;&gt; signInManager,<br>        ILogger&lt;LoginValidationService&gt; logger)<br>    {<br>        Requires.NotNull(out this.config, config);<br>        Requires.NotNull(out this.host, host);<br>        Requires.NotNull(out this.httpContextAccessor, httpContextAccessor);<br>        Requires.NotNull(out this.cache, cache);<br>        Requires.NotNull(out this.userManager, userManager);<br>        Requires.NotNull(out this.signInManager, signInManager);<br>        Requires.NotNull(out this.logger, logger);<br>    }</pre><pre>[... rest of class ...]<br>}</pre><p>Let’s take all of them in turn.</p><p>We will probably need some sort of configuration access, so we inject the IConfiguration interface as the easiest way of accessing it. More <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/">documentation on ASP.NET configuration</a> over at Microsoft Docs.</p><p>We want to have some information on the current host, as chances are that you may not want to send emails (or that many emails) from a developer machine. You will see how that happens later.</p><p>We will need access to the HTTP context, and we get access to that via injecting the IHttpContextAccessor. More <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context">documentation on injecting and using ASP.NET HttpContext</a> over at Microsoft Docs.</p><p>We then do a rather interesting trick. How exactly this is performed depends on what your actual needs are, so you may need to adapt this part to suit your business needs. But for a very simple application, this will work:</p><p>We need to generate a code that will be available to the user for 10 or so minutes, and disappear afterwards. We don’t necessarily need to store it, just offer the application a simple way to access it, while it’s not yet expired. And we don’t expect a plethora of such codes to need to be valid at the same time. This sounds exactly like how a cached object behaves, so, naturally, a cache (in our particular cache an in-memory cache) will do the trick. I am using <a href="https://www.nuget.org/packages/LazyCache/">LazyCache</a>, and inject IAppCache.</p><p>An important thing to note now is the constant LoginValidationKey. It will be used in order to work with our IAppCache instance.</p><p>We then inject the UserManager, and please note that it has the user class mentioned above as a type parameter. We will be using this to check whether the user has logged in before, and to create a database entry for it if not.</p><p>Afterwards, we will use SignInManager to instruct ASP.NET to actually do the login, and, finally, the ILogger to give us the opportunity to log things if needed.</p><p>So let’s see how this works.</p><h4>First stage login</h4><p>Let’s analyse the code for the first stage of the login:</p><pre>public async ValueTask CommitLogin(string emailAddress, CancellationToken cancellationToken = default)<br>        {<br>            // Create login key<br>            string key = string.Format(<br>                LoginValidationKey,<br>                Requires.NotNullOrWhiteSpace(emailAddress));<br> <br>            // Validate that there hasn&#39;t already been a login<br>            if (this.cache.TryGetValue&lt;string&gt;(<br>                    key,<br>                    out _))<br>            {<br>                return;<br>            }<br> <br>            // Generate code<br>            string loginCode = DataGenerator.RandomAlphanumericString(50);<br> <br>            // Save code to cache<br>            this.cache.Add(key, loginCode, new DateTimeOffset(DateTime.Now.AddMinutes(10)));<br> <br>            // Send e-mail message<br>            if (this.host.IsDevelopment())<br>            {<br>                this.logger.LogDebug(&quot;Message sending on login was triggered, but will not run on a development environment.&quot;);<br> <br>                return;<br>            }<br> <br>            try<br>            {<br>[... initialize email sending service here ...]</pre><pre>                var httpContext = this.httpContextAccessor.HttpContext ?? throw new InvalidOperationException(&quot;No HTTP context, cannot proceed.&quot;);<br>                var linkGenerator = httpContext.RequestServices.GetService&lt;LinkGenerator&gt;() ?? throw new InvalidOperationException(&quot;No link generator, cannot proceed.&quot;);<br>                var website = linkGenerator.GetUriByName(httpContext, &quot;default&quot;, new RouteValueDictionary());<br>                var loginValidateAddress = linkGenerator.GetUriByAction(<br>                    httpContext,<br>                    &quot;ValidateLogin&quot;,<br>                    &quot;Login&quot;);<br>                var loginPageAddress = linkGenerator.GetUriByPage(httpContext, &quot;/Forms/Authentication/Login&quot;);<br> <br>                var subject = $&quot;Login request for {emailAddress}&quot;;<br>                var plainTextContent = string.Format(<br>                    @&quot;Thank you for your interest in the {2} site.<br> <br>Please login using the following link (valid for 10 minutes):<br> <br>{3}?code={0}&amp;email={1}<br> <br>This link should validate your session, and should redirect you towards the home page.<br> <br>If you cannot use this link, this means it might have expired, so please try to log in again.&quot;,<br>                    loginCode,<br>                    emailAddress,<br>                    website,<br>                    loginValidateAddress);<br>                var htmlContent = string.Format(<br>                    @&quot;&lt;h1&gt;Login&lt;/h1&gt;<br>&lt;p&gt;Thank you for your interest in the &lt;a href=&quot;&quot;{2}&quot;&quot;&gt;{2}&lt;/a&gt; site.&lt;p&gt;<br>&lt;p&gt;Please login using the following link (valid for &lt;strong&gt;10 minutes&lt;/strong&gt;):&lt;/p&gt;<br>&lt;p&gt;&lt;a href=&quot;&quot;{3}?code={0}&amp;email={1}&quot;&quot;&gt;{3}?code={0}&amp;email={1}&lt;/a&gt;&lt;p&gt;<br>&lt;p&gt;...or copy and paste it into a browser&#39;s navigation bar.&lt;/p&gt;<br>&lt;p&gt;This link should validate your session, and should redirect you towards the home page.&lt;/p&gt;<br>&lt;p&gt;If you cannot use this link, this means it might have expired, so please try to &lt;a href=&quot;&quot;{4}&quot;&quot;&gt;log in again&lt;/a&gt;.&lt;/p&gt;&quot;,<br>                    loginCode,<br>                    emailAddress,<br>                    website,<br>                    loginValidateAddress,<br>                    loginPageAddress);<br> <br>[... send the email with the content ...]<br>            }<br>            catch (Exception e)<br>            {<br>                this.logger.LogError(e, &quot;Could not send the login email due to an exception.&quot;);<br> <br>                return;<br>            }<br>        }</pre><p>Long, but simple, isn’t it?</p><p>First, create a proper cache key from the email address, check if one is already valid, if not then create the code (<em>note: DataGenerator.RandomAlphanumericString is part of the </em><a href="https://www.nuget.org/packages/IX.StandardExtensions/"><em>IX.StandardExtensions</em></a><em> package</em>). We’ll save the code in the cache using the already-existing key. We check whether or not we are on a development environment (such as a developer machine, in order to not go through with email, in order to avoid spamming the SMTP server), and, if we aren’t, we can proceed to create some links.</p><p>Please note how we’re using the HTTP context. We are getting a LinkGenerator instance from it, and we’re using that to generate links. Why do we need to tie this to a HttpContext?</p><p>The answer lies in how ASP.NET (and web application frameworks in general) can generate links. If, for instance, I am accessing the application using www.myawesomeapp.com, then that’s what we need to make links relative to. If, however, we are using a staging server, such as staging.myawesomeapp.com, then we need to make the links relative to that, otherwise they won’t work. We also need to think: are we using HTTP or HTTPS (although this will become an irrelevant question pretty soon)? and so on. We could just hardcode some addresses in the configuration file(s), but that implies maintaining those links, and that is simply a useless endeavour since we have this working solution.</p><p>Next up is the actual email sending, with the content (links included) showcased in the code sample.</p><p>Second stage login</p><p>Code for the second stage is slightly more complex:</p><pre>public async ValueTask&lt;bool&gt; ValidateLogin(<br>            string emailAddress,<br>            string code,<br>            CancellationToken cancellationToken = default)<br>        {<br>            // Create login key and code<br>            string key = string.Format(<br>                LoginValidationKey,<br>                Requires.NotNullOrWhiteSpace(emailAddress));<br> <br>            var innerCode = Requires.NotNullOrWhiteSpace(code);<br> <br>            // Validate that there was a login that hasn&#39;t expired<br>            if (!this.cache.TryGetValue&lt;string&gt;(<br>                    key,<br>                    out var existingCode))<br>            {<br>                return false;<br>            }<br> <br>            // Compare code<br>            if (!existingCode.OrdinalEquals(innerCode))<br>            {<br>                return false;<br>            }<br> <br>            // Do login<br>            try<br>            {<br>                var existingUser = await this.userManager.FindByNameAsync(emailAddress);<br> <br>                if (existingUser == null)<br>                {<br>                    // If there is no current user, let&#39;s create one<br>                    existingUser = new IdentityUser&lt;int&gt;(emailAddress);<br> <br>                    var result = await this.userManager.CreateAsync(existingUser);<br> <br>                    if (!result.Succeeded)<br>                    {<br>                        return false;<br>                    }<br> <br>                    // Send an e-mail to the new user, if we&#39;re not in development mode<br>                    if (!this.host.IsDevelopment())<br>                    {<br>[... send user an email with user creation ...]<br>                    }<br>                }<br> <br>                await this.signInManager.SignInAsync(<br>                    existingUser,<br>                    false);<br> <br>                // Done<br>                return true;<br>            }<br>            catch (Exception e)<br>            {<br>                this.logger.LogError(e, &quot;Could not perform login due to an exception.&quot;);<br> <br>                return false;<br>            }<br>        }</pre><p>The major difference is that we actually want our cache to contain an entry now, which we dutifully verify.</p><p>There’s only one thing to mention at this point: The default Identity implementation does expect that a user is persisted in order to properly work, so that’s what the userManager does — tries to find an existing entry and, if none is found, tries to create one. Only thing it needs to set is the user name, which is the email address.</p><p>And last, but not least, signInManager then calls SignInAsync and instructs ASP.NET to log in the user. From that point onwards, there is a user session created, and you can use the identity to do all sort of session-based stuff:</p><pre>@if (User.Identity?.IsAuthenticated ?? false)<br>{<br>    &lt;a class=&quot;nav-link text-dark&quot;&gt;Welcome, @User.Identity.Name! @Html.GravatarImage(User.Identity.Name, size: 25)&lt;/a&gt;<br>}<br>else<br>{<br>    &lt;a class=&quot;nav-link text-dark&quot; asp-page=&quot;/Forms/Authentication/Login&quot;&gt;Log in&lt;/a&gt;<br>}</pre><p>(<em>Note: the Html.GravatarImage can be used from </em><a href="https://github.com/AndrewFreemantle/Gravatar-HtmlHelper"><em>Andrew Freemantle’s GitHub repository</em></a><em> and does pretty much what you’d expect</em>)</p><p>I won’t go into details about the logout page, as the only thing it needs to do is to call <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.signinmanager-1.signoutasync">SignInManager.SignOutAsync</a> method.</p><h3>Conclusion</h3><p>As <a href="https://blog.medium.com/signing-in-to-medium-by-email-aacc21134fcd">Medium clearly demonstrates itself</a>, doing away with passwords and not bothering with third-party social media is possible.</p><p>I hope that my rather short implementation example is conclusive proof that it is also accessible to developers.</p><p>Remember: everyone is responsible for security, and your first duty as a developer of secure applications is to give attackers as little surface as possible to attack, and as few chances as possible to succeed. Some things will always be out of your hands, but, where they’re not, it is your responsibility to make sure that security is close to impossible to compromise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa65bd5fb601" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/doing-away-with-passwords-in-asp-net-fa65bd5fb601">Doing away with passwords in ASP.NET</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to train your robot]]></title>
            <link>https://adimosh.medium.com/how-to-train-your-robot-9a77a44595a5?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a77a44595a5</guid>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Fri, 11 Feb 2022 21:37:48 GMT</pubDate>
            <atom:updated>2022-02-11T21:42:19.140Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick guide on how to make human-interactive robots not be annoying, insecure and useless.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oP-sjNKnXNVnCMrifBVJBw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@kindelmedia?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Kindel Media</a> from <a href="https://www.pexels.com/photo/close-up-photo-of-toy-bot-8566472/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>I don’t mind robots. I think call centre robots are great, a wonderful addition to an otherwise unworldly busy workspace meant to both ease some tension on the caller and also to maybe filter out some calls that could have been some web searches instead. I think procedural robots most likely save a lot of soul-sucking work that some unfortunate clerks would otherwise have to deal with on a daily basis.</p><p>However, what I do mind are when call centre robots are implemented in annoying ways, like the examples below in no particular order. For reference, I will be giving examples of banking call centre robots, but you can extrapolate from here.</p><p><strong>Marketing robots</strong> — robots that are programmed to hold a one- or two-minute speeches about some wonderful feature of a certain app or site, which cannot be skipped. I might call your call centre for a card being stuck in an ATM, so I couldn’t care less about your feature (which, being a geek, I may already use if it’s as wonderful as you claim). Or, if you really think this is the way to go, maybe give the option to make a menu selection while you’re playing it, if I happen to already know that I need to press “2”. If I have to wait for two minutes listening to some marketing drivel (no offense, marketing people) before I can press a button to make a selection, I will not be less angry when I get to talk to that unfortunate worker at the other end of the line.</p><p><strong>Voice-ID robots.</strong> Now I do call on Siri myself with personal requests from time to time (heck, even my young daughter likes to give her commands), but I do so from the comfort, and especially the privacy, of my own home. It may just be me, but I think that there’s something inherently wrong about having to state my name, ID number and maybe some other identification details <strong>out loud in a slow and very clear voice, in the middle of a densely-populated public square</strong> where the ATM that ate my card just happened to be located. Maybe give me the option “<em>If you’re in public and can’t give out your identification details to just any passer-by who might or might not be a cracker, please press 0 to type them in.</em>”</p><p><strong>Guessing game robots.</strong> Those that just state “<em>Welcome to Funk, You and Howe, Inc., please dial the interior code you desire</em>” and then wait. OK, robot, let’s guess… maybe it’s 100? Wrong? OK, maybe it’s 10. No? OK, let’s try 666! Oh, whoops, that was the CEO’s interior… well darn, sorry to bother, but maybe if you would have included some guide as to what your interiors are, for, you know, those clients that try to get in touch with you but have absolutely no idea what the internal structure of your phone relay centre looks like, which, I would imagine, means pretty much ALL clients… Something as little as “Reception lines start with 100, Accounting with 200, Leisure and Entertainment with 300, Hitmen for hire with 400, Children’s afterschool with 500” and so on would go a long way, I think.</p><p><strong>Surprise questionnaire robots.</strong> Those who go “<em>In order to identify you better, let me ask you a few questions. Do you currently have, or have you ever had, accounts with us that have had funds withdrawn from escrow as a result of an immediate court order through certiorari in which you, or any third person who you have vouched for or for which warranty was implied, were involved?</em>” Umm… no, I… guess? Maybe… I don’t know, listen, robot lady, I’m here because your ATM ate my damn card, also, I am not a lawyer, or whatever one needs to be in order to understand that oddly-specific question. Could you maybe just ask “<em>Do you have a credit card with us?</em>” Well no, thanks for asking, I do not, but at least I can offer a confident and informed answer.</p><p><strong>Oddly-limiting robots.</strong> And by the way, this does not just apply to robots. If your robot asks me to choose some password, and I type one in, and then it says that it’s too long, I immediately start to worry. And I do so because I know for a fact that <a href="https://en.wikipedia.org/wiki/Salt_(cryptography)">salted</a> <a href="https://en.wikipedia.org/wiki/Hash_function">hashes</a> for very secure passwords that can be physically typed by humans in a manner practical-enough to actually be used as passwords tend to be of the same very predictable size. If you limit my password at 20 characters, I tend to worry that what you’re doing is saving it in clear text. Otherwise, a good salted hash of a 20-character password would be just the same size as a good salted hash for a 128-character password, which is only harder to crack by so many orders of magnitude, that bacteria wouldn’t have had appeared on Earth yet when you had to start, in order to finish when quantum computing is probably going to make all of this obsolete anyway. I don’t worry too much about a PIN, as PINs tend to be three-strikes-and-the-bomb-goes-off deals, but passwords are something else entirely. So don’t limit me to password lengths, or, if you must do so for practical reasons, choose to limit me at high values, not 20 freakin` characters.</p><p>Oh, and please, DO NOT STORE PASSWORDS!!! There is no compelling reason to store them, and, instead of telling every grandma who has forgotten her password “<em>Dear madam, your password was SweetGingerbreadAndNaughtyEggNog1972</em>”, you might just want to go through the “<em>Forgot your password? No worries, happens to everyone, let’s just set a new one</em>” instead. You know, because, apart from being more secure, it’s also completely true.</p><p>Oh, and if you’re using fixed-length passwords as binary keys for your encryption… well, let’s… just… move on, before a vein pops in my head.</p><p><strong>Poorly thought out functional robots.</strong> Listen, I get that in order to open an account, now especially more than ever, I should use an online process that will involve a robot, and, since I have to submit paperwork for processing, I realize I will have to get a digital version of my papers to you. Bot for crying out loud, why do you force me to use my webcam to snap a photo of them? Why can’t you just offer a file upload box like a normal website? I wouldn’t mind at all, but you know, I’m not a professional streamer, so my webcam is the cheapest option that would allow me to actually show my face in meetings, not a 14400-dpi scanner-head that I fashioned into a makeshift ultra-high-resolution camera to look my very best, and to also make my paperwork look legible. And, worst offender, the webcam scanner bot that asks me to hold a small item (such as a modern drivers’ license, or an ID card) close within the edges of a scan border the size of Alaska. Developers, at any point when you created that monstrosity, have you maybe stopped to consider that maybe my webcam can’t actually focus at such a small focal length? I’m not using my Nikon mirrorless as a webcam, you know… although, with some banks’ recent experience, I’m quite certain that what they actually used in functional validation was a microscope.</p><p><strong>“You can’t do that” robots (and apps).</strong> Look, robot (and web page/app) developers, let’s be honest here. I get that you are probably new under the sun, and the closest you’ve seen to an actual hacker is a Guy Fawkes mask in someone’s basement next to a Linux station. But just open your web-based robot in whatever browser you prefer and <a href="https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide-chromium">hit</a> <a href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">the</a> <a href="https://developer.chrome.com/docs/devtools/">F12</a> key (or <a href="https://support.apple.com/guide/safari/use-the-developer-tools-in-the-develop-menu-sfri20948/mac">some equivalent</a> on a Mac). Now navigate to that “secure” field that you so cleverly hooked up an event handler to in order to catch when someone hits Ctrl+V (or its equivalent on a Mac), and just uncheck the handler. Can you paste into that field now? Great. See how you were able to fully circumvent your security for that “secure” field just by a few clicks? Now imagine that I can do that as well. Or any actual hacker, for that matter. So why, might I ask, do you insist on disabling pasting in a “Secure” field? Do you honestly think it will do anything more than annoy your users? If your robot asks me to change a password, and I can’t paste a serious password (you know, like from a <a href="https://bitwarden.com/">password manager</a>), and I’m not a computer geek, I will most likely swear at you a bit, then type in an insecure password. Please think a bit.</p><p>That’s it, for now. Why don’t we turn this robot business into a good, secure and pleasant experience?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a77a44595a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thought process: High-throughput data fetching and processing in C#]]></title>
            <link>https://medium.com/codex/thought-process-high-throughput-data-fetching-and-processing-in-c-33195919ac65?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/33195919ac65</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Wed, 19 May 2021 00:56:51 GMT</pubDate>
            <atom:updated>2021-05-19T00:56:51.397Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software development is a process, which can and should evolve.</h4><p>Let us assume that we have a serious piece of equipment that outputs high volumes of data in a specific format, which needs to be loaded onto a computer in real time and processed, then saved onto a storage medium. You are tasked with creating a .NET 5 program that takes said data from the equipment via a dedicated driver API, does the processing, then outputs the results.</p><p>If the above sounds scary, it shouldn’t be. Software development is almost always the result of an evolutive process. Experience will usually allow you to start later and later in the process, but, while learning, starting from the beginning is what everyone should do.</p><h3>The setup</h3><p>The easiest to imagine situation in which this could be necessary is an image acquisition setup. Usually, dedicated hardware will have a real-time operation, whereas a PC will not, and timing will become crucial for success.</p><p>At 60 frames per second of uncompressed 1080p frames (approximately 6MB per frame), the total amount of data that needs to be transferred, processed and saved would be:</p><blockquote>6MB/f *60f/s = 360MB/s</blockquote><p>Since we’re talking about 60 frames per second real-time, we’re talking about:</p><blockquote>1000 ms/s / 60f/s = 16.(6) ms/f</blockquote><p>This means that the time between two frames is slightly less than 17 milliseconds.</p><h3>Considerations</h3><p>Usually, since 360MB/s is quite a hefty load to transfer via multiple a chain of multiple interfaces, drivers, OS layers and software layers, and do processing on it as well, a few things are required for success:</p><ol><li>Enough buffer should be available so that, should processing slow down, there is space to accumulate so that data doesn’t get lost</li><li>Either a fast-enough processing cycle, or a parallel-enough processing cycle, must be applied, so that the time it takes between subsequent moments that the software can process does not overrun the data input time from the dedicated hardware</li><li>A fast-enough storage medium, or a good-enough compression cycle, must be used so that the time it takes to save the result to a non-volatile storage medium does not overrun the data input times</li></ol><p>For point #1, a lot will depend on hardware. Usually, dedicated hardware will have enough buffer so that what it’s attached to will have the chance to read data before the same buffer is overwritten by new data. This is usually achieved with a buffer certain times larger than the actual data package being received (for the sake of simplicity, let’s just assume that the size of each data package (in our example case a bitmap-format 1080p frame) is constant).</p><p>Point #2 will mostly depend on software factors. If the requirements are for processing into a specific format (say, a series of PNG images), then the processing cycle defines which strategy should be employed. A still image encoding, for instance, will take a lot longer than 16.6 milliseconds, the gap between two frames at 60f/s. So, in such a situation, the only strategy that can ensure proper timing is parallel processing.</p><p>A separate problem that again forces a parallel strategy is the choice of software platform. If you chose a managed platform, such as .NET, you must contend with various timing skews and delays that come from various platform-specific sources, such as thread pool management, garbage collection, marshalling, p/invoke, etc.</p><p>Point #3 will mostly be based on requirement and available hardware. If the machine that you are running on has a dedicated encoding equipment that only takes 5ms to process, and a dedicated API to call, then, of course, you won’t have to use a parallel strategy on point #2. But, should the requirements be custom encoding, or no hardware is available, then you need to plan accordingly.</p><p>Ultimately, should the requirements actually be met, then considerations for points #1–3 will have only determined how many resources you need, and how efficient you are in using them.</p><p>However, in real-life scenarios, the considerations for points #1–3 will determine your strategy, as the inability to offer the speed or the timing required for dedicated hardware on a PC will usually greatly limit your range of available strategies.</p><h3>The simulated API</h3><p>Let’s assume that we have a driver API (translated in C#) that follows some principles:</p><ol><li>The driver does not push anything itself — anything that is required must be fetched</li><li>The driver notifies for data available in a blocking way, and writes data into a specified buffer in a non-blocking way — this ensures the maximum amount of speed for the driver itself, while allowing the maximum amount of non-blocking time for the API caller, while simultaneously ensuring that the caller is guaranteed data available for reading upon notification</li><li>The driver uses the fastest possible data transfer strategies, which means that PC RAM must be allocated and registered within it in order to be used</li></ol><p>These principles are mostly in line with what one would expect from a dedicated hardware’s API. It would look something like this:</p><pre>public static class Acquisition<br>{<br>    #region Notification API<br> <br>    public static DriverResponse WaitForNotification(DriverOptions options) =&gt; ...;<br> <br>    #endregion<br> <br>    #region Buffer pinning<br> <br>    public static DriverResponse PinBuffer(<br>        byte[] buffer,<br>        DriverOptions options)<br>    { ... }<br> <br>    #endregion<br> <br>    #region Data fetching API<br> <br>    public static uint StartFetchingData(DriverOptions options,<br>            byte[] buffer) =&gt; ...;<br> <br>    public static DriverResponse EndFetchingData(<br>        uint fetchingId) =&gt;<br>        ...;<br> <br>    #endregion<br>}</pre><p>We will use <em>WaitForNotification </em>in order to block a listening thread until data is available. We’ll use <em>StartFetchingData </em>to initiate writing of data into a predefined buffer, which would be non-blocking, and we’ll use <em>EndFetchingData </em>to block (if necessary) until the buffer is filled. The buffers that we’ll use are going to be pre-allocated and registered with <em>PinBuffer</em>.</p><p>Since drivers will require option sets and will probably wish to return complex results as structured data types. For the sake of example, we’ll be using two structures for this purpose.</p><ul><li>A struct called <em>DriverOptions</em>, which is basically input for driver API methods:</li></ul><pre>[StructLayout(LayoutKind.<strong>Sequential</strong>)]<br>public struct DriverOptions<br>{<br>    public uint ChannelId { get; set; }<br> <br>    public uint TimeoutInMilliseconds { get; set; }<br> <br>    public byte BufferIdentifier { get; set; }<br>}</pre><ul><li>A struct called <em>DriverResponse</em>, which is status response with a minor information payload:</li></ul><pre>[StructLayout(LayoutKind.<strong>Sequential</strong>)]<br>public struct DriverResponse<br>{<br>    public byte ChannelId { get; set; }<br> <br>    public ResponseStatus Status { get; set; }<br> <br>    public byte BufferIdentifier { get; set; }<br> <br>    public uint ResponseDuration { get; set; }<br>}<br> <br>public enum ResponseStatus : byte<br>{<br>    Success = 0,<br>    Timeout = 1,<br>    NoData = 2,<br>    EquipmentNotInitialized = 3,<br>    HardwareFailure = 4,<br>}</pre><ul><li>A set of constants about the API:</li></ul><pre>public static class Constants<br>{<br>    public static int PayloadSize { get; set; } = 6291456; // 6MB<br>}</pre><h3>Beginning to design</h3><p>For the sake of simplicity, let’s make a few decisions that are not likely to influence us on the long term, and can be easily adjusted according to the situation:</p><ul><li>we will be using a console app</li><li>we will not be limiting the resources that are being used: CPU, RAM, threads</li><li>We’ll be skipping some data validation — doing data validation is always a good idea, so please do validate user input, but, for the sake of</li></ul><p>Beginning the code, we’ll do some simple plumbing to get some input parameters. I’ve found that the <a href="https://www.nuget.org/packages/CommandLineParser">CommandLineParser NuGet package</a> is a good way to do simple parsing of command line arguments, by creating a class that will contain argument data, or default values.</p><p>Let’s define such a class, inside the Program static class, with option, such as the output folder:</p><pre>private class ConsoleArgumentData<br>{<br>    [Option(&#39;o&#39;, &quot;output&quot;)]<br>    public string OutputFolder { get; set; }</pre><pre>    [Option(&#39;c&#39;, &quot;channel&quot;)]<br>    public uint Channel { get; set; }<br>}</pre><p>Let’s also create a Main function that parses arguments using the default parser, uses a separate thread to do the job, and then simply waits for user input to finish calling the driver:</p><pre>static void Main(string[] args)<br>{<br>    Parser.Default.ParseArguments(args)<br>        .WithParsed&lt;ConsoleArgumentData&gt;(<br>            data =&gt;<br>            {<br>                // We use a cancellation token source to be able<br>                // to stop the process later<br>                CancellationTokenSource cts = new CancellationTokenSource();<br> <br>                // We run the worker method MainLoop on a separate<br>                // thread, giving the output folder and the<br>                // cancellation token<br>                Task runningTask = Task.Run(() =&gt; MainLoop(data.OutputFolder, data.Channel, cts.Token));<br> <br>                // Let&#39;s await for any user input<br>                Console.WriteLine(&quot;Press any key to end...&quot;);<br> <br>                Console.Read();<br> <br>                Console.WriteLine(&quot;Finishing...&quot;);<br> <br>                // Cancelling the task immediately<br>                cts.Cancel();<br> <br>                // Let&#39;s wait for 30 seconds so everything<br>                // finishes processing, since we have them<br>                runningTask.Wait(TimeSpan.FromSeconds(30));<br>            });<br>}</pre><p>The only thing left is to implement the main method that waits for being notified, then fetches the data, processes it, and saves it. We have already called the <em>MainLoop </em>method, let’s write down a basic skeleton for it below.</p><h3>First draft, a naïve but functional version</h3><p>Let’s try to write our method without considering things like timing and performance:</p><pre>private static void MainLoop(string outputFolder, uint channel, CancellationToken cancellationToken)<br>{<br>    // Buffer and initial driver options<br>    byte[] buffer = new byte[Constants.PayloadSize];<br>    DriverOptions driverOptions = new()<br>    {<br>        ChannelId = channel<br>    };<br> <br>    // Attempt to pin the buffer<br>    DriverResponse <strong>response</strong> = Acquisition.PinBuffer(<br>        buffer,<br>        driverOptions);<br> <br>    if (<strong>response</strong>.Status != ResponseStatus.<strong>Success</strong>)<br>    {<br>        // Failure to pin<br>        Console.WriteLine(&quot;Buffer could not be pinned.&quot;);<br>        return;<br>    }<br> <br>    // Let&#39;s read until we&#39;re told to quit<br>    int <strong>fileIndex</strong> = 0;<br>    while (!cancellationToken.IsCancellationRequested)<br>    {<br>        // Block while waiting for notification<br>        <strong>response</strong> = Acquisition.WaitForNotification(driverOptions);<br> <br>        if (<strong>response</strong>.Status != ResponseStatus.<strong>Success</strong>)<br>        {<br>            // Missed frame<br>            continue;<br>        }<br> <br>        // Set options for fetching<br>        DriverOptions nextDriverOptions = new()<br>        {<br>            ChannelId = channel,<br>            BufferIdentifier = <strong>response</strong>.BufferIdentifier<br>        };<br> <br>        // Start data fetching (non-blocking)<br>        uint fetchId = Acquisition.StartFetchingData(<br>            nextDriverOptions,<br>            buffer);<br> <br>        <strong>response</strong> = Acquisition.EndFetchingData(fetchId);<br> <br>        if (<strong>response</strong>.Status != ResponseStatus.<strong>Success</strong>)<br>        {<br>            // Missed frame<br>            continue;<br>        }</pre><pre>        /*<br>         * Add processing here<br>         */ </pre><pre>        try<br>        {<br>            // Let&#39;s save the file<br>            using FileStream sw = File.Create(<br>                Path.Combine(<br>                    outputFolder,<br>                    $&quot;{<strong>fileIndex</strong>++}.bin&quot;));<br> <br>            sw.Write(buffer);<br>        }<br>        catch<br>        {<br>            // Missed frame<br>            continue;<br>        }<br>    }<br>}</pre><p>The method does what we want it to do: it creates a buffer, it registers it (“pins”) with the driver, then starts a cycle waiting for a notification, reading the data when one is received, then saving the data.</p><h3>First improvement, offloading to another thread</h3><p>Let’s think of a few things here:</p><ol><li>The entire method runs synchronously on one thread, which means that it has to execute within the time interval of 16.6 milliseconds, otherwise it will miss data</li><li>The method does not use the blocking/non-blocking mechanism offered by the driver</li></ol><p>These are both improvement points that we can capitalize on, so let’s try and do a small improvement in the second part of the method:</p><pre>// Start data fetching (non-blocking)<br>uint fetchId = Acquisition.StartFetchingData(<br>    nextDriverOptions,<br>    buffer);<br> <br>(uint, byte[], int, string) outerState = (fetchId, buffer, <strong>fileIndex</strong>, outputFolder);<br><strong>fileIndex</strong>++;<br> <br>ThreadPool.QueueUserWorkItem(<br>    state =&gt;<br>    {<br>        var (fId, buf, fI, oF) = ((uint, byte[], int, string))state;<br> <br>        var r2 = Acquisition.EndFetchingData(fId);<br> <br>        if (r2.Status != ResponseStatus.<strong>Success</strong>)<br>        {<br>            // Missed frame<br>            return;<br>        }<br> <br>        /*<br>         * Add processing here<br>         */<br> <br>        try<br>        {<br>            // Let&#39;s save the file<br>            using FileStream sw = File.Create(<br>                Path.Combine(<br>                    oF,<br>                    $&quot;{fI}.bin&quot;));<br> <br>            sw.Write(buf);<br>        }<br>        catch<br>        {<br>            // Missed frame<br>            return;<br>        }<br>    }, outerState);</pre><p>Now this looks somewhat better. Once the data fetching is initiated, a value is created that holds the data which should be passed onto a different thread. Then, this data is passed through to a worker thread which takes over and waits (in a blocking way) for the data to be brought to system memory, then processes it and saves it, all the while leaving the original thread to go on and catch another notification.</p><p>Now, should the driver method that initiates reading be of sufficient performance (and there is little reason for it not to be), this new way of writing the method would allow the thread that is waiting for notifications to run with minimal interference, and start off threads with every notification it gets.</p><p>Resource-wise, we can follow the threads in the thread pool, and do some calculations of our own. We will clearly have more than one thread processing at one time, but it is important to note that multiple processing threads does not necessarily mean that the performance of our software is going to be bad. It just means that we are using the advantage of our PC (that it can be massively parallel) to complement the advantage of our equipment (that it is real-time), ensuring that the high-throughput of the entire cycle will remain the same.</p><p>Ideally, in this case, the number of parallel processing threads will grow sharply at the beginning of the cycle, then taper off and oscillate around the same value after a short while. This means that the PC can handle the load well. We can even calculate how many threads there will be:</p><p>Let <em>Tp</em> be the time it takes to process one payload (we’ll include the time it takes to spawn the thread and save the data in here as well), and let <em>Tn</em> be the time between two successive notifications. We can therefore compute <em>Tmin</em> and <em>Tmax</em> as:</p><blockquote>Tmin = ceiling(Tp / Tn)</blockquote><blockquote>Tmax = ceiling(Tp / Tn)</blockquote><p>We get <em>Tmin</em> and <em>Tmax</em> as the interval in which the number of parallel processing threads oscillates.</p><p>We can further expand this formula to a non-constant time elapsed for processing or notifications, considering <em>Tpmin</em> and <em>Tnmin</em> as the smallest intervals for processing and notification, and <em>Tpmax</em> and <em>Tnmax</em> as the largest. We therefore get:</p><blockquote>Tmin = ceiling(Tpmin / Tnmax)</blockquote><blockquote>Tmax = ceiling(Tpmax / Tnmin)</blockquote><h3>Ensuring that buffers don’t overrun</h3><p>If you were to actually run the code written in the step before, you would have noticed that the data is garbled and unrecognizable. This is because we use the same buffer to write data, then to process.</p><p>Let’s switch our code to use a buffer for each time we need it:</p><pre>private static void MainLoop(string outputFolder, uint channel, CancellationToken cancellationToken)<br>{<br>    // Let&#39;s read until we&#39;re told to quit<br>    int <strong>fileIndex</strong> = 0;<br>    while (!cancellationToken.IsCancellationRequested)<br>    {<br>        // Buffer and initial driver options<br>        byte[] buffer = new byte[Constants.PayloadSize];<br>        DriverOptions driverOptions = new()<br>        {<br>            ChannelId = channel<br>        };<br> <br>        // Attempt to pin the buffer<br>        DriverResponse <strong>response</strong> = Acquisition.PinBuffer(<br>            buffer,<br>            driverOptions);<br> <br>        if (<strong>response</strong>.Status != ResponseStatus.<strong>Success</strong>)<br>        {<br>            // Failure to pin<br>            Console.WriteLine(&quot;Buffer could not be pinned.&quot;);<br> <br>            continue;<br>        }<br> <br>        // Block while waiting for notification<br>        <strong>response</strong> = Acquisition.WaitForNotification(driverOptions);</pre><pre>... the rest of the method</pre><p>This looks like it’s running, but it seems to miss quite a few frames. Why is that?</p><h3>Digging in deeper in garbage collection</h3><p>We seem to be forgetting that our buffers are 6MB in size, each! The garbage collection mechanism puts them directly in the large objects heap, and, as you’ve noticed, we’re discarding each after every use. This prompts the GC to keep finding 6MB chunks of memory to allocate, which it naturally doesn’t want to do, so it has to collect the unused ones. This, in turn, triggers a level 2 heap collection, which severely slows down the process.</p><p>Naturally, the solution is to use multiple pre-allocated buffers. But how would you know how many?</p><p>A clue is the formulas that we have computed in the previous phase and create enough buffers to accommodate the maximum number of threads that one can have. This is a risky proposition, though: the processing speed depends on available CPU time, so the <em>Tpmax</em> time will remain constant only as long as there is available CPU time for all processing threads. Once the resources become limited (e.g. the user is doing something else on that machine), the <em>Tpmax</em> value will increase, and we will be in exactly the same situation as before.</p><p>Clearly, a solution with a dynamic number of buffers is ultimately required. Let’s start to prepare our code for multiple buffers.</p><p>The values that we have computed before can be used as reference points. The <em>Tmin</em> value is the lowest that we will have, so it is reasonable that we would begin with that number of buffers, and let them increase as needed.</p><p>We could also use <em>Tmax</em> as a starting point, but whether or not we should do so depends on how the minimum and maximum times for processing and notification were calculated. If the maximum was calculated with serious outliers, it might be wasteful to pre-allocate buffers to serve that much, since you will only benefit from them in edge cases. Perhaps a smarter way to be safe and have high-throughput at the cost of using up more RAM would be to calculate a superior average and start from there:</p><blockquote>Tpmax = avg(Tp where Tp &gt; avg(Tp))</blockquote><p>This way, we would begin with an already-hefty allocation that would serve us well in the vast majority of cases, and only increase if absolutely necessary. This would be a trial-and-error determination, a practice which is a lot more useful in the world of development than you think.</p><p>Let’s modify our API constants class to have that value for number of initial buffers:</p><pre>public static class Constants<br>{<br>    public static int PayloadSize { get; set; } = 6291456; // 6MB<br> <br>    public static int EstimatedNumberOfThreads { get; set; } = 8;<br>}</pre><p>And now let’s modify our class so that the buffers are there. We first take the buffer initialization to the outside of the cycle, and then we run through buffers in the cycle:</p><pre>// Initialize buffers<br>byte[][] buffers = new byte[Constants.EstimatedNumberOfThreads][];<br>for (int <strong>i</strong> = 0; <strong>i</strong> &lt; Constants.EstimatedNumberOfThreads; <strong>i</strong>++)<br>{<br>    buffers[<strong>i</strong>] = new byte[Constants.PayloadSize];<br>}<br> <br>// Let&#39;s read until we&#39;re told to quit<br>int <strong>fileIndex</strong> = 0;<br>int <strong>bufferIndex</strong> = 0;<br> <br>while (!cancellationToken.IsCancellationRequested)<br>{<br>    // Buffer and initial driver options<br>    byte[] buffer = buffers[<strong>bufferIndex</strong>++];<br>    if (<strong>bufferIndex</strong> == Constants.EstimatedNumberOfThreads)<br>    {<br>        <strong>bufferIndex</strong> = 0;<br>    }<br> <br>    DriverOptions driverOptions = new()<br>    {<br>        ChannelId = channel<br>    };<br>...</pre><p>We now see that the software executes correctly while we still have buffers, and it also has no timing issues, but we’ve used up a lot of RAM. This might be a trade-off that you willing to do in order to keep performance at an all-time high.</p><p>As an added bonus, we’ve kept our application relatively garbage-collection-free. Let’s think of a few ways to improve this, and the very first is to switch to fully dynamic buffers.</p><h3>Using dynamic buffers</h3><p>In order to use dynamic buffers, we can and should write our own dynamic object pool. But for the purpose of this exercise, we will use a ready-made one: <a href="https://www.nuget.org/packages/IX.StandardExtensions/">IX.StandardExtensions</a>. If you want to research how to make your own dynamic object pool, you could look through the <a href="https://github.com/adimosh/IX.StandardExtensions/blob/master/src/IX.StandardExtensions/StandardExtensions/Efficiency/ObjectPool%7BT%7D.cs"><em>ObjectPoolQueue&lt;T&gt;</em></a> class, which we will use (along with its associated <a href="https://github.com/adimosh/IX.StandardExtensions/blob/master/src/IX.StandardExtensions/StandardExtensions/Efficiency/PooledObject%7BT%7D.cs"><em>PooledObject&lt;T&gt;</em></a> class).</p><p>After using the NuGet package, our code thus becomes:</p><pre>// Initialize buffers<br>ObjectPool&lt;byte[]&gt; buffers = new ObjectPool&lt;byte[]&gt;(<br>    () =&gt; new byte[Constants.PayloadSize],<br>    Constants.EstimatedNumberOfThreads);<br> <br>// Let&#39;s read until we&#39;re told to quit<br>int <strong>fileIndex</strong> = 0;<br> <br>while (!cancellationToken.IsCancellationRequested)<br>{<br>    // Buffer and initial driver options<br>    using var bufferObject = buffers.Get();<br>    var buffer = bufferObject.Value;<br> <br>    DriverOptions driverOptions = new()<br>    {<br>        ChannelId = channel<br>    };<br>...</pre><p>And we can go on and on, improving our algorithms more and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*8J2DwKWNv7Nkn3RzKUV9Mw.png" /></figure><h3>Final word</h3><p>As you can see, a complex problem has been tackled in an evolutive manner: we started small, and, with each solution, a new set of problems or concerns showed themselves, and were tackled one by one.</p><p>We used C#, we used a little basic maths, some logical deduction and our own analysis of how the software behaves. And we went from a simple somewhat working solution to a solution that is actually usable and performant.</p><p>This technique is not a magic bullet that will solve all your software development problems, but it is a good way to start gaining experience.</p><p>By looking at how your software behaves beyond the first working solution, you can discover new things to consider. After, for instance, you tackle the buffer problem, you start considering memory usage more. After starting to use multiple buffers, garbage collection is suddenly on your mind. And with every software or component that you code, more considerations come to you naturally, and that “first working solution” will get more and more complex. This, in turn, will open up new considerations, and higher levels of performance and refinement.</p><p>I hope that, at the end of this article, you will have realized that even a problem that sounds complex and slightly frightening can, in fact, be solved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33195919ac65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/thought-process-high-throughput-data-fetching-and-processing-in-c-33195919ac65">Thought process: High-throughput data fetching and processing in C#</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User-Interfacing Software Design Patterns, Revisited]]></title>
            <link>https://medium.com/codex/user-interfacing-software-design-patterns-revisited-2ac1dcfd445d?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ac1dcfd445d</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 15:57:20 GMT</pubDate>
            <atom:updated>2021-04-19T15:57:20.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kHvOFRtxFTlbM_dK" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When developing software that is facing the general public, it is first and foremost important to get the interaction with the users right. Nobody will care that there are fancy design patterns behind the scenes, if, for them, navigating your application is an absolute nightmare.</p><p>That being said, however, it is also important to remember that there are two sets of people that are somehow using your software: the users, and the developers. While the success of a piece of software depends on the interaction with the users, the success of a software development team depends on how it builds software. At this stage, design patterns become important.</p><p>Let’s then, take a look at design patterns that extend all the way to user interaction. We will look at MVC (model-view-controller), MVVM (model-view-viewmodel), SAM (state-action-model) and CQRS (command-query responsibility segregation), with the BFF (backend for frontend) “anti”-pattern.</p><p>One thing to note in this story is that these patterns are examined from a web application perspective, and might need slight adjustment when applying to anything else.</p><h3>MVC</h3><p>MVC stands for Model-View-Controller and is possibly the oldest in the list, being invented somewhere in the 1970s.</p><figure><img alt="The MVC pattern, as used with a query operation, and as used with a command operation" src="https://cdn-images-1.medium.com/max/591/1*vX4jZvdyHVflcgccaV93dA.png" /><figcaption>MVC pattern: query (top) and command (bottom)</figcaption></figure><p>The main entry point for a user is the controller, which exposes actions. When users decides to interact with the software, they do so by invoking an action on the controller. The controller then does what it’s supposed to do, and creates a model, which is essentially a structured data package, and applies a view on top of it, which transforms that data into a format that can be sent back to the client (HTML in the case of web applications). The client then displays the data to the user and the whole system pauses to wait for further action from the user.</p><p>Users, if they decide to interact with what is presented before them, can bring alterations to the model, and can submit it back to the controller via an action (which can be the same, but doesn’t have to). The controller will take that modified model and, after validation (which, depending on the framework and business logic, can take place in multiple places and in multiple ways) will start doing what the action is supposed to do. When done, it generates another model and applies a view on top of it, sending it back to the user.</p><p>A few key things to take out:</p><ul><li>MVC is merely reacting to the user’s requests (be them manual or automatic), and by definition does nothing absent a user; certain actions can be invoked automatically by the browser, but they will appear as user-invoked actions to the controller, as it (in principle) cannot tell that a piece of JavaScript code is doing the request</li><li>This pattern is controller-centric and action-centric — controllers and the actions they expose are the only components that actually need to exist in order for this pattern to work; a controller might not create or accept a model, or it might not need it at all, and there might not actually be a view per se (unless you consider output of raw data into a HTTP-compliant format as some sort of a default view)</li><li>It is relatively easy to change in terms of how data is presented to the user — including extended support for browsers, various viewports, etc., without affecting the business logic of the application; even if you do introduce a bug, if MVC is done right, and the model is well-validated (which is usually a difficult task), it should be a rather easy to spot and correct it in most cases</li><li>both CQRS and separation of concerns are rather easy to achieve, with a good MVC-based design</li><li>It is relatively easy to conceptualize tests, but it is relatively difficult to actually write tests, as there is seriously tight coupling within the controller, and especially with the underlying framework (ASP.NET MVC is a good example of this, as calls to the underlying framework cannot be abstracted away in most cases, and such calls are necessary for a lot of functionality)</li><li>A lot of developers assume that the model is somehow coupled with the persistence model (for instance, the database model) — this is not true, as the MVC pattern makes no such requirement — whether or not the model matches the database in any way is solely the decision of the implementer, and the database model can be subject to a composed or related MVC pattern, as outlined below:</li></ul><figure><img alt="Composition of multiple MVC patterns, one for serving the user, and another for the database" src="https://cdn-images-1.medium.com/max/478/1*LpdEf9pTyZizW2le04O6mA.png" /><figcaption>Composition in MVC</figcaption></figure><p>MVC is a pattern that is easy to understand, and easy to implement, but, also, easy to misunderstand, and seriously easy to misuse. Amongst the biggest sins of developers using this pattern are:</p><ul><li>not figuring out that they are using composition when they shouldn’t</li><li>not seeing all the links to the underlying framework, and the tight coupling that comes with it</li><li>mixing UI code in business logic (especially in frameworks that don’t encourage tight separation, such as Blazor)</li><li>poor model/view design, resulting in a hazy border between business data, operational data and UI data</li><li>poorly designed middleware that interferes with normal operation when it shouldn’t, or doesn’t interfere with it when it should</li><li>fragile request state due to poor execution path design, especially with underlying frameworks that practically demand asynchronous operation</li></ul><p>MVC is a tried-and-tested design pattern that has stood the test of time, but is becoming a thing of the past, as more and more developers manage to wrap their heads around advanced concepts of control flow, security, CQRS, scaling, massive parallelism, etc.</p><p>Further reading:</p><ul><li>Martin Fowler’s history of MVC and other UI architectures: <a href="https://martinfowler.com/eaaDev/uiArchs.html">GUI Architectures (martinfowler.com)</a></li><li>ASP.NET MVC: <a href="https://dotnet.microsoft.com/apps/aspnet/mvc">ASP.NET MVC Pattern | .NET (microsoft.com)</a></li></ul><h3>MVVM</h3><p>MVVM stands for Model-View-ViewModel, and is, at first glance, an antithesis of the MVC pattern, from the perspective of user interaction design.</p><figure><img alt="The MVVM pattern" src="https://cdn-images-1.medium.com/max/617/1*n1u1y5XhgT0nQSma8Tf9Vw.png" /><figcaption>The MVVM pattern</figcaption></figure><p>The entry point for MVVM is the view, and all interaction with the user is done through it. The view dictates what data is presented to the user, and how. The view has a life of its own, and, in practice, any view from a collection of views which make up an application may or may not have any of the rest of the components, while still correctly implementing the pattern as a whole.</p><p>Views in MVVM are usually considered to be declarative, meaning that they’re supposed to be a declaration of data and how everything binds, and commanding, meaning that various actions that are made available to the users are declared through binding to commands (or through a very similar overridable system for default actions or internal workings). In the case of the .NET environment, this is achieved via the extensible application markup language (XAML).</p><p>The model is the domain model, or, really, any model of data that we wish to operate on (it may or may not be a data access model, or a database model, or a REST/SOAP data model, etc.), with little limitation.</p><p>The view-model is basically a UI-useful abstraction of the model, and is used for connecting things together, and holding all the intermediate state between the model and the view. The view-model, as an abstract concept, does not need to be functional in any way, however, in practice, the logic that supports the UI, as well as the logic that supports changes on the model, as well as the internal state of the view, are being held in the view-model.</p><p>An accessory, as stated in the image above, is the binder, which has the purpose of linking parts of the view with parts of the view-model, and is usually the heart of the binding system of MVVM, implemented specifically and usually differently in any framework.</p><p>A few key things to take out:</p><ul><li>MVVM is view-centric, meaning that user interaction is at the centre of its philosophy, and clearly separates the model, meaning that the only component that is tightly-coupled and will always be affected by non-cosmetic changes is the view-model (note: the view-model is only conceptually tightly-coupled with the view — in practice, since they rely on entirely different writing styles, most compilers and IDEs will not notice a lot of possible errors, especially if bindings are not type-safe, which will only surface at runtime; an especially-annoying implementation is WPF, the binding system of which depends on the visual tree, which is not always what the developer expects)</li><li>MVVM offers disconnect between model and view, but the view-model is tightly coupled to both</li><li>Unless someone has seriously messed up their design, UI-supporting code should be completely separate from the model</li><li>Composition of MVVM can be done at any level, and every view can be broken down into subcomponents, themselves implementing the MVVM pattern either to a model of their own, through a view-model of their own, the same model as their parent, the same view-model of their parent, or any combination of the above, in any number (it is possible to have components that use both their parents view-model and a view-model of their own, and the same goes for models)</li><li>Unit testing and mocking is rather easy</li><li>The learning curve of the MVVM model is steep by comparison</li></ul><p>Further reading:</p><ul><li>Jeremy Likness’ introduction to MVVM: <a href="https://blog.jeremylikness.com/blog/model-view-viewmodel-mvvm-explained/">Model-View-ViewModel (MVVM) Explained | Developer for Life (jeremylikness.com)</a></li><li>SyncFusion’s article on MVVM in Blazor, by Marco Dalla Libera: <a href="https://www.syncfusion.com/blogs/post/mvvm-pattern-in-blazor-for-state-management.aspx">MVVM Pattern in Blazor For State Management — A Complete Guide | Syncfusion Blogs</a></li></ul><h3>SAM</h3><p>SAM stands for State-Action-Model, and is a departure from the previously-describe architectures, in the sense that it makes both a clear separation between the domain-driven model and the application state, and also gives clear option to the domain-driven model as to how to update itself according to its own rules.</p><figure><img alt="The state-action-model pattern, with components and subcomponents" src="https://cdn-images-1.medium.com/max/434/1*qD6ojClaICi8KEMTeZVPNg.png" /><figcaption>The SAM pattern</figcaption></figure><p>The user is presented with a view, which is a pure function of the state of the application. The view works pretty much as one would expect the MVC view.</p><p>The user then gets the chance to perform an action. An action is, in fact, a proposal for the model to change in a certain way, proposal which goes through its own set of validators (in practice, these validate whether the proposed change is formally valid), moving on to the model.</p><p>The model, through acceptors (which validate whether the proposed change is valid as per business rules, considering the current state of the model), chooses whether to accept the proposed change, or to discard it.</p><p>Should the model accept the proposed change, it will incorporate the change and make its own internal state valid as per that change, then either react to it, updating the application state (through reactors) or by getting the state to learn of a mutation (through learners), which state, in return, may, according to its own rules, propose a new action, and/or update the view presented to its user.</p><p>The key things to take out:</p><ul><li>The SAM pattern gives the model a life of its own, emphasizing the domain rules regarding it, while decoupling it completely from the view</li><li>The pattern focuses on mutations of the model as the source of state change</li><li>The view can be mathematically described as a pure function of the state, at any moment, and is supposed to be recomputed as the state mutates</li><li>SAM shuns the idea of managing subscriptions to events, and, instead, relies on the user’s interaction pushing suggestions for state mutation</li><li>SAM has its roots in TLA+, a software modelling language created by prof. Leslie Lamport as part of Microsoft Research</li></ul><p>Further reading:</p><ul><li>SAM pattern: <a href="http://sam.js.org/">SAM — State | Action | Model</a></li><li>TLA+: <a href="http://lamport.azurewebsites.net/tla/tla.html">The TLA+ Home Page (lamport.azurewebsites.net)</a></li><li>Jean-Jacques Dubray’s InfoQ article speaking out against MVC and introducing SAM: <a href="https://www.infoq.com/articles/no-more-mvc-frameworks/">Why I No Longer Use MVC Frameworks (infoq.com)</a></li></ul><h3>CQRS</h3><p>Standing for command-query responsibility separation, CQRS proposes that any command/action/event handler should be one-directional, in the sense that it should either query data, or mutate data. It is not an alternative to the previous patterns, but an addition to them.</p><figure><img alt="The command-query responsibility segregation pattern." src="https://cdn-images-1.medium.com/max/493/1*gvJazh3gwkq4Eo-dSs-MBA.png" /><figcaption>The CQRS pattern</figcaption></figure><p>The query part represents a one-way data selection, conversion and arrangement, with the purpose of serving data to the user in a specific and desired format (either a view, or maybe exports, or reporting).</p><p>The command part represent a one-way data mutation.</p><p>In practice, however, many times, the command also has a query part, which retrieves the entity that it has mutated, in order to display its new state to the user. This is usually used by small pages which focus solely on one entity, which usually has an almost one-to-one mapping with a domain entity.</p><p>While this practical situation does not implement CQRS in its strictest definition, it is usually considered an accepted practice, since it is unlikely that an entity will change in a way which only affects the way it is written, and not the way it is read.</p><p>Implementing CQRS in MVC is rather easy, as actions in the controller can be designed specifically to query or to mutate. In the case of ASP.NET MVC, for instance, and most other frameworks involving HTTP, one could argue that the intention was to support a specialized implementation of this pattern right from the start.</p><p>With MVVM, things are not that simple, as there is not necessarily a clear distinction between mutation and the simple effects of data binding. Since (usually incorrect, or, at least, overeager) binding logic can mutate the underlying model beyond what is required from the perspective of UI logic, CQRS is best implemented strictly inside the view-model, in the sense that, even though the view-model mutates its internal state as a result of data binding, those mutations do not impact the underlying model, unless a command (such as a conceptual “save”) triggers this mutation.</p><p>SAM does not concern itself much with CQRS, as mutation is solely in the will of the model (thus the idea of “commands” from a CQRS perspective is not particularly relevant), and the view (as a conceptual query) is, basically, a function of the state. From the perspective of acceptors and reactors/learners, CQRS is implemented by definition.</p><p>A few things to take out:</p><ul><li>CQRS aims to make flows of data one-directional, in order to simplify the application</li><li>By separating queries from commands, CQRS aims to isolate changes in the application, by lowering the number of sources of volatility; should an entity change its structure, but not in a way that impacts some queries, those queries need not be touched; similarly, should a query be changed by some business need, then the commands need not be touched, even if the query is expanded to include new entities</li><li>Complex domains benefit most from CQRS, especially when coupled with a single point-of-change policy in application design, although, in practice, this may not necessarily always be possible</li><li>Extreme care needs to be taken for resource access synchronization, as a poorly-implemented multithreaded application that follows strict CQRS will almost certainly be prone to many inconsistency issues and race conditions</li></ul><p>Further reading:</p><ul><li>Martin Fowler’s CQRS article: <a href="https://www.martinfowler.com/bliki/CQRS.html">CQRS (martinfowler.com)</a></li><li>Microsoft’s Azure Architecture Center article: <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs">CQRS pattern — Azure Architecture Center | Microsoft Docs</a></li></ul><h3>BFF</h3><p>Considered by many an anti-pattern, or a comical last-resort pattern, Sam Newman’s BFF stands for Backend-For-Frontend, and can be considered both as an able critique of general-purpose backend API architectures, as well as a useful pattern when there is simply no reason to have a general-purpose backend API architecture.</p><figure><img alt="An example of general-purpose backend, and the backends-for-frontends pattern" src="https://cdn-images-1.medium.com/max/882/1*bTG4ts9ACCAa8tOIuXqOXg.png" /><figcaption>General-purpose back-end (left) and BFF pattern (right)</figcaption></figure><p>The idea behind this pattern is that unique frontends (or category of frontends) have unique needs, and, therefore, should also have unique backends (or, at least, public-facing sets of APIs).</p><p>The idea is already widely-used, as the needs of an AJAX-based web application differ from the needs of an iOS application, for instance, in terms of session management, security, trust, accessibility, data flow, etc. So, the idea is that there is no reason to burden an application with has better API capabilities with a limited API.</p><p>Similarly, communication can be done in multiple ways (easiest example is a web assembly with web sockets technology, versus a classic AJAX-based application), which means that some facilities for APIs can dramatically improve performance, speed, and features, which would otherwise be very difficult with a general-purpose back-end.</p><p>A few key things to take out:</p><ul><li>BFF is based on the inequality of frameworks, hardware and underlying system facilities between differing types of frontends and/or clients</li><li>considered by many purists an anti-pattern, the idea behind BFF is actually very useful in specific circumstances</li><li>BFF does not necessarily mean that other patterns cannot be implemented — indeed, each of the backends can correctly and completely implement other patterns</li><li>when implementing BFF, there is always the risk of code duplication — in which case, either back-ends can be made to have a common root, or, maybe, depending on the nature of the duplicated code, a new service can be implemented for that common part</li><li>BFF can also be implemented towards external service consumers, meaning that on the same set of services, different downstream services (federation, streaming, etc.) will connect to different “frontends”</li><li>BFF is meant as a way to parallelize development across teams, while offering autonomy</li><li>One of the key concerns with BFF is keeping features in sync, which means that product owners will have a harder job managing such an architectural choice</li></ul><p>Further reading:</p><ul><li>Sam Newman’s introduction and justification: <a href="https://samnewman.io/patterns/architectural/bff/">Sam Newman — Backends For Frontends</a></li><li>Lukasz Plotnicki about BFF at SoundCloud: <a href="https://www.thoughtworks.com/insights/blog/bff-soundcloud">BFF @ SoundCloud | ThoughtWorks</a></li><li>Microsoft’s short introduction: <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/backends-for-frontends">Backends for Frontends pattern — Cloud Design Patterns | Microsoft Docs</a> (especially the Related Guidance section)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ac1dcfd445d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/user-interfacing-software-design-patterns-revisited-2ac1dcfd445d">User-Interfacing Software Design Patterns, Revisited</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The better mousetrap]]></title>
            <link>https://medium.com/codex/the-better-mousetrap-66a4384c7e6e?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/66a4384c7e6e</guid>
            <category><![CDATA[vaccination]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[scheduling]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 19:25:08 GMT</pubDate>
            <atom:updated>2021-03-24T14:10:15.456Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="http://medium.com/codex">CODEX</a></h4><h4>A programmer’s way of scheduling vaccines during the pandemic.</h4><p>As most countries are dealing with waves of vaccine batches to spread out to the population, each has adopted their own strategy on how to best schedule their vaccinations for best efficacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzKBZRxzcB5Ci15VfD5muA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@jessbaileydesign?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Jess Bailey Designs</a> from <a href="https://www.pexels.com/photo/black-framed-wayfarer-style-eyeglasses-on-white-surface-917293/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>No matter the strategy, one thing seems to stand out from all countries: an engineering oversight on the whole system was fundamentally lacking, and almost all vaccinations were a lot less optimal than they could have been.</p><p>The result of the exercise we are about to do should be a scheduling application, one that works with a set of input data from each user, a set of input data from the administration, and outputs what is essentially a day-by-day calendar of who gets vaccinated and where.</p><h3>Preparation</h3><p>Our project runtime begins in November 2020, when there is news that there have been approvals for COVID-19 vaccines and some countries have started using them. Once there is approval from the regulation agencies that have jurisdiction over them, vaccines are, basically, usable, so the only question is when production will be sufficiently ramped up for vaccinations en masse to begin. At that moment, the entire system needs to be operational, at least in the user input phase, as to allow the most possible time for users to express their preferences.</p><p>This means that the project start date should be a lot sooner, and, for a project like what I’m describing, I would say that a serious software development team should have about 3 months’ worth of work. So that means August 2020.</p><p>This timeframe is not just for the kicks of would-be project managers. There is real value in knowing what your audience wants. If the government of a country estimated that they would need a million doses, and three million people have signed up before actual vaccinations even begun, than that is a sign that the country (or federation, or the EU, whichever the case) did not allocate enough funding and did not secure enough vaccines. Knowing ahead of time what your people want is the best way to serve their interests, and get the sweetest deals for them.</p><h3>User input</h3><p>User input should consist of a set of parameters that are relevant to the vaccines that would be administered. Naturally the whole spectrum cannot be thought of ahead of time, but basic information that pertains to pretty much every vaccine out there can.</p><p>Each user should be able to add themselves and the people they manage (children, disabled, elderly, maybe spouse, even pet — who knows what vaccines might be necessary — zoonoses are tricky), and, for each individual, a few details should be asked for:</p><ul><li>Full name</li><li>Some sort of identity and/or citizenship proof (in Romania, there’s the PNC — Personal Numeric Code — which is uniquely generated for every citizen)</li><li>Date of birth (if not already obtainable — in Romania it can be extracted from the PNC)</li><li>The area where the person lives</li><li>Whether or not the person is a chronic illness sufferer, or has any conditions that make them more at risk</li><li>Whether or not the person has had an active infection</li><li>Whether or not the person is a doctor</li><li>Whether or not the person is actively working in a key sector</li><li>Whether or not the person is in jail</li><li>Whether or not the person has some special status that qualifies them for some closed-circuit vaccination centers (such as active military duty, or diplomatic mission)</li><li>Whether or not the person is pregnant, or breastfeeding (by now it has been proven without a doubt that pregnant women do pass antibodies — which is extremely important if the baby is expected to have some diseases or predispositions such as for auto-immune diseases)</li><li>Whether or not the person may have died in the meantime (before being scheduled) — unfortunately, this can happen</li><li>Whether or not the person has mobility</li></ul><p>Apart from these, contact data, in the form of e-mail and telephone number, should be added to each person (except jailed or special status), and the preliminary data set for users is complete. At every stage, new info can be requested, such as possible interactions (e.g. don’t do vaccine type X if you’re on medication with Y or Z), depending on what is discovered in the meantime.</p><h3>Administration and government input</h3><p>The input phase of the administration is slightly trickier.</p><p>Input needs to be centered around three areas: the vaccine characteristics, the vaccination centers and the priority ratings.</p><h4>Vaccine characteristics</h4><p>We obviously need the vaccine characteristics in order to properly and safely distribute them. It matters if a specific vaccine can be distributed only to a specific age group, or has any specific interactions. These characteristics, while not really foreseeable ahead of time, could actually save lives.</p><p>Certain data can be anticipated, though, such as what age ranges the vaccine was cleared for. There is no sense in scheduling a person over a certain age for a specific type of vaccine that has not been cleared for that age group, when an alternative vaccine that has been exists.</p><p>Other information that you can anticipate is the vaccine dosage per unit. Since vaccines for mass vaccination campaigns rarely, if ever, come in single dose packages (it is highly impractical for this to happen), this data can be anticipated to be needed for later use.</p><p>Imagine, if you will, that you correlate this data with the user input. You can filter out those people that can use only one specific type of vaccine, and you will know both how many doses you need of that vaccine as a minimal number, and, also, how to distribute it. In case the government does not rely on storing second doses (in case this is necessary), they would also know how to properly plan ahead.</p><h4>Vaccination centers</h4><p>The most important thing about vaccination centers is their location. This allows correlation of recipients to vaccination centers, therefore allowing for good planning of vaccine storage and distribution routes.</p><p>If you define a vaccination center with a specific location, you can automatically get a distribution of possible vaccine recipients based on distance (or some other location criterion such as the same administrative division). By correlating this data with user input, you get a few things.</p><p>First off, you get an indication of which centers will be underworked and which will be overworked; by adding a maximum distance criterion to a query, you can get an indication of where it is a good idea to either increase center capacity or open more centers, so as to further distribute recipients amongst centers. These numbers, of course, can be adjusted when estimation of vaccine quantities change (as we’ve seen with basically all pharmaceutical companies overpromising on their capacity), but they still remain a powerful set of indicators.</p><p>Efficiency can be achieved in different ways, too. Underworked centers can be easily spotted, especially in areas where there is sparse population, or very few actually willing to be immunized. In such a case, local administrations can rake cost cutting measures that may end up helping more people, such as dedicated shuttle services. By manually setting schedules for a whole set of people that would otherwise be assigned to an underworked center, and offering them a shuttle to safely take them to and from the vaccination center, underworked centers may be removed from the system ahead of time, instead of allowing them to waste resources.</p><p>A particular decision has been made about vaccination centers in Romania that each one can carry one, and only one type of vaccine. This has been decided in order to avoid possible errors of getting vaccinated with a different vaccine on the second dose, than was on the first does. For those who can read Romanian and have missed this piece of news, <a href="https://www.digi24.ro/stiri/actualitate/pacient-imunizat-la-rapel-cu-moderna-in-loc-de-pfizer-o-asistenta-din-targu-jiu-a-incurcat-dozele-de-vaccin-1448977">this has actually happened before</a>. So let’s say that we will be extra-careful and add this requirement to our specifications, in order to increase safety, and make logistics planning a whole lot easier.</p><p>So this would conclude our initial setup of vaccination centers.</p><p>Next, during running time of the vaccination phase, each center can display the number of people that it is currently expected to serve. Since we started running the web application way before the actual vaccination phase began, we can already schedule the first people to be vaccinated, and we have a rather comfortable pool of people at every vaccination center to schedule for many day to come.</p><p>Again taking Romania’s model, vaccination logistics are coordinated in a few regional centers, for easier storage and distribution to actual vaccination centers. Since vaccines with special requirements, such as Pfizer’s, which require temperatures below -70 degrees to store, are a serious burden for individual vaccination centers, a decision to store them in larger batches in a regional center makes sense. So let’s factor in the super-unit of regional centers, with local centers that depend on them.</p><p>Whenever a vaccination batch is arriving, the authorities need only input the total number of doses that are expected to arrive. Each vaccination center already has a waiting list, and each regional center can automatically deduce the number of doses that it needs. By having a minimal factor of half the number of incoming doses, divided by the number of regional centers, or the minimum in each vaccination center’s persons waiting list, whichever is smaller, we can thus calculate a minimal number of doses to be sent to each regional center for distribution, and the rest of the doses would be split according to each center’s remaining size of the waiting list, as a proportion to the total people waiting. A simple yet effective algorithm to ensure that every center gets a somewhat proportional cut of the doses, yet no center can get more than they need, and none gets ignored because too few people have registered.</p><h4>Priority ratings</h4><p>The administration can adjust priority ratings at any time.</p><p>Paramount is for those that have the first dose of vaccine to get their second one (if needed). If the waiting time is 20 days for a vaccine, then those who have already gotten theirs should have absolute top priority for scheduling 20 days later. In essence, a center can function, time-wise, like an Agile software team: a 20-day sprint of vaccinating people with the first dose, followed by a 20-day sprint of vaccinating with the second dose. In essence, a tick-tock sprint cycle (hey, we’ve managed to cram quite a few software development buzzwords in this paragraph!).</p><p>Otherwise, the administration is free to decide, at any time, who get priority when scheduling. For example, for a specific period of time, teachers have a higher priority rating than energy workers. Or, they can halt vaccinations under specific conditions altogether (such as, say, a vaccine discovered to have serious side effects in a specific category of people).</p><p>The unwanted consequence of this, though, is that there is lack of predictability for the common people as to when they get vaccinated. A commercial worker can look forward to their vaccination sometime next week, only to find out that some other category has taken priority, and now, they’re suddenly pushed back for about three months or so. Ideally, priorities should be rather stable, especially taken broadly (it is expected that those at-risk will always have priority over those with no risk), but variation should be allowed, especially if some centers can be closed-circuit (serving only a specific subgroup of people).</p><p>For that reason, there should be some sort of stable period, say 3 days, in which scheduling cannot change unless under extreme circumstances. This means that someone who has their shot scheduled within that timeframe will not have their place taken by someone whose priority is higher. A timeframe should be chosen that both limits the unwanted side effect of having lower priority vaccinated before higher priority but would still actually be practical and somewhat predicable for people. Vaccination, especially in these conditions, is not something that can be taken lightly, so it would be a good idea to offer some sort of stability.</p><h3>How the whole thing works</h3><p>The entire system works based on simple priority queries to fill in a schedule for the next stable period (for example’s sake, 3 days, but it can be extended to a week, I’d say). Every person that has registered to be vaccinated, based on certain characteristics, is assigned a place in the queue, and can be distributed, based on their mobility factors, to centers.</p><p>Once a new day in the stable period dawns, each vaccination center is scheduled people from the queue, creating an actual schedule in the calendar. The next day dawns, a new batch of people is drawn from the prioritized queue and a new day’s schedule is created, and so on.</p><p>Once a scheduled day comes, people show up to be vaccinated. The personnel there should have the ability to input vaccination status in for everyone, ensuring that information is accurate. Every vaccinated person is scheduled automatically for the second dose.</p><p>If a person does not show up, they are removed from the schedule and put back in the queue, this time with a handicap that grows larger by each missed schedule, with a penalty after a number of misses (say, 3). This ensures that no center can be left with only no-shows.</p><p>Should a spot be left open by a no-show, the system can draw from queue, and, upon successful showing up and vaccination, that person can be scheduled for the second dose and removed from queue themselves, thus ensuring that no doses get wasted.</p><p>Since the system is real-time, authorities have a clear picture of who got vaccinated, where issues are, how many doses are needed, and so on, and each person has an idea of where they are in the queue and how many people get vaccinated.</p><h3>In conclusion</h3><p>This was a simple exercise of imagination, and a possibly viable product for use in further epidemics or pandemics.</p><p>Of course, the problems that we’ve seen in this COVID-19 pandemic are less of logistics and more of society. In Romania, for example, the vaccination campaign is, so far, going rather well considering how many doses we’re getting and what the public interest is. But the cracks were not with the military medic that is in charge of the campaign, but with people themselves.</p><p>From stories of doctors that refuse to schedule those who do not have access, or are simply too decrepit to do it themselves, to those who do not have Internet access, or cellphone signal, etc. (I won’t link to any of these), these are problems that no computer system will fix. As long as user input and consent is needed, anything I suggest will be a simple tool, more or less useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66a4384c7e6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/the-better-mousetrap-66a4384c7e6e">The better mousetrap</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A lesson in free speech learned during the pandemic]]></title>
            <link>https://adimosh.medium.com/a-lesson-in-free-speech-learned-during-the-pandemic-455f9db21b0d?source=rss-51fbcdcad700------2</link>
            <guid isPermaLink="false">https://medium.com/p/455f9db21b0d</guid>
            <category><![CDATA[free-speech]]></category>
            <dc:creator><![CDATA[Adrian Mos]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 12:58:27 GMT</pubDate>
            <atom:updated>2021-02-13T12:58:27.041Z</atom:updated>
            <content:encoded><![CDATA[<p>How not to understand law and government.</p><p>Background: In the midst for the COVID-19 pandemic, a Romanian actor who, by that point, had made nothing newsworthy in medical terms, took to Facebook posting that he will not be getting himself vaccinated, and will not be wearing a mask:</p><p><a href="https://www.facebook.com/dragos.bucur/posts/10157806090955736">Log into Facebook</a></p><blockquote>Translation: In case you didn’t have anyone to curse at: I’m not getting vaccinated and I’m not wearing a mask.</blockquote><p>Predictably, he did get a lot of flak on that, to which he created a reply:</p><p><a href="https://www.facebook.com/dragos.bucur/posts/10157808651655736">Log into Facebook</a></p><p>The reply is, in my opinion, a perfect example of how not to relate to law and citizenship, and gives a very good and very condensed image of how poorly understood our current states and values are by its inhabitants.</p><p>In the following, I will take each paragraph, translate it, and then dissect it to find out what’s being said, what concepts are being used, and what is wrong with it.</p><blockquote>Original Romanian text: Cativa prieteni m-au sunat sa ma intrebe de ce nu tac, de ce a trebuit sa spun ce gandesc. Ei bine, aceasta intrebare este raspunsul la ea insasi. Am spus ce gandesc pentru ca oamenii au ajuns (iar) sa aleaga varianta in care tac si pastreaza pentru ei si familiile lor ceea ce cred, de teama ca nu cumva sa fie linsati public si ostracizati si sa nu isi piarda locurile de munca, prietenii, relatiile si sursele de venit.</blockquote><blockquote>Translation: Some friends called to ask why I’m not keeping quiet, why I had to say what I think. Well, this question is the answer to itself. I said what I thought because people have (again) resorted to keeping quiet and keeping their thoughts for themselves and their own family, because of their fear of being publicly crucified [note: expression adaptation] and ostracized and losing their jobs, friends, connections and income streams.</blockquote><p>I do understand that this is both a real fear, and a definite possibility. It is not unheard of, even in our modern societies, that people with wild ideas get turned away from their friends, communities, or jobs. It has happened before, and it will happen again.</p><p>However, one must realize that agreeability is, in fact, what friendships, communities and societies are actually built on. And one must realize that, in case a wild idea is presented, there are multiple ways in which this could go.</p><p>The best way is that the people who it is presented to will listen, then will think about it, and then will analyse, along with the author, whether or not the idea is that wild to begin with.</p><p>There’s the option of the idea being labelled as ridiculous, and everyone moving on. There’s the option of a little fun being made at the presenter’s expense.</p><p>Of course, there is the option of that idea (and, implicitly, its presenter) being shot down violently (not necessarily in the physical sense). And everyone needs to realise that this is indeed a very real option.</p><p>Not to say that the result was surprising in any way. After all, we are talking about an opinion to wilfully refuse to contribute to ending a pandemic that has taken quite a few lives. By the time it was launched (almost a year in), it is hardly surprising that Mr. Bucur even had to come up with a reply. Only he knows how exactly he expected things to go differently.</p><blockquote>Original Romanian text: Mi-a fost teama de reactia pe care impartasirea parerilor mele ar putea sa o nasca, apoi mi-a fost rusine de aceasta teama si de gandul meschin ca “E mai bine tac decat sa spun ce cred”. Cum de obicei aleg sa fac exact lucrurile de care imi e cel mai frica, asta am facut si acum.</blockquote><blockquote>Translation: I was afraid of the reaction that me sharing my opinions might bring on, then I was ashamed of this fear and the paltry thought that “It’s better to shut up then to say what I think”. And, given that I usually choose to do exactly the things that I fear most, that’s what I did now.</blockquote><p>Well, this is a cute explanation, I’ll give him that.</p><p>However, just because you are afraid of something, doesn’t mean that you have to do it. There is good reason why we’re afraid of things: fear helps avoid harm. That’s apparently why evolution has gifted us fear: to avoid situations that are dangerous, either to us, or to our close ones. Fear alone should never be a justification.</p><p>Then there’s the idea that “It’s better to shut up than to say what I think” is a paltry thought that one should be ashamed of. This idea is not only demonstrably false, but is also plain stupid. Only the Romanian culture, which, being an active part of, I’m certain Mr. Bucur is highly aware of, contains numerous variations on the “silence is golden” expression (and I am certain that every Romanian can think of both its literal translation and at least two others just off the top of their heads).</p><p>Indeed, it seems that finding the appropriate time to speak is such an integral part of human society (and has been so in all corners of the world, since the most ancient of times), that it is amazing how this argument didn’t get blasted off not just Facebook, but within the author’s own head, if not wile thinking it, at least after having written it on Facebook, before hitting Post.</p><p>Mostly, it is better to just shut up rather than say what you think, if you have no discernible expertise on the topic. There are real consequences to meddling with what is essentially a medical act, and, ever since people have started publicizing deaths in cases of notorious refusal to follow medical procedure, in spite of all warnings that that would be how the story would inevitably develop.</p><p>In a better world, these words would have been simply ignored and dismissed with the phrase “You’re an actor, dude, nobody cares what you think of vaccination and masks”, but we don’t live in such a world. So this attitude can only be considered a disservice.</p><p>A little note on this section: the author of the posts is an actor by trade, and studies. To the extent of my knowledge at this time, he does not have any studies or experience in either medicine, or in law (which will become relevant later). This is why I used “discernible expertise” a few paragraphs above. I might be wrong, of course, but, so far, there appears to be no indication towards that direction.</p><blockquote>Original Romanian text: Celor ce aleg sa injure si sa atace ii sfatuiesc sa se gandeasca la faptul ca in curand s-ar putea sa fie ei cei care nu vor mai avea libertatea de a exprima (sau chiar ataca) nici o idee sau o parere. Cred ca ne apropiem de acel moment si nu vreau sa particip la crearea lui.</blockquote><blockquote>Translation: Those who choose to curse and attack, I advise them to think that, soon, they might be the ones who don’t have the freedom to express (or even attack) an opinion or an idea. I believe we are getting close to that moment, and I do not wish to take part in its creation.</blockquote><p>Let’s put aside the fact that anyone who has seriously lived during the times of the Socialist Republic of Romania (up to 1989) will have rolled their eyes over a few times already by this point.</p><p>Somehow, the author believes that their freedom of expression is being restricted. Let us assume that he would face charges for his original post, and analyze why that: 1. Would be well within the rights of the authorities; and 2. Would not constitute a freedom of speech violation.</p><p>Romanian law defines criminal instigation, as applies here, as a public message that is undeniably targeted at provoking or directing the audience into committing a crime. As such, his initial statement can be considered as provocative towards not wearing a mask. While this, in itself, is not a crime, Romanian law also defines defeating the combatting of illness as not respecting the measures that have been established through legal procedures in order to combat diseases, if that has resulted in further spread of an ongoing disease.</p><p>It does not take a legal expert to figure out how to connect these two. The only reason why Mr. Bucur is not being prosecuted is that no direct causal link can be established between his post and an instance of spreading the disease. But, should anyone be hospitalized and indicated as the source of infection (with maybe some infected dead), and a public post (or video, because we like to boast) of him expressing that he got the idea from Mr. Bucur’s post, that problem would vanish right away.</p><p>Now, why would this not constitute a breach of free speech? Because of the principle upon which legal rights are based: your right stops where others’ higher ones are infringed. You have the right to drive a car to its maximum capacity, but you do not have the right to do that on a public road, where the risk of others being hurt or killed is maximized.</p><p>Similarly, you are not in right to express an opinion with the clear intent to provoke, while it may cause further spread of a disease.</p><p>And by far the most easily accessible excuse would be “Mr. Bucur did not know that his statement would have such an effect.” A valid argument, from a strictly logical perspective, but not a valid one from a legal perspective. You see, when establishing the guilty mindset (<em>mens rea</em>), one can establish either intention (which I honestly think is not the case here), but also culpability, which is far more interesting as an option. Two forms of it can be established: when the author foresees the possible effect of their actions, but invalidly dismisses them, or when the author does not foresee the possible effects of their actions, even though that could have happened, and should have happened. Which one do you think might best apply?</p><p>Well, both, really, depending on what Mr. Bucur might have been thinking at the time. Even if the first one can mot be proven under the circumstances, the second one need not even be proven: one year in the pandemic, thousands dead, authorities plastering every centimeter of public display space with calls to wear the mask and how easily the infection spreads, no sane person could dismiss that not only the author could have known the consequences of his actions, but that he also should have known them.</p><p>Lastly, one might say that the author didn’t really want to provoke with his comment (a rather strange argument, given that he begins his original post as “In case you didn’t have anyone to curse at…”), and we cannot know what went on in his mind, so the instigation charge might not hold, we actually can. Keep reading.</p><blockquote>Original Romanian text: Nu sustin ca decizia de a nu ma vaccina este cea corecta, dar sustin si apar libertatea de a lua singur aceasta decizie.</blockquote><blockquote>Translation: I don’t claim the choice to not vaccinate is the correct one, but I defend the freedom to make that choice.</blockquote><p>This is, in essence, a correct statement. If something is not mandatory by law, the choice of whether to do it or not should lie with each individual, regardless of whether or not it appears to be a good choice <em>a priori</em>, or it turns out to be a bad choice <em>a posteriori</em>.</p><p>In essence, this is what freedom means: the liberty to make choices of your own, unimpeded will, all while agreeing that every choice has costs, and that gains from that choice might actually be worth the costs for some people. In the specific case of the COVID-19 vaccine, <a href="https://link.medium.com/PcXhaoY3Pdb">I have covered that before</a>.</p><p>But notice something missing from the argument?</p><p>In the original statement, there were two claims: that he won’t get vaccinated, which is not mandatory, and which appears in this statement, and that he doesn’t wear a mask, which is mandatory, and which doesn’t appear in this statement.</p><blockquote>Original Romanian text: Nu incurajez pe nimeni sa nu poarte masca, dar nu sunt de acord cu aceasta ordonanta militara si consider ca traiesc intr-o societate in care inca am voie sa nu fiu de acord cu guvernul si cu deciziile lui si sa imi exprim public acest dezacord.</blockquote><blockquote>Translation: I don’t encourage anyone to not wear a mask, but I do not agree with this military ordinance [note: the term “military ordinance” is explained below] and I consider that I live in a society in which I still am allowed to disagree with the government and their decisions, and to publicly express this disagreement.</blockquote><p>That was very smart. The second sentence of the same paragraph has no legal connection to the first, in any of the concepts that it is presenting. While the first was about freedom of choice, the second one is about freedom of expression. But, put together, they appear to be related, and making the same kind of argument, when, in fact, they don’t.</p><p>This is obviously deceptive, but it is debatable as to whether or not it is intentional. Only time (and slip-ups) will tell.</p><p>Taken together, though, it is easy for a prosecutor to make a case of deceptive provocation, as it should be clear to any reader that the author knows that the two statements are not the same, and that they were carefully meshed together to appear that they are.</p><p>The second post, which appears to explain away the legal implication of the first, in fact, only makes matters more complicated. For starters, the deception is undeniably there, but even if it weren’t, and the argument would make sense from a legal perspective, it still cannot be considered an argument, because of its disconnection. The two posts were not delivered together, and, therefore, it cannot be ensured that someone who sees the first post will also see the justification in the second post. Anyone saying “well I only saw him writing about not wearing a mask” cannot be accused of taking things out of context, as, by way of how Facebook works, that was the whole context. This is further proven by the fact that the author took no steps to edit, amend or remove his first post.</p><p>However, even if none of this mattered from a legal standpoint, the argument is still wrong, in the sense that disagreeing with government measures does not mean you are no longer obliged to follow them. There are legal ways to change the rules, and legal procedures to follow, so, even if you don’t agree with a specific rule, you still have to follow it until it is repealed. That does not make you any less free to disagree, or to express disagreement, or to gather a community large enough to try to change things.</p><p>Addendum: the “military ordinance” that Mr. Bucur was talking about is a legal form of emergency rule enactment that can take place in situations of extreme emergency, while a state of emergency has been declared and is ongoing. By virtue of their definition, all such military ordinances lose their power once the state of emergency is no longer in effect. This means that, technically, Mr. Bucur is wrong as to the origin of the mandatory wearing of the mask, but, since it is still mandatory, albeit through a different legal procedure, this is not relevant to the arguments on either side.</p><blockquote>Original Romanian text: Stiu sigur ca mai sunt oameni care gandesc ca mine, dar fie le este teama sa se exprime public, fie prefera sa stea departe de online.</blockquote><blockquote>Translation: I know for sure that there are more people who think like me, but who are either afraid to go public, or prefer to stay far away from the online.</blockquote><p>This is, in my opinion, the final nail in the coffin of an argument against instigation. The very idea that something is done in order to bring out the people who think the same and would do the same cannot be considered anything other than instigation in the general sense. What can make it criminal is the nature of the opinion.</p><blockquote>Original Romanian text: Sunt un om cu familie, sunt artist, cred in Dumnezeu si in libertatea de expresie, sunt sustinator al luptei impotriva discrimarii si astea sunt valorile dupa care ma ghidez in viata.</blockquote><blockquote>Translation: I am a family man, an artist, i believe in God [note: the Christian god] and in freedom of expression, I support the fight against discrimination and these are the values by which I guide my life.</blockquote><p>So, those values don’t include respect for the law, apparently.</p><h4>Conclusion</h4><p>Why, one might ask, did I go through the trouble of analyzing an actor’s silly protest against government measures in the COVID-19 pandemic, and why did I inflate the criminal law dimensions of the two nu posts?</p><p>I mostly did that as the opportunity presented itself. Rarely does one come across a set of arguments that appear eloquent and to the point, but are really not.</p><p>This was, for me, a lesson on the wrong attitude towards the concept of free speech. You are still free to speak against something that you feel is wrong, but what was exercised here was not free speech.</p><p>It would have been better had he said “I won’t get vaccinated, and I hate wearing a mask” — a subtle difference, but a very important one — the second form does not imply action in defiance of the law, but only a sentiment.</p><p>And yes, before you ask, the criminal law matters of this post have been inflated to the level of purity of principle for the sake of the free speech argument. Do I think that there should be a criminal prosecution against the author? No, of course not. I have no reason to suspect malevolence on his part, nor do I think that he did it just for the sake of a publicity stunt. To the extent of my knowledge at this point, those posts reflect his sincere opinion (and justification), albeit worded in a careless way. But they were also a good lesson that most people need to learn.</p><p>Especially, Mr. Bucur’s posts are not the kind of grumpy, uneducated, defiant simpleton posts like “Ah dun’ wearin’ dem mesks, god’dang’it!” Not at all. They were far more eloquent and cultured than that, as is expected from a man of culture. And yes, he manages to convey a sentiment of choice and freedom. But all the arguments above against his expressed position still stand.</p><p>After all, a democratic community is built upon respect for the rule of law, wherever that law might come from. One cannot pick and choose what laws to respect, and this agreement that those are the sets of rules that we follow is critical. Yes, some people might not like some laws, but they are there for a reason, and they can be changed if necessary (as the protests against decriminalization of certain corruption crimes a few years back prove). Yes, some laws might not have the luxury to wait for them to be thoroughly debated by everyone interested. But this is democracy, I’m afraid.</p><p>Cheers, Mr. Bucur! I understand what you wanted to say, and a lot of us did, but some might not. Please choose your words better next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=455f9db21b0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>