<?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 Nelson Nobre on Medium]]></title>
        <description><![CDATA[Stories by Nelson Nobre on Medium]]></description>
        <link>https://medium.com/@NelsonBN?source=rss-222bd3f8465d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9VB_oVYxyGZ1bj-CjQ2mVA.png</url>
            <title>Stories by Nelson Nobre on Medium</title>
            <link>https://medium.com/@NelsonBN?source=rss-222bd3f8465d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:51:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@NelsonBN/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[How to run integration tests using Testcontainers with WSL]]></title>
            <link>https://medium.com/@NelsonBN/how-to-run-integration-tests-using-testcontainers-with-wsl-52c77a2acbbb?source=rss-222bd3f8465d------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c77a2acbbb</guid>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Nelson Nobre]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 15:46:42 GMT</pubDate>
            <atom:updated>2023-07-23T16:03:16.945Z</atom:updated>
            <content:encoded><![CDATA[<p>The purpose of this demo is to demonstrate how to run integration tests using Testcontainers with WSL. I won’t explain how you should write your tests using Testcontainers, my goal is just to show how to run them in WSL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*7bVZYUVzl0dF9Xkdstln7g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*JSR-A06Er4I4BFHXwgm-jg.jpeg" /></figure><h3>Issue</h3><p>Some people, when developing on Windows, use Docker Desktop, and in that case, the Docker daemon is running on the same machine as the IDE, and the tests are executed without any problem. However, when you are using WSL, the Docker daemon is running on a different machine, and in this case, Testcontainers cannot start the containers because it can’t connect to the Docker daemon.</p><h3>Solution</h3><h4>1. Expose the endpoint of the Docker daemon</h4><p>In WSL, create a file named <strong>daemon.json</strong> in the folder <strong>/etc/docker/</strong> with the following content:</p><pre>{<br>    &quot;hosts&quot;: [<br>        &quot;tcp://0.0.0.0:2375&quot;,<br>        &quot;unix:///var/run/docker.sock&quot;<br>    ]<br>}</pre><p>After that, restart the Docker daemon or WSL.</p><p>The previous step was obtained from <a href="https://gist.github.com/sz763/3b0a5909a03bf2c9c5a057d032bd98b7">here</a>.</p><h4>2. Configure testcontainers in test project</h4><p>In your integration tests project, you should have an extension of the <strong>WebApplicationFactory</strong> with configurations for <strong>Testcontainers</strong> similar to this:</p><pre>private readonly IContainer _dbContainer = new ContainerBuilder()<br>    .WithImage(DB_IMAGE)<br>    .WithName($&quot;db-integration-tests-{Guid.NewGuid().ToString()[^5..]}&quot;)<br>    .WithEnvironment(&quot;MYSQL_ROOT_PASSWORD&quot;, DB_ROOT_PASSWORD)<br>    .WithEnvironment(&quot;MYSQL_DATABASE&quot;, DB_DATABASE)<br>    .WithPortBinding(DB_HOST_PORT, DB_CONTAINER_PORT)<br>    .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(DB_CONTAINER_PORT))<br>    .Build();</pre><p>You just need to add the configuration of the Docker endpoint <strong>WithDockerEndpoint()</strong>, like this:</p><pre>private readonly IContainer _dbContainer = new ContainerBuilder()<br>    .WithImage(DB_IMAGE)<br>    .WithName($&quot;db-integration-tests-{Guid.NewGuid().ToString()[^5..]}&quot;)<br>#if RUN_LOCAL<br>    .WithDockerEndpoint(&quot;tcp://localhost:2375&quot;)<br>#endif<br>    .WithEnvironment(&quot;MYSQL_ROOT_PASSWORD&quot;, DB_ROOT_PASSWORD)<br>    .WithEnvironment(&quot;MYSQL_DATABASE&quot;, DB_DATABASE)<br>    .WithPortBinding(DB_HOST_PORT, DB_CONTAINER_PORT)<br>    .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(DB_CONTAINER_PORT))<br>    .Build();</pre><p>The <strong>RUN_LOCAL</strong> is a compilation symbol that I use to run the tests locally. In the CI pipeline, I don’t use it, so the tests are executed without the <strong>WithDockerEndpoint()</strong> configuration.</p><p>If you also want to run the conditional compilation symbol, you need to configure your symbol in the <strong>.csproj</strong> file of the integration tests project, like this:</p><pre>&lt;PropertyGroup Condition=&quot;&#39;$(COMPUTERNAME)&#39; != &#39;&#39;&quot;&gt;<br>  &lt;DefineConstants&gt;$(DefineConstants);RUN_LOCAL&lt;/DefineConstants&gt;<br>&lt;/PropertyGroup&gt;</pre><p>In that configuration, we use the <strong>COMPUTERNAME</strong> environment variable to check if the tests are running locally or not, because in the CI pipeline, this variable is not defined. With this approach, we can set the <strong>RUN_LOCAL</strong> compilation symbol only when the tests are running locally.</p><p>The remaining configurations of the <strong>Testcontainers</strong> are normal configurations that you also use when running directly on the host machine.</p><p>Full example is available on <a href="https://github.com/NelsonBN/demo-dotnet-integration-tests-with-testcontainers-wsl">my GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c77a2acbbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithms and Data StructuresBinary search]]></title>
            <link>https://medium.com/@NelsonBN/algorithms-and-data-structuresbinary-search-a12594183c0d?source=rss-222bd3f8465d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a12594183c0d</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nelson Nobre]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 15:40:13 GMT</pubDate>
            <atom:updated>2023-06-08T15:40:13.482Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algorithms and Data Structures — Binary search</h3><h3>What is binary search?</h3><p>Binary search is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.</p><p>The concept behind binary search is to “divide and conquer” continuously dividing the number of candidate elements in half at each iteration. This property enables the algorithm to have a time complexity of <strong>O(log n)</strong>.</p><h4><strong>Pros</strong></h4><ul><li><strong>O(log n)</strong> time complexity. It’s one of the fastest search algorithms;</li><li>It’s simple to implement;</li><li>It’s easy to understand;</li></ul><h4><strong>Cons</strong></h4><ul><li>It only works on sorted arrays;</li><li>Time complexity for insertion is <strong>O(log n)</strong>. I put this as a cons because exists algorithms with <strong>O(1)</strong> time complexity for insertion, but that is not a big deal for many cases because <strong>O(log n)</strong> is still very good performance;</li></ul><h4><strong>Requirements</strong></h4><ul><li>The array must be sorted;</li><li>To use the binary search algorithm, the array must be random-access, which means that elements can be accessed using their index;</li><li>The data stored in the array must be of a type that supports comparison. For example <strong>a &lt; b</strong>, <strong>a &gt; b</strong>, <strong>a == b</strong>;</li><li>The comparison used to search value in the array must be the same used to sort or insert values in the array;</li></ul><h4>Time complexity (Binary search vs. linear search)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loknQR-o8_0Q2tUcSHYIyQ.png" /></figure><h4><strong>Demo animation</strong></h4><p><a href="https://www.cs.usfca.edu/~galles/visualization/Search.html">Binary search vs linear search</a></p><h3>Interative implementation</h3><pre>static int BinarySearch(int[] array, int search)<br>{<br>    var left = 0;<br>    var right = array.Length - 1;<br><br>    while (left &lt;= right)<br>    {<br>        var middle = left + ((right - left) / 2);<br>        if (array[middle] == search)<br>        {<br>            return middle;<br>        }<br><br>        if (array[middle] &lt; search)<br>        {<br>            left = middle + 1;<br>        }<br>        else<br>        {<br>            right = middle - 1;<br>        }<br>    }<br><br>    return -1;<br>}</pre><h3>Recursive implementation</h3><pre>static int BinarySearch(int[] array, int search, int left, int right)<br>{<br>    while(left &lt;= right)<br>    {<br>        var middle = left + ((right - left) / 2);<br><br>        if(search == array[middle])<br>        {<br>            return middle;<br>        }<br><br>        if(search &gt; array[middle])<br>        {<br>            return BinarySearch(array, search, middle + 1, right);<br>        }<br><br>        return BinarySearch(array, search, left, middle - 1);<br>    }<br><br>    return -1;<br>}</pre><h3>Some tips to implement binary search</h3><h4>Found the middle index</h4><p>It is very common to see the middle index calculation as <strong>(left + right) / 2</strong>, but this is not the best way to do it. If the array is very large, the sum of <strong>left </strong>and <strong>right</strong> can overflow the maximum value of the integer type. To avoid this problem, we can use the following formula: <strong>left + ((right — left) / 2)</strong>.</p><p>Let’s break down this formula piece by piece to understand the problem.</p><pre>Console.WriteLine($&quot;MaxInt: {int.MaxValue:n0}&quot;); // MaxInt: 2 147 483 647<br><br>var left = int.MaxValue - 1_000;<br>var right = int.MaxValue - 300;<br><br>Console.WriteLine($&quot;left: {left:n0}&quot;); // left: 2 147 482 647<br>Console.WriteLine($&quot;right: {right:n0}&quot;); // right: 2 147 483 347<br><br>// Bad why<br>var badWhyStep1 = left + right;<br>Console.WriteLine($&quot;Bad why -&gt; left + right: {badWhyStep1:n0}&quot;); // Bad why -&gt; left + right: -1 302<br>var badWhyStep2 = badWhyStep1 / 2;<br>Console.WriteLine($&quot;Bad why -&gt; (left + right) / 2: {badWhyStep2:n0}&quot;); // Bad why -&gt; (left + right) / 2: -651<br><br>// Good why<br>var goodWhyStep1 = right - left;<br>Console.WriteLine($&quot;Good why -&gt; right - left: {goodWhyStep1:n0}&quot;); // Good why -&gt; right - left: 700<br>var goodWhyStep2 = goodWhyStep1 / 2;<br>Console.WriteLine($&quot;Good why -&gt; (right - left) / 2: {goodWhyStep2:n0}&quot;); // Good why -&gt; (right - left) / 2: 350<br>var goodWhyStep3 = left + goodWhyStep2;<br>Console.WriteLine($&quot;Good why -&gt; left + ((right - left) / 2): {goodWhyStep3:n0}&quot;); // Good why -&gt; left + ((right - left)) / 2: 2 147 482 997 // right: 2 147 483 147</pre><p>As you can see, for a large array, the <strong>left + right</strong> operation can overflow the maximum value of the integer type and return a worng value.</p><h4>Use shift operator</h4><p>In the built-in binary search implementation of some languages, you can see the use of the shift operator <strong>&gt;&gt; 1</strong> to divide the value by 2.<br>First we can do this because the shift operation <strong>&gt;&gt; 1</strong> is equivalent to the division by 2. Second because the bitwise operations are more close to the machine code and can be faster than the division operation.</p><p><strong>Before</strong></p><pre>var middle = left + ((right - left) / 2);</pre><p><strong>After</strong></p><pre>var middle = left + ((right - left) &gt;&gt; 1);</pre><h4>Return the complement of the index if the value is not found</h4><p>In the previous examples, I returned <strong>-1</strong> when the value was not found. Using the condition <strong>index &lt; 0</strong> serves as an indicator that the value was not located. However, suppose we also want to use the same implementation to identify the next suitable index for inserting the value. In this scenario, the index <strong>-1</strong> is not particularly helpful.</p><p>We know that when we attempt to search for a value in our sorted array, the algorithm will halt either when it finds the value or when it doesn’t. If the value is not found, the left index will point to the position where the value should be inserted.</p><p>With this in mind, if the value is not found, we can simply use the <strong>~</strong> operator. This operator inverts all bits, including the sign bit, resulting in a negative value. We can use this negative value to signify that the value was not found. However, if we apply the complement operation once more, we obtain the position where the value should be inserted. This approach allows us to use the same implementation for both finding a value and determining the next possible insertion point.</p><pre>public void Add(int item)<br>{<br>    var position = Search(item);<br>    if(position &lt; 0)<br>    {<br>        position = ~position;<br>    }<br>    items.Insert(position, item);<br>}<br><br>public int Search(int item)<br>{<br>    // ...<br>    // When the value is not found<br>    return ~left;<br>}</pre><h4>Binary search is not only for numbers</h4><p>The binary search algorithm does not work only with numbers. It can be used with any type of data that supports comparison. For example in C# you can a class and implement the <strong>IComparable</strong> interface to to define the comparison logic.</p><pre>public int BinarySearch(T item)<br>{<br>    var left = 0;<br>    var right = _items.Count - 1;<br><br>    while(left &lt;= right)<br>    {<br>        var middle = left + ((right - left) &gt;&gt; 1);<br><br>        if(_items[middle].CompareTo(item) == 0)<br>        {<br>            return middle;<br>        }<br><br>        if(_items[middle].CompareTo(item) &lt; 0)<br>        {<br>            left = middle + 1;<br>        }<br>        else<br>        {<br>            right = middle - 1;<br>        }<br>    }<br><br>    return ~left;<br>}<br><br>public class Person : IComparable&lt;Person&gt;<br>{<br>    public string? FirstName { get; set; }<br>    public string? LastName { get; set; }<br>    public int Age { get; set; }<br><br>    public int CompareTo(Person? other)<br>    {<br>        if(other is null)<br>        {<br>            return -1;<br>        }<br><br>        var result = Age.CompareTo(other.Age);<br>        if(result != 0)<br>        {<br>            return result;<br>        }<br><br>        result = compareTo(FirstName, other?.FirstName);<br>        if(result != 0)<br>        {<br>            return result;<br>        }<br><br>        return compareTo(LastName, other?.LastName);<br><br><br>        static int compareTo(string? left, string? right)<br>        {<br>            if(left is null &amp;&amp; right is null)<br>            {<br>                return 0;<br>            }<br><br>            if(left is null)<br>            {<br>                return -1;<br>            }<br><br>            if(right is null)<br>            {<br>                return 1;<br>            }<br><br>            return left.CompareTo(right);<br>        }<br>    }<br>}</pre><p>Full example is available on <a href="https://github.com/NelsonBN/algorithms-data-structures-binary-search">my GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a12594183c0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to securely set environment variables from a .env file in Docker Compose]]></title>
            <link>https://medium.com/@NelsonBN/how-to-securely-set-environment-variables-from-a-env-file-in-docker-compose-13f2f28e5c46?source=rss-222bd3f8465d------2</link>
            <guid isPermaLink="false">https://medium.com/p/13f2f28e5c46</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[configuration-file]]></category>
            <dc:creator><![CDATA[Nelson Nobre]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 19:51:18 GMT</pubDate>
            <atom:updated>2023-06-08T15:36:53.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to securely set environment variables from a .env file in Docker Compose</h3><p>Nowadays, working with code repos is a reality for everyone. Docker is another technology that is highly prevalent in the daily lives of programmers. It has become common practice to use a docker-compose file to easily run the environment. However, issues arise when these environments require sensitive configuration information. Often, developers resort to hardcoding this information, which can lead to accidentally committing it to the repository. While it is possible to remove this information from remote repos, it is still a significant headache. Prevention is the best solution.</p><h3>The solution</h3><ol><li>First we will simulate an application using environment variables. For this we will create a simple Dockerfile that will print the environment variables.</li></ol><pre>FROM alpine:latest<br>CMD echo &quot;My name is $NAME, I am from $COUNTRY and I am a $JOB.&quot;d</pre><p>2. Now we will create our docker-compose. The docker-compose will be the entry point for our application. We will use the.</p><pre>```yaml<br>version: &#39;3.9&#39;<br><br>services:<br>  demo:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    environment:<br>      - NAME=${NAME}<br>      - COUNTRY=${COUNTRY}<br>      - JOB=${JOB}</pre><p><strong>Note:</strong> We are using the <strong>${}</strong> syntax to reference the environment variables from the <strong>.env</strong> file.</p><p>3. Now we will create our <strong>.env</strong> file. This file will contain the environment variables that we want to use in our application.</p><pre>NAME=Nelson<br>COUNTRY=Portugal<br>JOB=Developer</pre><p>4. Let’s run our environment.</p><pre>docker-compose up --build</pre><p>If everything went well, you should see the following output:</p><pre>demo_1  | My name is DSKT-NelsonBN, I am from Portugal and I am a Developer.</pre><p>5. To finish, we will add the <strong>.env</strong> file to the <strong>.gitignore</strong> file.</p><pre>echo &quot;.env&quot; &gt;&gt; .gitignore</pre><p><strong>Note:</strong> Now you can see that your <strong>.env</strong> file is no longer visible in the git status.</p><p><strong>Note:</strong> In my demo the file is versioned, so we can see all the configuration. However, in your case, the file should not be versioned.</p><p>6. You can test using the command:</p><pre>git status</pre><p>Full example is available on my <a href="https://github.com/NelsonBN/demo-docker-env-file">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13f2f28e5c46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variable scopes in C#]]></title>
            <link>https://medium.com/@NelsonBN/variable-scopes-in-c-8f7c7bbeecb1?source=rss-222bd3f8465d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7c7bbeecb1</guid>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[varaibles-scopes]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Nelson Nobre]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 23:26:51 GMT</pubDate>
            <atom:updated>2023-04-09T23:26:51.525Z</atom:updated>
            <content:encoded><![CDATA[<p>Nowadays, this topic is confused with the lifecycle of the container of dependency injection because one of the lifecycles of the container is called “scope”. But it’s not the same thing, it is a concept that is related to the variables.</p><p>In C#, you have three types of scopes for variables:</p><ul><li>Class level;</li><li>Method level;</li><li>Block level;</li></ul><h3>Class level</h3><p>A variable has class level when it is declared outside of any method or constructor.</p><ul><li>A variable declared with class level can be accessed inside a method or constructor;</li><li>Non-static variables declared with class level only can be accessed by non-static methods or constructors inside the same class;</li><li>Variables declared with class level can be accessed outside of the class depending on the access level. For example, public, internal, etc.</li></ul><p><strong>Example:</strong></p><pre>var demoClass = new DemoClass();<br>demoClass.Method();<br>Console.WriteLine($&quot;Outside: {demoClass.Variable}&quot;);<br><br>class DemoClass<br>{<br>    // This is a class level variable<br>    public string Variable = &quot;Hello World!&quot;;<br><br>    public DemoClass()<br>    {<br>        Console.WriteLine($&quot;Constructor: {Variable}&quot;);<br>    }<br><br>    public void Method()<br>    {<br>        Console.WriteLine($&quot;Method: {Variable}&quot;);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Constructor: Hello World!<br>Method: Hello World!<br>Outside: Hello World!</pre><h3>Method level</h3><p>Variables declared inside a method or constructor have method level.</p><ul><li>Variables with scope method level also called local variables;</li><li>Variables declared with method level can be accessed inside the same method or constructor. Outside the method or constructor will not be accessible;</li><li>We can declare a variable with the same name as a class level inside a method or constructor and will be an independent variable. In this case we can use the keyword <em>this </em>to access the class level variable. For example: <em>this.Variable</em>;</li></ul><p><strong>Example:</strong></p><pre>var demoClass = new DemoClass();<br>demoClass.Method1();<br>demoClass.Method2();<br><br>class DemoClass<br>{<br>    string Variable = &quot;Hello galaxy!&quot;;<br><br>    public DemoClass()<br>    {<br>        string Variable = &quot;Hello planet earth!&quot;;<br>        Console.WriteLine($&quot;Constructor: {Variable}&quot;);<br>    }<br><br>    public void Method1()<br>    {<br>        string Variable = &quot;Hello world!&quot;;<br>        int year = 2023;<br>        Console.WriteLine($&quot;Method1: {Variable} - {year}&quot;);<br>    }<br><br>    public void Method2()<br>    {<br>        string Variable = &quot;Hello universe!&quot;;<br>        Console.WriteLine($&quot;Method2: {Variable}&quot;);<br>        Console.WriteLine($&quot;Method2 class level: {this.Variable}&quot;);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Constructor: Hello planet earth!<br>Method1: Hello world! - 2023<br>Method2: Hello universe!<br>Method2 class level: Hello galaxy!</pre><h3>Block level</h3><p>The previous two scopes I believe are easy to understand and that is not strange for anyone. In this last scope, everyone uses it, but few are aware of its real existence.</p><p>But what really is a block level? A block is a group of statements between braces <em>{}</em>. For example, the body of a <em>loop</em>, <em>if statemen</em>, <em>try..catch</em>, <em>using</em>, etc. Or when we use only <em>{}</em>.</p><p><strong>Example:</strong></p><pre>var demoClass = new DemoClass();<br>demoClass.Method();<br><br>class DemoClass<br>{<br>    string Variable = &quot;Hello class!&quot;;<br><br>    public void Method()<br>    {<br>        Console.WriteLine(Variable);<br>        if (true)<br>        {<br>            string Variable = &quot;Hello block!&quot;;<br>            Console.WriteLine(Variable);<br>        }<br><br>        for(int i = 0; i &lt; 2; i++)<br>        {<br>            string Variable = $&quot;Hello {i}!&quot;;<br>            Console.WriteLine(Variable);<br>        }<br><br>        try<br>        {<br>            string Variable = &quot;Hello try!&quot;;<br>            Console.WriteLine(Variable);<br>        }<br>        catch (Exception)<br>        {<br>            string Variable = &quot;Hello catch!&quot;;<br>            Console.WriteLine(Variable);<br>        }<br>        finally<br>        {<br>            string Variable = &quot;Hello finally!&quot;;<br>            Console.WriteLine(Variable);<br>        }<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>Hello class!<br>Hello block!<br>Hello 0!<br>Hello 1!<br>Hello try!<br>Hello finally!</pre><p>Who has never declared a variable outside the <em>try..catch</em> to be able to access it after executing it? Yeah, the reason for that is the block scope.</p><pre>string variable = null;<br>try<br>{<br>    variable = &quot;Hello try!&quot;;<br>    // ...<br>}<br>catch (Exception)<br>{<br>    // ...<br>}<br>Console.WriteLine(variable);</pre><p>One thing few people know is that we don’t need to have a statement like a <em>loop </em>or <em>condition</em> to have a defined block. We can use only <em>{}</em>.</p><p><strong>Example:</strong></p><pre>var var0 = &quot;Hello level0!&quot;;<br>Console.WriteLine($&quot;L0 {var0}&quot;);<br><br>{<br>    var var1 = &quot;Hello level1!&quot;;<br>    Console.WriteLine($&quot;L1.1 {var1}&quot;);<br>    Console.WriteLine($&quot;L1.1 {var0}&quot;);<br><br>    {<br>        var var2 = &quot;Hello level2!&quot;;<br>        Console.WriteLine($&quot;L2 {var2}&quot;);<br>        Console.WriteLine($&quot;L2 {var1}&quot;);<br>        Console.WriteLine($&quot;L2 {var0}&quot;);<br><br>        {<br>            var var3 = &quot;Hello level3!&quot;;<br>            Console.WriteLine($&quot;L3 {var3}&quot;);<br>            Console.WriteLine($&quot;L3 {var2}&quot;);<br>            Console.WriteLine($&quot;L3 {var1}&quot;);<br>            Console.WriteLine($&quot;L3 {var0}&quot;);<br>        }<br>    }<br>}<br><br>{<br>    var var1 = &quot;Hello level1.2!&quot;;<br>    Console.WriteLine($&quot;L1.2 {var1}&quot;);<br>    Console.WriteLine($&quot;L1.2 {var0}&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>L0 Hello level0!<br>L1.1 Hello level1!<br>L1.1 Hello level0!<br>L2 Hello level2!<br>L2 Hello level1!<br>L2 Hello level0!<br>L3 Hello level3!<br>L3 Hello level2!<br>L3 Hello level1!<br>L3 Hello level0!<br>L1.2 Hello level1.2!<br>L1.2 Hello level0!</pre><p>To finalize, let’s go to understand the allowed accesses of the block levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*gOClNGDGl_hF2LI4Bpay1A.png" /></figure><p>The previous code does not compile. It is only for we understand this examaple.</p><p>The nested blocks can access the variables of the upper blocks, but the upper blocks cannot access the variables of the nested blocks.</p><p>All examples are available on my <a href="https://github.com/NelsonBN/doc-csharp-variable-scopes">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7c7bbeecb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reclaim space used by WSL]]></title>
            <link>https://medium.com/@NelsonBN/reclaim-space-used-by-wsl-8163850cdcb?source=rss-222bd3f8465d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8163850cdcb</guid>
            <category><![CDATA[wsl-2]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[wsl]]></category>
            <dc:creator><![CDATA[Nelson Nobre]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 19:48:16 GMT</pubDate>
            <atom:updated>2023-04-02T19:48:16.606Z</atom:updated>
            <content:encoded><![CDATA[<p>It is known that WSL 2 has a caracteristic that it does not free the space even after recovering some space within WSL distribution. So this will consume space on the host machine that is not being used. So we need to solve this issue manually.<br>This manual was created based on <strong>Ubuntu 20.04</strong> and <strong>WSL 2</strong>.</p><h3>Tips to free up space</h3><h4>Free up space used by docker</h4><p>One of the main reason we use WSL is to use docker. Se we end up consuming many spaces in downloading images, volumes, containers, etc. For our tests.</p><p>We can check the space used by docker with the following command:</p><pre>docker system df<br><br># Only volumes<br>docker system df -v</pre><p>Can do is to remove all we dot not need anymore. To do this we can use the following commands:</p><pre>docker system prune -a --volumes</pre><p>This will remove all unused containers, networks, and images. By default, the prune command does not remove volumes to prevent data loss. But we can use the <strong>— volumes </strong>flag to remove all unused volumes.</p><p>Or remove individually:</p><pre># Remove all unused containers<br>docker container prune<br><br># Remove all unused networks<br>docker network prune<br><br># Remove all unused images<br>docker image prune<br><br># Remove all unused volumes<br>docker volume prune</pre><h4>Free up spaces used by Docker Logs</h4><pre>truncate -s 0 /var/lib/docker/containers/**/*-json.log</pre><h3>Analyse the space used by distribution</h3><p>The following command will analyse the space used by the distribution and show the top 10 biggest folders:</p><pre>du -h &lt;Folder to analyse&gt; | sort -rh | head -n 10<br><br># Example for the root folder<br>du -h / | sort -rh | head -n 10</pre><p>Normally the WSL distribution has the host machine’s disk mounted on <strong>/mnt</strong><br>You can prevent the previous command to analyse the host machine’s disk by using the following command:</p><pre>du -h / --exclude /mnt | sort -rh | head -n 10</pre><h3>Compact the WSL distribution</h3><p>First stop the WSL</p><pre>wsl --shutdown</pre><p>Then find the disk of the distribution</p><pre>cd C:\Users\%PROFILE%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows_79rhkp1fndgsc\LocalState\</pre><p>You will see a file called <strong>ext4.vhdx</strong> that is the disk of the distribution.<br>You will be able to verify that even after freeing up space within the distribution, the disk is still large.</p><p>To compact the disk we can use the following command:</p><pre>optimize-vhd -Path .\ext4.vhdx -Mode full</pre><p>Sometimes the previous command may not be available.<br>In this case we can use the following steps:</p><p>First a file script. I am using the <strong>vscode </strong>but you can use any text editor.</p><pre>code ./disk-compression.script</pre><p>Paste the following script and save it:</p><pre>select vdisk file=&quot;C:\Users\%username%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows_79rhkp1fndgsc\LocalState\ext4.vhdx&quot;<br>attach vdisk readonly<br>compact vdisk<br>detach vdisk</pre><p>Then run the script as <strong>administrator</strong>:</p><pre>diskpart /s ./disk-compression.script</pre><p><strong><em>IMPORTANT:</em></strong> Make sure the file <strong>ext4.vhdx</strong> is not used during this process so as not to corrupt the disk.</p><p>You can follow this and other tips on my <a href="https://github.com/NelsonBN/tool-tips/blob/main/Tools/WSL/wsl2-reclaim-space-used.md">github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8163850cdcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skip and Take in Linq of .NET]]></title>
            <link>https://medium.com/@NelsonBN/skip-and-take-in-linq-of-net-3622bddff0ca?source=rss-222bd3f8465d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3622bddff0ca</guid>
            <category><![CDATA[linq]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[collections-in-c-sharp]]></category>
            <dc:creator><![CDATA[Nelson Nobre]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 19:08:48 GMT</pubDate>
            <atom:updated>2023-03-18T19:08:48.167Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Skip and Take in Linq of .NET</strong></h3><h3>What is it?</h3><p><strong>Skip()</strong> and <strong>Take()</strong> are simples methods presents in <strong>System.Linq</strong> library of the <strong>.NET</strong> that allows to work with collections in a very expressive way.</p><h3>Skip()</h3><p>The <strong>Skip()</strong> method allows to skip a number of elements from the beginning of a collection.</p><h4>Skip some elements in a list</h4><pre>var list1 = new List&lt;char&gt; { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39; };<br><br>// [D, E, F, G]<br>var result1 = list1.Skip(3);</pre><h4>Skip more than the collection has</h4><p>If you skip more elements than the collection has, you will get an empty collection.</p><pre>var list2 = new List&lt;char&gt; { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39; };<br><br>// []<br>var result2 = list2.Skip(30);</pre><h4>Skip while a condition is true</h4><pre>var list3 = new List&lt;int&gt; { 1, 2, 3, 4, 5, 4, 3, 2, 1 };<br><br>// [3, 4, 5, 4, 3, 2, 1]<br>var result3 = list3.SkipWhile(c =&gt; c &lt; 3);</pre><p>Notice that in the next example all elements are returned because for the first element the condition was false, so it stopped skipping immediately on the first element.</p><pre>var list4 = new List&lt;int&gt; { 1, 2, 3, 4, 5, 4, 3, 2, 1 };<br><br>// [1, 2, 3, 4, 5, 4, 3, 2, 1]<br>var result4 = list4.SkipWhile(c =&gt; c &gt; 1);</pre><h3>Take()</h3><p>The <strong>Take()</strong> method allows to take a number of elements of a collection.</p><h4>Take some elements from a list</h4><pre>var list5 = new List&lt;char&gt; { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39; };<br><br>// A, B, C, D]<br>var result5 = list5.Take(4);</pre><h4>Take more than the collection has</h4><p>There is no problem to take more elements than the collection has, because the `Take` method will return all elements of the collection.</p><pre>var list6 = new List&lt;char&gt; { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39; };<br><br>// [A, B, C, D, E, F, G]<br>var result6 = list6.Take(30);</pre><p>Notice that in this example any elements are returned because the first element that didn’t match the condition, so it stopped taking immediately on the first element.</p><pre>var list8 = new List&lt;int&gt; { 1, 2, 3, 4, 5, 4, 3, 2, 1 };<br><br>// []<br>var result8 = list8.TakeWhile(c =&gt; c &gt; 4);</pre><h4>Take a range of elements from a list</h4><pre>var list9 = new char[] { &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39; };<br><br>// [C, D, E]<br>var result9_1 = list9.Take(2..4);<br>var result9_2 = list9[2..4]; // This syntax is only available for arrays</pre><p><strong>list9[2..4]</strong> is the syntax suger for <strong>list9[new Range(2, 4)]</strong>.</p><p>The syntax for <strong>Range</strong> is <strong>new Range(start, end)</strong>:</p><ul><li><strong>start</strong> is the index of the first element to be taken (inclusive);</li><li><strong>end</strong> is the index of the last element to be taken (exclusive)</li></ul><h3>Some more examples</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd96be4d5402bfeefd952a5853ebbe07/href">https://medium.com/media/fd96be4d5402bfeefd952a5853ebbe07/href</a></iframe><h3>Conclusion</h3><p>The syntax such as <strong>Range</strong> definitely makes the code cleaner, but that doesn’t mean it should be used. Because in some cases it increases the difficulty of interpreting the code by other programmers. The decision to use certain syntaxes (e.g. very recent syntaxes), must consider how much all the team members or people who will maintain the code in the future, are or will be familiarized with the syntax. If you really want to modernize your code, first familiarize your team with new syntax you want to use. That way you ensure that everyone on your team remains productive.</p><p>All examples are available on my <a href="https://github.com/NelsonBN/doc-csharp-skip-take">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3622bddff0ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swap variables elegantly in C#]]></title>
            <link>https://medium.com/@NelsonBN/swap-variables-elegantly-in-c-c7aa7c7fb651?source=rss-222bd3f8465d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7aa7c7fb651</guid>
            <dc:creator><![CDATA[Nelson Nobre]]></dc:creator>
            <pubDate>Sat, 22 Oct 2022 15:16:29 GMT</pubDate>
            <atom:updated>2022-10-22T15:21:05.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKEb9B0uN0pjea0fcSy9KQ.png" /></figure><p>Have you ever needed to swap two variables? Probably yes, and probably you used the classic way, creating a temporary variable to store one of the values and then swap them.</p><p>Something like this:</p><pre>using static System.Console;</pre><pre>var a = 10;<br>var b = 20;</pre><pre>var aux = a;<br>a = b;<br>b = aux;<br> <br>WriteLine(a); // 20<br>WriteLine(b); // 10</pre><p><a href="https://dotnetfiddle.net/WnQkw6">Test here</a></p><h4>Do you know you can do it in a more elegant way?</h4><p>Tuple is a resource in C# you can encapsulate multiple values in a single variable without the need to create a struct, class or record for it.</p><pre>using static System.Console;</pre><pre>var person = GetPerson();<br> <br>WriteLine(person.Name);<br>WriteLine(person.Age);<br> <br>(string Name, int Age) GetPerson()<br>{<br>    return (&quot;Nelson&quot;, 30);<br>}</pre><p><a href="https://dotnetfiddle.net/OJlVlH">Test here</a></p><p>And tuple has a capabilty named <strong>Deconstruct </strong>that allows you to extract the values from a tuple into separate variables. Let me show you one example:</p><pre>using static System.Console;</pre><pre>var person = new Person(&quot;Name&quot;, 30);</pre><pre>(var name, var age) = person;</pre><pre>WriteLine(name);<br>WriteLine(age);</pre><pre>public class Person<br>{<br>  public string Name { get; set; }<br>  public int Age { get; set; }</pre><pre>  public Person(string name, int age)<br>  {<br>    Name = name;<br>    Age = age;<br>  }</pre><pre>  public void <strong>Deconstruct</strong>(out string name, out int age)<br>  {<br>    name = Name;<br>    age = Age;<br>  }<br>}</pre><p><a href="https://dotnetfiddle.net/gUZ1hR">Test here</a></p><p>With these two amazing features we can create a clean and readable code like this:</p><pre>using static System.Console;</pre><pre>var a = 10;<br>var b = 20;</pre><pre>(a, b) = (b, a);<br> <br>WriteLine(a); // 20<br>WriteLine(b); // 10</pre><p><a href="https://dotnetfiddle.net/VpSyS6">Test here</a></p><h4>Maybe you are asking “What’s performance difference?”</h4><p><strong>For primitive types</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*STu13noY6fQCgYQedrtKSQ.png" /></figure><p><strong>For classes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*XK1tR8iUKtrJvOWciGLuVA.png" /></figure><p>How we can see in the bencmark, the performance difference is not measurable. And the difference probably was caused by my machine. If I run the benchmark again, the results will benefit the other approach.</p><h4>Let’s also check the IL code generated by the compiler for both approaches:</h4><p><strong>For primitive types</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*xfysEDNxRjf8a_5xisIlyA.png" /></figure><p><a href="https://sharplab.io/#v2:C4LglgNgPgAgTARgLACgYGYAE9MGFMDeqmJ2WMALJgLIAUAlIcaSwG4CGATpu5gLyYEABgDczFiQ7cARv0xxR4iUpa12AGkzTGA2tM3t6YlCwC+qU0A=">Check here the resulted IL</a></p><p><strong>For classes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*8PxOCi5oY7rWpmVcUv6kFg.png" /></figure><p><a href="https://sharplab.io/#v2:C4LglgNgPgAgTARgLACgYGYAE9MGFMDeqmJ2WMALJgLIAUAlIcaSwG4CGATpu5gLyYEABgDczFiQ7cARv0xxR4iUrZceAVwAec9mJQTSvAdL0GSsgey2nSAX1S2gA===">Check here the resulted IL</a></p><p>If the performance is not measurable, choose the most readable and less error prone approach.</p><p>The example project is available on <a href="https://github.com/NelsonBN/doc-csharp-swap-variables">GitHub</a>.</p><h4>References</h4><ul><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples">Tuple types (C# reference)</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct">Deconstructing tuples and other types</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7aa7c7fb651" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>