<?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 Belarmino Silva on Medium]]></title>
        <description><![CDATA[Stories by Belarmino Silva on Medium]]></description>
        <link>https://medium.com/@silva.belarmino?source=rss-5c0eb44c3c36------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dkA0sPTxU40UakvBH2ab3Q.jpeg</url>
            <title>Stories by Belarmino Silva on Medium</title>
            <link>https://medium.com/@silva.belarmino?source=rss-5c0eb44c3c36------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 20:32:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@silva.belarmino/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[Vulnerabilidades surgem todos os dias. A sua empresa está preparada?]]></title>
            <link>https://medium.com/@silva.belarmino/vulnerabilidades-surgem-todos-os-dias-a-sua-empresa-est%C3%A1-preparada-529c685796a5?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/529c685796a5</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[cibersecurity]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 18:53:18 GMT</pubDate>
            <atom:updated>2026-11-21T18:57:06.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVyAFUQ0QI5UQNrLxnrKHA.jpeg" /></figure><p><em>Manter os sistemas atualizados já não é apenas uma boa prática tecnológica. É uma questão de segurança, continuidade e responsabilidade empresarial.</em></p><p>As ameaças digitais evoluem constantemente. Todos os dias são identificadas novas vulnerabilidades em sistemas operativos, frameworks, bibliotecas e aplicações utilizadas pelas empresas.</p><p>Neste cenário, uma questão merece a atenção de todos os responsáveis tecnológicos: <strong>a sua empresa está preparada para responder a estas ameaças?</strong></p><p>Ter sistemas em funcionamento não significa necessariamente que estejam seguros. Uma aplicação pode continuar a funcionar normalmente, mesmo utilizando componentes que já não recebem atualizações de segurança.</p><p>É aqui que a gestão do ciclo de vida das tecnologias assume particular importância.</p><h3>O fim do suporte também é um risco de segurança</h3><p>Quando uma tecnologia termina o seu período de suporte open source, deixa de receber, nesse modelo, as atualizações públicas de segurança e correções de erros.</p><p>É importante esclarecer que o <strong>Spring Boot, por exemplo, é um projeto open source, distribuído sob a licença Apache 2.0, e não possui uma edição comercial separada do código-base</strong>.</p><p>O que existe é suporte comercial, disponibilizado pela Broadcom através do ecossistema Tanzu, que permite prolongar a manutenção e disponibilizar correções para determinadas versões antigas.</p><p>Assim, as empresas podem continuar a utilizar versões anteriores mediante suporte comercial, mas também devem avaliar os custos, os riscos e a necessidade de migração.</p><h3>Um exemplo concreto: a evolução para Spring Boot 4</h3><p>O ecossistema Spring demonstra bem a importância desta questão.</p><p>Com o fim do suporte open source das linhas Spring Boot 3.5 e Spring Framework 6.2, a evolução para Spring Boot 4 e Spring Framework 7 torna-se particularmente relevante.</p><p>A descoberta de vulnerabilidades como a <strong>CVE-2026–47884</strong>, relacionada com SSRF e execução remota de código em determinadas configurações, e a <strong>CVE-2026–47890</strong>, relacionada com streams Server-Sent Events, reforça a necessidade de acompanhar as versões e aplicar as correções disponíveis.</p><p>A nova geração do Spring Framework disponibiliza as correções correspondentes na linha open source, permitindo às organizações evoluir para uma base tecnológica com manutenção pública.</p><p>Mas migrar não significa simplesmente alterar uma versão. É necessário avaliar dependências, adaptar o código, executar testes automatizados e garantir que as aplicações continuam a funcionar corretamente.</p><h3>O que as empresas devem fazer?</h3><p>Existem quatro medidas fundamentais:</p><ol><li><strong>Monitorizar vulnerabilidades:</strong> acompanhar regularmente os alertas de segurança das tecnologias utilizadas.</li><li><strong>Controlar o ciclo de vida:</strong> identificar componentes sem suporte e planear a sua substituição ou migração.</li><li><strong>Automatizar a segurança:</strong> integrar ferramentas nos processos de desenvolvimento para identificar as vulnerabilidades.</li><li><strong>Planear atualizações:</strong> realizar migrações controladas, com testes e validações antes da entrada em produção.</li></ol><h3>Conclusão</h3><p>A segurança digital não depende apenas de firewalls, antivírus ou mecanismos de controlo de acesso. Depende também da qualidade, atualização e manutenção das tecnologias que sustentam os sistemas de informação.</p><p>Adiar atualizações pode parecer uma forma de reduzir custos no imediato, mas acumular dependências desatualizadas aumenta os riscos e pode tornar futuras migrações muito mais dispendiosas.</p><p><strong>A pergunta não é se a sua empresa será confrontada com novas vulnerabilidades, mas se estará preparada para responder quando elas forem descobertas.</strong></p><p>Manter os sistemas atualizados é investir na segurança, na continuidade operacional e na confiança dos clientes.</p><p><em>Referências técnicas:</em></p><ul><li><a href="https://spring.io/support-policy">Spring — Política de suporte</a></li><li><a href="https://github.com/spring-projects/spring-boot">Spring Boot — Código-fonte e licença Apache 2.0</a></li><li><a href="https://spring.io/security/cve-2026-47884/">CVE-2026–47884</a></li><li><a href="https://spring.io/security/cve-2026-47890/">CVE-2026–47890</a></li></ul><p>#CyberSecurity #DevSecOps #SpringBoot #SoftwareEngineering #OpenSource #Technology</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=529c685796a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Environment Variables Are Essential in .NET Core Applications]]></title>
            <link>https://medium.com/@silva.belarmino/why-environment-variables-are-essential-in-net-core-applications-dada94a3db66?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/dada94a3db66</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 15:37:34 GMT</pubDate>
            <atom:updated>2026-02-26T15:37:34.612Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Environment Variables Matter?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5nd0yTvl1xxnn0Of0wLqQ.png" /></figure><h4>Introduction</h4><p>Environment variables are one of the pillars for building modern, secure, and easily configurable .NET Core applications. They allow you to separate configuration from code, adapt application behavior across different environments, and protect sensitive information. In this article, we’ll see in practice how to combine .NET environment variables, Docker, and Docker Compose to manage dynamic configurations in a clean, scalable way that aligns with industry best practices.</p><p>Using environment variables aligns directly with the <em>The Twelve-Factor App</em> manifesto, especially regarding configuration:</p><ul><li>External configuration: separate configuration from source code;</li><li>Multiple environments: same code, different behaviors;</li><li>Security: keep secrets out of the repository.</li></ul><p>This approach makes the application more portable, predictable, and secure. With environment variables, you can adapt the application without recompiling it for different environments such as Development, Staging, and Production.</p><h4>.NET Core Application</h4><p>In .NET Core applications, we use the appsettings.json or appsettings.{Environment}.json files to define environment-specific configurations (e.g., Development, Staging, Production).</p><p>Here’s an example of an appsettings.json file:</p><pre>{<br>  &quot;Keycloak&quot;: {<br>    &quot;Url&quot;: &quot;http://keycloak&quot;<br>  },<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;,<br>  &quot;Kestrel&quot;: {<br>    &quot;Endpoints&quot;: {<br>      &quot;Https&quot;: {<br>        &quot;Url&quot;: &quot;https://0.0.0.0:443&quot;<br>      },<br>      &quot;Http&quot;: {<br>        &quot;Url&quot;: &quot;http://0.0.0.0:8080&quot;<br>      }<br>    }<br>  }<br>}</pre><p>.NET Core includes a powerful built-in configuration system. The example below shows how to access the Url property inside the Keycloak section:</p><pre>app.MapGet(&quot;/test&quot;, () =&gt;<br>{<br>    return &quot;HELLO : &quot;.Concat(app.Configuration[&quot;Keycloak:Url&quot;]);<br>})<br>.WithName(&quot;test&quot;)<br>.WithOpenApi();</pre><p>The same line can read data from appsettings or from an environment variable.</p><p>Until this point, the project works normally in a local environment. However, when deploying, you often need different Keycloak URLs for Development, Staging, and Production.</p><p>You can test and consume the endpoint with:</p><pre>curl https://localhost:8443/test</pre><h4>Environment Variables</h4><p>This is where environment variables become essential, especially when integrating the project into a CI/CD pipeline. It’s common to create a .env file in the project with variables for each environment:</p><pre>KEYCLOAK_URL=http://keycloak<br>CERTIFICATE_PASSWORD=1234</pre><h4>Self-Signed Certificate</h4><p>To support HTTPS, generate a self-signed certificate. The .NET SDK provides commands for this:</p><pre># Generate a self-signed certificate<br>dotnet dev-certs https -ep aspnetapp.pfx -p 1234<br># Trust the certificate (only for development)<br>dotnet dev-certs https - trust</pre><h4>Dockerfile Example</h4><p>Below is a Dockerfile for a .NET Core application, following best practices:</p><pre># Use the official .NET 8.0 SDK image for building<br>FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env<br>WORKDIR /app<br>COPY *.csproj ./<br>RUN dotnet restore<br>COPY . ./<br>RUN dotnet publish -c Release -o out<br><br># Use the official .NET 8.0 runtime image<br>FROM mcr.microsoft.com/dotnet/aspnet:8.0<br>WORKDIR /app<br>COPY --from=build-env /app/out .<br>EXPOSE 8080<br>EXPOSE 443<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;shope.dll&quot;]</pre><p>With this Dockerfile, you can build the image and run the container consistently on any platform.</p><p>Build and run commands:</p><pre># Build the image<br>docker build -t test-app .<br># Run standalone container<br>docker run -p 8088:8080 -p 8443:443 test-app -e Keycloak__Url=OLA1</pre><h4>Docker Compose</h4><p>Docker Compose simplifies building and running containers, especially when managing multiple services:</p><pre>version: &#39;3.8&#39;<br>services:<br>  app-app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8088:8080&quot;<br>      - &quot;8443:443&quot;<br>    environment:<br>      - ASPNETCORE_ENVIRONMENT=Production<br>      - ASPNETCORE_Kestrel__Certificates__Default__Password=${CERTIFICATE_PASSWORD}<br>      - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx<br>      - ASPNETCORE_HTTPS_PORT=8443<br>      - Keycloak__Url=${KEYCLOAK_URL}<br>    volumes:<br>      - ./aspnetapp.pfx:/https/aspnetapp.pfx:ro<br>    networks:<br>      - app-network<br>networks:<br>  app-network:<br>    driver: bridge</pre><p>In Docker Compose, environment variables are injected like ${KEYCLOAK_URL}. For .NET Core, the double underscore (__) convention represents hierarchical configuration levels (for example, Keycloak__Url corresponds to Keycloak:Url in <em>appsettings.json</em>).</p><p>Run with:</p><pre>docker compose up --build</pre><p>And test again:</p><pre>curl https://localhost:8443/test</pre><h4>Conclusion</h4><p>Proper management of environment variables is essential for modern .NET applications. It brings significant benefits in flexibility, security, and maintenance:</p><ul><li>Separating configurations per environment makes deployment easier;</li><li>Docker Compose simplifies managing variables and services locally;</li><li>Validating configurations helps avoid failures and unexpected runtime behavior;</li><li>Secrets management protects sensitive data and reduces security risks.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dada94a3db66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mapster vs AutoMapper: Why Mapster Is Up to 17.000x Faster in Simple Mappings]]></title>
            <link>https://medium.com/@silva.belarmino/mapster-vs-automapper-why-mapster-is-up-to-17-000x-faster-in-simple-mappings-67ea4187e238?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/67ea4187e238</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[data-mapper]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 07:24:28 GMT</pubDate>
            <atom:updated>2026-02-16T07:24:28.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*dLLoSIviuJV7nbsfx5df-Q.png" /></figure><blockquote>In .NET projects, object mapping between layers — such as from DTO to Entity and vice versa — is a recurring task. Among the most popular libraries for this purpose are AutoMapper and Mapster.</blockquote><blockquote>AutoMapper is the more established and widely adopted option within the community. According to GitHub, its first version dates back to May 2010. However, on April 2, 2025, it was announced that the library would transition to a commercial product.</blockquote><blockquote>Mapster, on the other hand, has been gaining traction, mainly due to its ease of use and, above all, its superior performance. As indicated on GitHub, its first version was released on February 12, 2015.</blockquote><p>For this exercise, we relied on the <strong>BenchmarkDotNet</strong> tool, which allows benchmarking and performance measurement of methods based on various metrics such as execution time, memory allocation, and result variability.</p><h4>Configuration in AutoMapper (with dynamic configuration)</h4><p>In AutoMapper, especially when using dynamic configuration or lambdas to create the mapper, there is a significant cost:</p><pre>// AutoMapper<br>IMapper mapper = new MapperConfiguration(cfg =&gt; <br>{<br>    cfg.CreateMap&lt;CityDTO, City&gt;();<br>}).CreateMapper();<br><br>CityDTO city = new()<br>{<br>    CityId = 1,<br>    Name = &quot;Tarrafal&quot;<br>};<br><br>City _city = mapper.Map&lt;City&gt;(city);</pre><p>Here, CreateMap is called with a lambda that builds the configuration at runtime. This involves reflection and expression compilation, which can be costly if executed repeatedly or in high-load scenarios.</p><h4>Usage in Mapster (without explicit configuration)</h4><p>Mapster stands out for its simplicity: it uses a direct extension on the source object, without requiring prior configuration for simple mappings.</p><pre>// Mapster<br>CityDTO city = new()<br>{<br>    CityId = 1,<br>    Name = &quot;Tarrafal&quot;<br>};<br><br>City _city = city.Adapt&lt;City&gt;();</pre><p>The Adapt&lt;T&gt;() method performs the mapping in a compiled and efficient way.</p><h4>The Benchmark That Stands Out</h4><p>In a performance test comparing the two approaches:</p><pre>| Method      | Mean           | Error        | StdDev       | Allocated |<br>|-------------|----------------|--------------|--------------|-----------|<br>| Mapster     | 33.14 ns       | 0.363 ns     | 0.303 ns     | 64 B      |<br>| AutoMapper  | 568,709.25 ns  | 7,833.144 ns | 6,541.030 ns | 51,278 B  |</pre><p>Mapster is approximately 17.000 times faster in this specific scenario! It also allocates almost no memory compared to AutoMapper.</p><p>Why such an absurd difference?</p><ul><li>AutoMapper, when creating configuration with a lambda (cfg =&gt; cfg.CreateMap&lt;…&gt;()), compiles expressions at runtime every time the mapper is instantiated.</li><li>If you instantiate MapperConfiguration repeatedly (which is common in tests or poorly optimized scenarios), the cost increases dramatically.</li><li>Mapster uses compiled code generation and does not require explicit configuration for simple cases, avoiding reflection overhead.</li></ul><h4>Conclusion: When Should You Choose Each One?</h4><ul><li>AutoMapper: Great for large projects with complex mappings, a huge community, and mature integrations (e.g., ProjectTo for EF Core). However, configure the mapper only once (as a singleton) to avoid performance penalties.</li><li>Mapster: Ideal for performance-critical scenarios, simplicity, and less boilerplate. In general benchmarks (2024/2025), it is usually 5–10x faster than a properly configured AutoMapper and supports compile-time code generation.</li></ul><p>If you are starting a new .NET project or optimizing an existing one, it is worth testing Mapster. Migration is usually straightforward, and the performance gains can be significant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67ea4187e238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java isn’t wrong — you just don’t know the Integer Cache]]></title>
            <link>https://medium.com/@silva.belarmino/java-isnt-wrong-you-just-don-t-know-the-integer-cache-e2eb3432d12a?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2eb3432d12a</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 09:00:30 GMT</pubDate>
            <atom:updated>2026-02-09T09:00:30.122Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Java isn’t wrong — you just don’t know the Integer Cache</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0PZOv_pWbmRYwqnm.jpeg" /></figure><p>🔍 Understand why Integer a == Integer b can be true or false in Java.</p><p>People who program in Java for the first time often find this behavior strange:</p><pre>Integer a = 1000;<br>Integer b = 1000;<br>System.out.println(a == b); // false<br>Integer x = 1;<br>Integer y = 1;<br>System.out.println(x == y); // true</pre><p>So why are two variables with the same value sometimes considered equal, and other times not?</p><p>The explanation lies in an internal detail of the language called the <strong>Integer Cache</strong>.</p><h4>🧠 == does not compare values — it compares references</h4><p>First of all, it’s important to remember:</p><ul><li>== compares <strong>references</strong> when we’re dealing with objects (like Integer);</li><li>To compare <strong>values</strong>, the correct method is .equals().</li></ul><p>So:</p><pre>System.out.println(a == b);        // checks if it’s the same object<br>System.out.println(a.equals(b));   // compares the value</pre><h4>📦 What is the Integer Cache?</h4><p>To improve performance and reduce memory allocation, Java maintains an internal cache of Integer objects in the range:</p><pre>-128 to 127</pre><p>This means that any autoboxing operation (converting int to Integer) within this range reuses the same object.</p><p>For example:</p><pre>Integer x = 1;<br>Integer y = 1;</pre><p>Here, x and y point to the <strong>same cached object</strong>, so the result is:</p><pre>System.out.println(x == y); // true</pre><h4>❗ Outside the range, no cache is applied</h4><p>Now look at larger values:</p><pre>Integer a = 1000;<br>Integer b = 1000;</pre><p>Since 1000 is outside the -128 to 127 range:</p><ul><li>a new Integer object is created for a;</li><li>another new Integer object is created for b.</li></ul><p>They do <strong>not</strong> point to the same reference:</p><pre>System.out.println(a == b); // false</pre><h4>🔧 The value comes from Integer.valueOf()</h4><p>This method:</p><ul><li>uses the cache for values between -128 and 127;</li><li>creates a new object outside that range.</li></ul><pre>| Value range     | Cached? | Result of `==` |<br>| --------------- | ------- | -------------- |<br>| -128 to 127     | ✅ Yes   | true          |<br>| Any other value | ❌ No    | false         |</pre><h4>✔ Best practice: use .equals()</h4><p>To avoid unexpected behavior, always compare values like this:</p><pre>a.equals(b);</pre><p>Or let Java do unboxing:</p><pre>a == b.intValue();</pre><h3>🏁 Conclusion</h3><p>Java’s seemingly strange behavior is <strong>not a bug</strong> — it’s an optimization.</p><p>The Integer Cache helps improve performance and reduce object creation, but it can be confusing when == is used to compare values.</p><p>Whenever you’re working with numeric objects, remember:</p><ul><li>== compares <strong>references;</strong></li><li>.equals() compares <strong>values.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2eb3432d12a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Por que as Variáveis de Ambiente são Essenciais em Aplicações .NET Core]]></title>
            <link>https://medium.com/@silva.belarmino/por-que-as-vari%C3%A1veis-de-ambiente-s%C3%A3o-essenciais-em-aplica%C3%A7%C3%B5es-net-core-4541fc525dab?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/4541fc525dab</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[environment]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 09:22:56 GMT</pubDate>
            <atom:updated>2026-02-25T00:29:51.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>Por que as Variáveis de Ambiente são Essenciais em Aplicações .NET Core</h3><h3>Por que Variáveis de Ambiente Importam?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZdT8fwFJzsxMjvS44IATg.png" /></figure><h3>Introdução</h3><p>Variáveis de ambiente são um dos pilares para construir aplicações <strong>.NET Core</strong> <strong>modernas, seguras e facilmente configuráveis</strong>. Elas permitem separar código de configuração, adaptar o comportamento da aplicação a diferentes ambientes e proteger informações sensíveis. Veremos na prática como combinar variáveis de ambiente <strong>.NET</strong>, <strong>Docker</strong> e <strong>Docker Compose</strong> para gerir configurações dinâmicas de forma limpa, escalável e alinhada com boas práticas de mercado.</p><p>Neste artigo, vamos percorrer desde os conceitos fundamentais até cenários avançados de produção.</p><p>A utilização de variáveis de ambiente está diretamente alinhada com o manifesto <strong><em>The Twelve-Factor App</em></strong>, especialmente no que diz respeito à configuração:</p><ul><li><strong>Configuração externa</strong>: separar configuração do código-fonte;</li><li><strong>Ambientes múltiplos</strong>: mesmo código, comportamentos diferentes;</li><li><strong>Segurança</strong>: <em>secrets</em> fora do repositório.</li></ul><p>Essa abordagem torna a aplicação mais portátil, previsível e segura.</p><p>Com variáveis de ambiente, conseguimos adaptar a aplicação sem recompilar em diferentes ambientes <em>Development, Staging </em>e<em> Production</em><strong><em>.</em></strong></p><h3>Aplicação .NET Core</h3><p>Nas aplicações .NET Core, utilizamos os ficheiros <strong>appsettings.json</strong> ou <strong>appsettings.{Environment}.json</strong> para definir configurações específicas por ambiente, como <em>Development, Staging </em>e<em> Production</em>.</p><p>Segue um exemplo de um ficheiro appsettings.json.</p><pre>{<br>    &quot;Keycloak&quot;: {<br>        &quot;Url&quot;: &quot;http://keycloak&quot;<br>    },<br>    &quot;Logging&quot;: {<br>        &quot;LogLevel&quot;: {<br>            &quot;Default&quot;: &quot;Information&quot;,<br>            &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>        }<br>    },<br>    &quot;AllowedHosts&quot;: &quot;*&quot;,<br>    &quot;Kestrel&quot;: {<br>        &quot;Endpoints&quot;: {<br>            &quot;Https&quot;: {<br>                &quot;Url&quot;: &quot;https://0.0.0.0:443&quot;<br>            },<br>            &quot;Http&quot;: {<br>                &quot;Url&quot;: &quot;http://0.0.0.0:8080&quot;<br>            }<br>        }<br>    }<br>}</pre><p>O .NET Core possui um sistema de configuração poderoso e integrado. O acesso às configurações é simples e direto; por exemplo, é possível aceder facilmente à propriedade <strong>Url</strong> dentro da secção <strong>Keycloak</strong>, conforme aparece no exemplo acima, com a linha de código apresentado a seguir.</p><pre>app.MapGet(&quot;/teste&quot;, () =&gt;<br>{<br>    return &quot;OLA : &quot;.Concat(app.Configuration[&quot;Keycloak:Url&quot;]);<br>})<br>.WithName(&quot;teste&quot;)<br>.WithOpenApi();</pre><p>Esse mesma linha pode ler dados do appsettings ou de uma variável de ambiente.</p><p>Até este ponto, o projeto funciona normalmente em ambiente local. No entanto, durante o processo de <em>deploy</em>, surge a necessidade de utilizar URLs diferentes do Keycloak para os ambientes de <em>Development, Staging </em>e<em> Production</em>.</p><p>Para testar e consumir o <em>endpoint</em> exposto pela aplicação, basta executar o comando abaixo.</p><pre>curl https://localhost:8443/teste</pre><h4>Variáveis de ambiente</h4><p>É neste contexto que as variáveis de ambiente tornam-se essenciais, especialmente quando queremos integrar o projeto num <em>pipeline</em> de CI/CD. Para isso, é prática comum criar um ficheiro <strong>.env</strong> no projeto, onde são definidas as variáveis específicas de cada ambiente.</p><pre>KEYCLOAK_URL=http://keycloak<br>CERTIFICATE_PASSWORD=1234</pre><h4><strong>Certificado </strong>digital <strong>autoassinado</strong></h4><p>Para executar um projeto com suporte a <strong>HTTPS</strong>, vamos gerar um <strong>certificado autoassinado</strong>. O SDK do .NET disponibiliza um comando que permite criar certificados autoassinados para uso local, facilitando a configuração de ambientes de desenvolvimento seguros. Segue os comandos para a geração do certificado.</p><pre># Gerar certificado auto-assinado.<br>dotnet dev-certs https -ep aspnetapp.pfx -p 1234<br><br># Confiar no certificado (apenas desenvolvimento)<br>dotnet dev-certs https - trust</pre><p>Aqui está um exemplo de um <strong>Dockerfile</strong> para uma aplicação<strong> </strong>.NET Core, alinhado com as boas práticas.</p><pre># Use the official .NET 8.0 SDK image for building<br>FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env<br>WORKDIR /app<br><br># Copy csproj and restore dependencies<br>COPY *.csproj ./<br>RUN dotnet restore<br><br># Copy everything else and build<br>COPY . ./<br>RUN dotnet publish -c Release -o out<br><br># Use the official .NET 8.0 runtime image<br>FROM mcr.microsoft.com/dotnet/aspnet:8.0<br>WORKDIR /app<br>COPY --from=build-env /app/out .<br><br># Expose port 80<br>EXPOSE 8080<br>EXPOSE 443<br><br>ENTRYPOINT [&quot;dotnet&quot;, &quot;shope.dll&quot;]</pre><p>Com o <strong>Dockerfile</strong> criado, já podemos fazer o <em>build</em> da imagem e executar o nosso <em>container</em>, garantindo que a aplicação .NET Core corre de forma consistente em qualquer plataforma.</p><p>Os comandos a seguir são responsáveis pela criação da imagem e pela execução dos <em>container</em> da aplicação.</p><pre>  # Build da imagem<br>  docker build -t teste-app .<br><br>  # Executar container standalone<br>  docker run -p 8088:8080 -p 8443:443 teste-app -e Keycloak__Url=OLA1</pre><h4><strong>Docker Compose</strong></h4><p>Embora possamos executar o nosso <em>container</em> diretamente a partir de um <strong>Dockerfile</strong>, existe uma abordagem mais simples e prática para fazer o <em>build</em> e executar o <em>container</em>, especialmente quando lidamos com múltiplas configurações e serviços através do <strong>Docker Compose</strong>.</p><p>Segue um exemplo de <strong>Docker Compose</strong>. O ficheiro é normalmente denominado <strong>docker-compose.yml</strong> e é utilizado para definir, configurar e executar um ou mais <em>containers</em> de forma simples e organizada.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  app-app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8088:8080&quot;<br>      - &quot;8443:443&quot;<br>    environment:<br>      - ASPNETCORE_ENVIRONMENT=Production<br>      - ASPNETCORE_Kestrel__Certificates__Default__Password=${CERTIFICATE_PASSWORD}<br>      - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp.pfx<br>      - ASPNETCORE_HTTPS_PORT=8443<br>      - Keycloak__Url=${KEYCLOAK_URL}<br>    volumes:<br>      - ./aspnetapp.pfx:/https/aspnetapp.pfx:ro<br>    networks:<br>      - app-network<br><br>networks:<br>  app-network:<br>    driver: bridge</pre><p>No <strong>Docker Compose</strong>, a variável de ambiente é injetada na aplicação da seguinte forma <strong>${KEYCLOAK_URL}</strong>, segue uma descrição detalhada.</p><ul><li><strong>KEYCLOAK_URL</strong> — é a variável definida no sistema, no ficheiro <strong>.env</strong> ou no <em>pipeline</em> de CI/CD;</li><li><strong>Keycloak__Url</strong> — segue a convenção do .NET Core para variáveis de ambiente, onde o separador <strong>__</strong>(duplo underscore) representa níveis hierárquicos de configuração. Neste caso, <strong>Keycloak__Url</strong> corresponde diretamente à chave definida no <strong>appsettings.json.</strong></li></ul><pre>&quot;Keycloak&quot;: {<br>  &quot;Url&quot;: &quot;...&quot;<br>}</pre><p>Para fazer o <em>build</em> da imagem e executar o <em>container</em> definido no Docker Compose, basta utilizar o comando abaixo.</p><pre>docker compose up --build</pre><p>Para testar e consumir o <em>endpoint</em> exposto pela aplicação, basta executar o comando abaixo.</p><pre>curl https://localhost:8443/teste</pre><h3>Conclusão</h3><p>A gestão adequado das variáveis de ambiente é fundamental para aplicações .NET modernas. Essa abordagem pode trazer ganhos significativos em flexibilidade, segurança e manutenção:</p><ul><li><strong>Separação de configurações por ambiente</strong> garante maior flexibilidade e facilidade de <em>deploy</em>;</li><li><strong>Docker Compose</strong> simplifica a gestão de variáveis e serviços em ambiente local;</li><li><strong>Validação de configurações</strong> evita falhas e comportamentos inesperados em <em>runtime</em>;</li><li><strong><em>Secrets</em> <em>management</em></strong> protege informações sensíveis e reduz riscos de segurança.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4541fc525dab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mapster vs AutoMapper: Por Que o Mapster é Até 17.000x Mais Rápido em Mapeamentos Simples]]></title>
            <link>https://medium.com/@silva.belarmino/mapster-vs-automapper-por-que-o-mapster-%C3%A9-at%C3%A9-17-000x-mais-r%C3%A1pido-em-mapeamentos-simples-c298963a7187?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/c298963a7187</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 13:25:40 GMT</pubDate>
            <atom:updated>2026-02-16T07:21:46.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*WMrCwnpXRJdrnbrzxET8Jw.png" /></figure><blockquote>Em projetos <strong>.NET</strong>, o mapeamento de objetos entre camadas — como de <strong>DTO para Entity</strong> e vice-versa — é uma tarefa recorrente. Entre as bibliotecas mais populares para esse fim destacam-se o <strong>AutoMapper</strong> e o <strong>Mapster</strong>.</blockquote><blockquote>O <strong>AutoMapper</strong> é o mais veterano e amplamente adotado pela comunidade. De acordo com o GitHub, a sua primeira versão data de <strong>maio de 2010</strong>. No entanto, em <strong>2 de abril de 2025</strong>, foi anunciado que a biblioteca passaria a ser um <strong>produto comercial</strong>.</blockquote><blockquote>Já o <strong>Mapster</strong> tem vindo a ganhar espaço, sobretudo pela sua <strong>simplicidade de uso</strong> e, principalmente, pela <strong>performance superior</strong>. Conforme indicado no GitHub, a sua primeira versão foi lançada em <strong>12 de fevereiro de 2015</strong>.</blockquote><p>Para este exercício, recorremos aos préstimos da ferramenta <strong>BenchmarkDotNet</strong>, que permite a realização de <em>benchmarks</em>e a medição do desempenho de métodos com base em diversas métricas, como <strong>tempo de execução</strong>, <strong>alocação de memória</strong> e <strong>variabilidade dos resultados</strong>.</p><h4>Configuração no AutoMapper (com configuração dinâmica)</h4><p>No AutoMapper, especialmente quando usamos configuração dinâmica ou <em>lambdas</em> para criar o mapper, há um custo significativo:</p><pre>// AutoMapper<br>IMapper mapper = new MapperConfiguration(cfg =&gt; <br>{<br>    cfg.CreateMap&lt;CityDTO, City&gt;();<br>}).CreateMapper();<br><br>CityDTO city = new()<br>{<br>    CityId = 1,<br>    Name = &quot;Tarrafal&quot;<br>};<br><br>City _city = mapper.Map&lt;City&gt;(city);</pre><p>Aqui, o CreateMap é chamado com uma <em>lambda</em> que cria a configuração em tempo de execução. Isso envolve reflexão e compilação de expressões, o que pode ser caro se feito repetidamente ou em cenários de alta carga.</p><h4>Uso no Mapster (sem configuração explícita)</h4><p>O Mapster destaca pela simplicidade: ele usa extensão direta no objeto fonte, sem necessidade de configuração prévia para mapeamentos simples:</p><pre>// Mapster<br>CityDTO city = new()<br>{<br>    CityId = 1,<br>    Name = &quot;Tarrafal&quot;<br>};<br><br>City _city = city.Adapt&lt;City&gt;();</pre><p>O método Adapt&lt;T&gt;() faz o mapeamento de forma compilada e eficiente.</p><h4>O Benchmark que Chama Atenção</h4><p>Em um teste de performance comparando os dois approaches:</p><pre>| Method      | Mean           | Error        | StdDev       | Allocated |<br>|-------------|----------------|--------------|--------------|-----------|<br>| Mapster     | 33.14 ns       | 0.363 ns     | 0.303 ns     | 64 B      |<br>| AutoMapper  | 568,709.25 ns  | 7,833.144 ns | 6,541.030 ns | 51,278 B  |</pre><p>O Mapster é <strong>aproximadamente 17.000 vezes mais rápido</strong> nesse cenário específico! E aloca <strong>quase nada de memória</strong> em comparação com o AutoMapper.</p><p>Por quê essa diferença absurda?</p><ul><li>O AutoMapper, ao criar a configuração com lambda (cfg =&gt; cfg.CreateMap&lt;…&gt;()), compila as expressões em runtime toda vez que o mapper é instanciado.</li><li>Se você instancia o MapperConfiguration repetidamente (comum em testes ou cenários mal otimizados), o custo explode.</li><li>O Mapster usa geração de código compilado e não requer configuração explícita para casos simples, evitando <em>overhead</em> de reflexão.</li></ul><h4>Conclusão: Quando Escolher Cada Um?</h4><ul><li><strong>AutoMapper</strong>: Ótimo para projetos grandes com mapeamentos complexos, comunidade enorme e integração madura (ex.: ProjectTo para EF Core). Mas configure o mapper uma única vez (<em>singleton</em>) para evitar penalidades de performance.</li><li><strong>Mapster</strong>: Ideal para performance crítica, simplicidade e menos boilerplate. Em <em>benchmarks</em> gerais (2024/2025), ele costuma ser 5–10x mais rápido que o AutoMapper configurado corretamente, e com suporte a geração de código em compile-time.</li></ul><p>Se você está começando um novo projeto .NET ou otimizando um existente, vale testar o Mapster. A migração costuma ser simples, e os ganhos de performance podem ser significativos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c298963a7187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java não está errado — você só não conhece o Integer Cache]]></title>
            <link>https://medium.com/@silva.belarmino/java-n%C3%A3o-est%C3%A1-errado-voc%C3%AA-s%C3%B3-n%C3%A3o-conhece-o-integer-cache-8548155dd1bf?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/8548155dd1bf</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 20:18:31 GMT</pubDate>
            <atom:updated>2025-12-14T12:15:05.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*1JzUnG5SoBbmxyWBhpxmuQ@2x.jpeg" /></figure><p>🔍 Entenda <strong>por que Integer a == Integer b pode ser true ou false em Java.</strong></p><p>Quem programa em Java pela primeira vez costuma estranhar este comportamento:</p><pre>Integer a = 1000;<br>Integer b = 1000;<br>System.out.println(a == b); // false<br><br>Integer x = 1;<br>Integer y = 1;<br>System.out.println(x == y); // true</pre><p>Por que, afinal, duas variáveis com o mesmo valor às vezes são consideradas iguais, e outras vezes não?</p><p>A explicação está em um detalhe interno da linguagem chamado <strong><em>Integer Cache</em></strong>.</p><p><strong>🧠 == não compara valores, compara referências</strong></p><p>Antes de tudo, é importante lembrar que:</p><p>•	Compara referências quando estamos a falar de objetos (como <strong>Integer</strong>) devemos usar <strong>==</strong>.</p><p>•	Para comparar valores, o correto é usar<strong> .equals()</strong>.</p><p>Por isso:</p><pre>System.out.println(a == b);   // compara se é o MESMO objeto<br>System.out.println(a.equals(b)); // compara o valor</pre><p><strong>📦 O que é o <em>Integer Cache</em>?</strong></p><p>Para melhorar desempenho e reduzir alocação de memória, o Java mantém um <em>cache</em> interno de objetos Integer no intervalo:</p><pre>-128 a 127</pre><p>Isso significa que qualquer operação de <em>autoboxing</em> (converter int para Integer) dentro desse intervalo reutiliza o mesmo objeto.</p><p>Por exemplo:</p><pre>Integer x = 1;<br>Integer y = 1;</pre><p>Aqui x e y apontam para o mesmo objeto no cache. Por isso o resultado é:</p><pre>System.out.println(x == y); // true</pre><p><strong>❗ Fora do intervalo, nenhum <em>cache</em> é aplicado</strong></p><p>Agora veja o caso de valores maiores:</p><pre>Integer a = 1000;<br>Integer b = 1000;</pre><p>Como 1000 está fora de -128 a 127:</p><p>•	um novo objeto Integer é criado para a</p><p>•	outro novo objeto Integer é criado para b</p><p>Eles não apontam para a mesma referência:</p><pre>System.out.println(a == b); // false</pre><p><strong>🔧 O valor vem do Integer.valueOf()</strong></p><p>Essa função:</p><p>•	usa o cache para valores no intervalo -128 a 127</p><p>•	cria um novo objeto fora desse intervalo</p><p><strong>🧩 Resumo rápido</strong></p><pre>| Valor          | Possui cache? | Resultado de == |<br>|----------------|---------------|-----------------|<br>| -128 - 128     | ✅ Sim        | true            |<br>| Qualquer outro | ❌ Não.       | false           |</pre><p><strong>✔ Boa prática: use .equals()</strong></p><p>Para evitar comportamento inesperado, sempre compare valores assim:</p><pre>a.equals(b);</pre><p>Ou deixe o Java fazer <em>unboxing</em>:</p><pre>a == b.intValue();</pre><p>🏁 <strong>Conclusão</strong></p><p>O comportamento aparentemente estranho do Java não é um <em>bug</em> — é uma otimização.</p><p>O <em>Integer Cache</em> ajuda a melhorar desempenho e reduzir criação de objetos, mas também pode confundir quando usamos == para comparar valores.</p><p>Sempre que estiver a trabalhar com objetos numéricos, lembre-se:</p><blockquote>== compara referências.</blockquote><blockquote>.equals() compara valores.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8548155dd1bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce bugs, vulnerabilities, and code smells, among other issues in .NET]]></title>
            <link>https://medium.com/@silva.belarmino/identify-vulnerabilities-bugs-and-more-in-your-code-in-less-than-5-minutes-5aace8533332?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aace8533332</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 22:56:40 GMT</pubDate>
            <atom:updated>2023-09-09T09:50:35.456Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reduce bugs, vulnerabilities, and code smells, among other issues in .NET core apps, with this tool.</h3><h4>Deliver codes that are secure, consistent, reliable, and with a low level of complexity.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gF04gXIt_0TIRlHUySCZcQ.png" /></figure><p>In line with the previously addressed <a href="https://medium.com/@silva.belarmino/ensure-reliability-stability-in-your-asp-net-core-project-with-tests-and-test-coverage-518c15bf2f40">topics</a>, the quality of software is a concern to be taken into account by companies and professionals in the field.</p><p>Previously, we discussed testing, which is an excellent ally in the pursuit of quality. However, there are other aspects that we intend to emphasize in this article, such as secure codes and their complexities. Complexity for readability, as well as for incorporating new changes easily.</p><p>You might be thinking, but code review can mitigate these impacts. The proposal is not to rely solely on developers, but to use a tool that analyzes the code and identifies issues related to the points mentioned above within minutes. As a bonus, it provides suggestions for correction.</p><h4>SonarQube</h4><p>It is a code analysis tool that assists developers in delivering quality, secure, consistent, reliable, and low-complexity code. It supports more than 30 programming languages and can be integrated into the continuous integration pipeline.</p><p>Developed in the Java language in 2006.</p><p>In terms of licensing, it has a free version and other paid versions.</p><p>SonarQube allows you to identify:</p><ul><li>Security vulnerabilities;</li><li>Bugs;</li><li>Code duplication;</li><li>Test coverage level;</li><li>Code complexity that could hinder the maintenance process;</li><li>It also allows creating new rules to ensure that certain standards are followed.</li></ul><h4>Functioning</h4><p>The solution consists of two applications: a client that gathers data from the source code and its respective tests, and another server that processes the collected data and presents reports and correction suggestions. On the server, configurations can be made, and new rules can be created.</p><h4>Demonstration</h4><p>For demonstration purposes, the proposal is to install the Community Edition version. The server will be installed in a Docker container, along with a PostgreSQL database. To facilitate this, a Docker Compose file (docker-compose.yml) is provided, which allows configuring and launching multiple containers simultaneously.</p><p>The file must be created with the name docker-compose.yml. The suggestion would be to create a folder, within the folder create the file, and execute the following commands.</p><pre>version: &quot;3&quot;<br><br>services:<br>  sonarqube:<br>    image: sonarqube:community<br>    depends_on:<br>      - db<br>    environment:<br>      SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar<br>      SONAR_JDBC_USERNAME: sonar<br>      SONAR_JDBC_PASSWORD: sonar<br>    volumes:<br>      - sonarqube_data:/opt/sonarqube/data<br>      - sonarqube_extensions:/opt/sonarqube/extensions<br>      - sonarqube_logs:/opt/sonarqube/logs<br>    ports:<br>      - &quot;9000:9000&quot;<br>  db:<br>    image: postgres:12<br>    environment:<br>      POSTGRES_USER: sonar<br>      POSTGRES_PASSWORD: sonar<br>    volumes:<br>      - postgresql:/var/lib/postgresql<br>      - postgresql_data:/var/lib/postgresql/data<br><br>volumes:<br>  sonarqube_data:<br>  sonarqube_extensions:<br>  sonarqube_logs:<br>  postgresql:<br>  postgresql_data:</pre><p>Here are the commands to start the containers. If you don’t have Docker or installed, follow the instructions on the <a href="https://www.docker.com/">official page</a>.</p><p>It’s worth noting that everything will be executed on an Ubuntu. For Windows, I believe Docker Desktop or <a href="https://learn.microsoft.com/en-us/windows/wsl/install">WSL</a> can be beneficial.</p><pre>sudo docker compose up</pre><p>You might come across the error message, “vm.max_map_count is too low,” there’s no need to panic, we can work around the situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Gxzk2f9DdjNsuzKQydFUg.png" /></figure><p>The command to increase the <em>maximum virtual memory areas</em> is the following.</p><pre>sudo sysctl -w vm.max_map_count=262144</pre><p>Once the memory has been increased, run the command again to execute Docker Compose. Then, simply access the address <a href="http://localhost:9000/">http://localhost:9000</a> and fill in the credentials:<br>User : <strong>admin</strong></p><p>Password : <strong>admin</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8c28c9xaTXUh2ki1ph4N0Q.png" /></figure><p>Provided with the right credentials, we move on to the next screen that allows connecting with some services, such as Azure DevOps, Bitbucket Server/Cloud, GitHub, GitLab.</p><p>For our example, we will use the manual option, with the project created for the <a href="https://medium.com/@silva.belarmino/ensure-reliability-stability-in-your-asp-net-core-project-with-tests-and-test-coverage-518c15bf2f40">article</a>, which already includes tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lV0Y06E9iEf4SJpmm0vqZg.png" /></figure><p>When selecting the manual option, a window appears to create the project. The last field should be the branch you wish to analyze.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fyq82snUeGpr4aAFFLIdA.png" /></figure><p>When setting up the project, you need to choose the option “Locally” to generate a <strong>token</strong>, as can be seen in the following images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-Aherw8HLZMfv3WftZZjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEy9mbKo5B8ZkC1RYB1CTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRREOtC6MR0HELW_TKbwbw.png" /></figure><p>After generating the <strong>token</strong>, the option to choose the language/framework and other instructions appears, such as the tools to be installed. The installation for ASP.NET Core applications follows below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8PveYEGlFQcz0t6IBCpZw.png" /></figure><pre>dotnet tool install --global dotnet-sonarscanner</pre><p>Finally, we are ready, but before that, let’s intentionally create a vulnerability in the method that uses regular expression.</p><p>Our class to be analyzed.</p><pre>public class Numbers<br>{<br>    public static bool IsValid(String number)<br>    {<br>        if (!IsNumber(number))<br>        {<br>            return false;<br>        }<br>        if (number.Trim().Length &gt; 10)<br>        {<br>            return false;<br>        }<br>        return true;<br>    }<br>    public static bool IsNumber(string number)<br>    {<br>        Regex regex = new(@&quot;^[0-9]+$&quot;, RegexOptions.None);<br>        return regex.IsMatch(number);<br>    }<br>}</pre><p>Now we can execute the commands to gather the data for analysis in SonarQube.<br>Note: I’ve provided the token, but do not share yours.</p><pre>dotnet sonarscanner begin /k:&quot;xUnitCoverletSonar&quot; /d:sonar.host.url=&quot;http://localhost:9000&quot;  /d:sonar.token=&quot;sqp_caa35cbdd7c1925b93c69fa9c95a4f995937&quot;</pre><pre>dotnet build</pre><pre>dotnet sonarscanner end /d:sonar.token=&quot;sqp_caa35cbdd7c1925b93c69fa9c95a4f995937&quot;</pre><p>Now we can see that there is a vulnerability (Security Hotspot) and other areas for improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0QtBT67rtnaQ32XpjeV6A.png" /></figure><p>Our provoked error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEW51o0sVhqpy7dhRgWLVg.png" /></figure><p>After being corrected, we now have a safer class, including a timeout for the regular expression. Without a timeout, it becomes a vulnerability that can be exploited in C#. However, it’s straightforward with the reduction of ‘if’ statements and modification of ‘static,’ since we are using static methods.</p><pre>public static class Numbers<br>{<br>    public static bool IsValid(String number)<br>    {<br>        if (!IsNumber(number) || number.Trim().Length &gt; 10)<br>        {<br>            return false;<br>        }<br>        return true;<br>    }<br>    public static bool IsNumber(string number)<br>    {<br>        Regex regex = new(@&quot;^[0-9]+$&quot;, RegexOptions.None, TimeSpan.FromMilliseconds(5));<br>        return regex.IsMatch(number);<br>    }<br>}</pre><p>The new result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGsqcj7tnivpYYPiRlHLbA.png" /></figure><h4>Conclusion</h4><p>Tools like SonarQube can be very useful, even with developers performing code reviews. They can accelerate the process of analyzing and identifying potential issues in the code.</p><h4>Reference</h4><p><a href="https://www.sonarsource.com/">https://www.sonarsource.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aace8533332" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduza bugs, vulnerabilidades, code smells, entre outros problemas em aplicações .NET]]></title>
            <link>https://medium.com/@silva.belarmino/identifique-vulnerabilidades-e-bugs-no-seu-c%C3%B3digo-em-minutos-c615c8ba8725?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/c615c8ba8725</guid>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[qualidade-de-software]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[código]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 01:23:22 GMT</pubDate>
            <atom:updated>2023-09-09T09:51:45.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reduza bugs, vulnerabilidades, code smells, entre outros problemas em aplicações .NET Core, com esta ferramenta.</h3><h3>Entrega códigos seguro, consistentes, confiáveis e com baixo nível de complexidade</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gF04gXIt_0TIRlHUySCZcQ.png" /></figure><p>Na linha dos conteúdos abordados <a href="https://medium.com/@silva.belarmino/assegure-confiabilidade-estabilidade-no-seu-projecto-asp-net-core-com-testes-e-cobertura-de-testes-d90fa571f5a">anteriormente</a>, a qualidade do software é uma preocupação a se ter em conta pelas empresas e profissionais da área.</p><p>Anteriormente falamos de testes que é um excelente aliado na busca pela qualidade. Todavia, existem outros aspectos que pretendemos dar ênfase neste artigo, como codigos seguros e a complexidades dos mesmo. Complexidade para leitura, como para incluir novas alterações de forma fácil.</p><p>Talvez esteja a pensar, mas a revisão de código pode mitigar esses impactos. A proposta é não depender apenas de desenvolvedores, mas recorrer a uma ferramenta que faz a análise dos códigos e apresenta problemas relacionados com os pontos acima mencionados em minutos. Como bônus apresenta sugestões de correção.</p><h4>Sonarqube</h4><p>É uma ferramenta de análise de código que ajuda os desenvolvedores a entregar código de qualidade, seguro, consistentes, confiáveis e com baixo nível de complexidade. Possui suporte a mais de 30 linguagens de programação, pode ser integrado a <em>pipeline</em> de <em>continuous integration.</em></p><p>Desenvolvido na linguagem Java em 2006.</p><p>Em termos de licenciamento possui versão grátis e outras versões pagas.</p><p>Sonarqube possibilita identificar:</p><ul><li>Vulnerabilidade de segurança;</li><li>Bugs;</li><li>Duplicação de código;</li><li>Nível de cobertura de teste;</li><li>Complexidade de código que podem dificultar no processo de manutenção;</li><li>Permite ainda, criar novas regras para assegurar que certos padrões sejam seguidos.</li></ul><h4>Funcionamento</h4><p>A solução é composta por duas aplicações, um cliente que recolhe os dados do código fonte e os respetivos testes, outro servidor que faz processamento dos dados recolhidos e apresenta os relatórios e as sugestões de correção. No servidor pode ser feito as configurações e criação das novas regras.</p><h4>Demonstração</h4><p>Para efeitos de demonstração a proposta é instalar a versão <em>Community Edition</em>. O servidor vai ser instalado num <em>container</em> Docker, assim como uma base de dados PostgreSQL. Para facilitar segue um ficheiro Docker compose (docker-compose.yml) que, permite configurar e arrancar vários containers <em>container</em> ao mesmo tempo.</p><p>O ficheiro deve ser criado com o nome docker-compose.yml, a sugestão seria criar uma pasta, dentro da pasta criar o ficheiro e executar os comandos a seguir.</p><pre>version: &quot;3&quot;<br><br>services:<br>  sonarqube:<br>    image: sonarqube:community<br>    depends_on:<br>      - db<br>    environment:<br>      SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar<br>      SONAR_JDBC_USERNAME: sonar<br>      SONAR_JDBC_PASSWORD: sonar<br>    volumes:<br>      - sonarqube_data:/opt/sonarqube/data<br>      - sonarqube_extensions:/opt/sonarqube/extensions<br>      - sonarqube_logs:/opt/sonarqube/logs<br>    ports:<br>      - &quot;9000:9000&quot;<br>  db:<br>    image: postgres:12<br>    environment:<br>      POSTGRES_USER: sonar<br>      POSTGRES_PASSWORD: sonar<br>    volumes:<br>      - postgresql:/var/lib/postgresql<br>      - postgresql_data:/var/lib/postgresql/data<br><br>volumes:<br>  sonarqube_data:<br>  sonarqube_extensions:<br>  sonarqube_logs:<br>  postgresql:<br>  postgresql_data:</pre><p>Segue os comandos para iniciar os <em>containers</em>, caso não tenha Docker instalado, siga as instruções na <a href="https://www.docker.com/">página oficial</a>.</p><p>Vale realçar que tudo vai ser executado num Ubuntu, para windows acredito que o Docker Desktop ou <a href="https://learn.microsoft.com/en-us/windows/wsl/install">WSL</a> podem ser uma mais valia.</p><pre>sudo docker compose up</pre><p>Pode deparar com a mensagem de erro, “<em>vm.max_map_count is too low</em>”, não precisa entrar em pânico, podemos contornar a situação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Gxzk2f9DdjNsuzKQydFUg.png" /></figure><p>O comando para aumentar a <em>max virtual memory areas</em> e o seguinte.</p><pre>sudo sysctl -w vm.max_map_count=262144</pre><p>Feito o aumento da memória, volta a executar o comando para rodar o Docker Compose, depois basta acessar o endereço<a href="http://localhost:9000/"> http://localhost:9000</a> e preencher as credenciais:</p><p>Utilizador : <strong>admin</strong></p><p>Senha : <strong>admin</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8c28c9xaTXUh2ki1ph4N0Q.png" /></figure><p>Fornecido as credenciais certas, passamos para a tela a seguir que permite ligar com alguns serviços, como Azure DevOps, Bitbucket Server/Cloud, GitHub, GitLab.</p><p>Para o nosso exemplo vamos usar a opção manual, com o projecto criado para o <a href="https://medium.com/me/stats/post/e62b0f85889a">artigo</a>, que já inclui testes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lV0Y06E9iEf4SJpmm0vqZg.png" /></figure><p>Ao selecionar a opção manual aparece uma janela para criar o projecto. O ultimo campo deve ser a <em>branch</em> que se pretende analisar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fyq82snUeGpr4aAFFLIdA.png" /></figure><p>Ao configurar o projeto precisar selecionar a opção <em>Locally</em>, para geração de um <em>token</em>, como pode ser verificado nas imagens seguintes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-Aherw8HLZMfv3WftZZjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEy9mbKo5B8ZkC1RYB1CTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRREOtC6MR0HELW_TKbwbw.png" /></figure><p>Depois de ter gerado o <em>token</em>, aparece a opção para de escolher linguagem/framework e outras instruções como ferramentas a serem instalados. A instalação para aplicações ASP.NET Core segue abaixo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8PveYEGlFQcz0t6IBCpZw.png" /></figure><pre>dotnet tool install --global dotnet-sonarscanner</pre><p>Finalmente estamos prontos, mas antes disso, vamos propositadamente criar uma vulnerabilidade no metodo que possui expressão regular.</p><p>A nossa classe a ser analisado.</p><pre>public class Numbers<br>{<br>    public static bool IsValid(String number)<br>    {<br>        if (!IsNumber(number))<br>        {<br>            return false;<br>        }<br>        if (number.Trim().Length &gt; 10)<br>        {<br>            return false;<br>        }<br>        return true;<br>    }<br>    public static bool IsNumber(string number)<br>    {<br>        Regex regex = new(@&quot;^[0-9]+$&quot;, RegexOptions.None);<br>        return regex.IsMatch(number);<br>    }<br>}</pre><p>Agora podemos executar os comandos para coletar os dados para análise no SonarQube.</p><p>Nota: Deixei o <em>token</em> mas não partilhem o vosso.</p><pre>dotnet sonarscanner begin /k:&quot;xUnitCoverlet&quot; /d:sonar.host.url=&quot;http://localhost:9000&quot;  /d:sonar.token=&quot;sqp_caa35cbdd7c1925b93c69fa9c95a4f995937&quot;</pre><pre>dotnet build</pre><pre>dotnet sonarscanner end /d:sonar.token=&quot;sqp_caa35cbdd7c1925b93c69fa9c95a4f995937&quot;</pre><p>Agora podemos ver que existe uma vulnerabilidade (<em>Security Hotspot</em>) e outros pontos a serem melhorados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0QtBT67rtnaQ32XpjeV6A.png" /></figure><p>O nosso erro provocado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEW51o0sVhqpy7dhRgWLVg.png" /></figure><p>Depois de corigido, passamos a ter uma classe mais segura, com a inclusão do tempo de execução da expressão regular, que é uma vulnerabilidade que pode ser explorado em C#, mas simples com a redução de <strong><em>if</em></strong> e modificar <strong><em>static</em></strong> já que temos metodos estaticos.</p><pre>public static class Numbers<br>{<br>    public static bool IsValid(String number)<br>    {<br>        if (!IsNumber(number) || number.Trim().Length &gt; 10)<br>        {<br>            return false;<br>        }<br>        return true;<br>    }<br>    public static bool IsNumber(string number)<br>    {<br>        Regex regex = new(@&quot;^[0-9]+$&quot;, RegexOptions.None, TimeSpan.FromMilliseconds(5));<br>        return regex.IsMatch(number);<br>    }<br>}</pre><p>O novo resultado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGsqcj7tnivpYYPiRlHLbA.png" /></figure><h4>Conclusão</h4><p>Ferramentas como SonarQube podem ser muito úteis, mesmo havendo desenvolvedores que fazem revisão de código, consegue-se acelerar o processo de análise e identificação dos potencias problemas no código.</p><h4><strong>Referência</strong></h4><p><a href="https://www.sonarsource.com/">https://www.sonarsource.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c615c8ba8725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Software Testing in ASP.NET: Enhancing Software Quality: xUnit & Coverlet II]]></title>
            <link>https://medium.com/@silva.belarmino/ensure-reliability-stability-in-your-asp-net-core-project-with-tests-and-test-coverage-518c15bf2f40?source=rss-5c0eb44c3c36------2</link>
            <guid isPermaLink="false">https://medium.com/p/518c15bf2f40</guid>
            <category><![CDATA[test]]></category>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[coverlet]]></category>
            <dc:creator><![CDATA[Belarmino Silva]]></dc:creator>
            <pubDate>Sat, 12 Aug 2023 14:58:35 GMT</pubDate>
            <atom:updated>2023-09-14T23:49:00.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking the Power of Software Testing in ASP.NET: Enhancing Software Quality: xUnit &amp; Coverlet — II</h3><h3>Tests and Test Coverage with xUnit and Coverlet — Part II</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*elcKDCZm1AY_i_6M.png" /></figure><p>Software tests are crucial to guarantee the delivery of a good quality product, indentify bugs, additionally offer comfort in the maintenance phase, code refactoring or even when changing team members, in addition to other benefits listed in <a href="https://medium.com/@silva.belarmino/tests-and-test-coverage-with-xunit-and-coverlet-part-1-bba121f1f93d">part 1</a>.</p><p>As mentioned in the part 1, we will create a project with its corresponding test project using <strong>xUnit</strong> and <strong>Coverlet</strong>. To bring the example to life, we will create a folder for the projects. Within the folder, we will have a class library and the test project.</p><pre>mkdir xUnitCoverlet<br>cd xUnitCoverlet</pre><h4>Code to be tested</h4><p>In the class library below, we will have a class that contains a method that takes a string as input and validates whether it is a number and if it has no more than 10 characters.</p><p>Commands to create the class library project.</p><pre>dotnet new classlib -o xUnitCoverletLib<br>cd xUnitCoverletLib<br>dotnet new gitignore<br>cd ..</pre><pre>using System.Text.RegularExpressions;<br><br>namespace xUnitCoverletLib;<br>public class Numbers<br>{<br>    public static bool IsValid(String number)<br>    {<br>        if (!IsNumber(number))<br>        {<br>            return false;<br>        }<br>        if (number.Trim().Length &gt; 10)<br>        {<br>            return false;<br>        }<br>        return true;<br>    }<br>    public static bool IsNumber(string number)<br>    {<br>        Regex regex = new(@&quot;^[0-9]+$&quot;, RegexOptions.None, TimeSpan.FromMilliseconds(5));<br>        return regex.IsMatch(number);<br>    }<br>}</pre><h4>Test with xUnit</h4><p>Next, we have the test project that uses <strong>xUnit</strong>, and upon creation, it already includes the <strong>Coverlet</strong> library. To confirm this, after creating the test project, if we open the file <strong>xUnitCoverletTest.csproj</strong>, we will find one of the <strong>PackageReference</strong> entries as <strong>coverlet.collector</strong>.</p><p>Commands to create the test project.</p><pre>dotnet new xunit -o xUnitCoverletTest<br>cd xUnitCoverletTest<br>dotnet new gitignore<br>cd ..</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Lnr__2tozyrmpVAT.png" /></figure><p>The test class validates the result of the method execution. In our example, if the method receives a string with only numbers and no more than 10 characters, it should return <strong>true</strong>, otherwise, the result is <strong>false</strong>.</p><p>Two approaches were used for testing, one that allows passing multiple inputs as parameters to test (<strong>[Theory]</strong>) and another without parameters (<strong>[Fact]</strong>).</p><pre>using xUnitCoverletLib;<br><br>namespace xUnitCoverletTest;<br>public class NumbersTests<br>{<br>    [Fact]<br>    public void ValidOneNumber()<br>    {<br>        // ARRANGE<br>        string number = &quot;123324324&quot;;<br>        // ACT<br>        bool isNumer = Numbers.IsValid(number);<br>        // ASSERT<br>        Assert.True(isNumer);<br>    }<br>    public static readonly object[][] InsertValidNumbers = {<br>            new object[] { &quot;123456782&quot;},<br>            new object[] { &quot;1&quot;},<br>            new object[] { &quot;233&quot;},<br>    };<br>    [Theory, MemberData(nameof(InsertValidNumbers))]<br>    public void ValidMultipleNumber(string number)<br>    {<br>        // ACT<br>        bool isNumer = Numbers.IsValid(number);<br>        // ASSERT<br>        Assert.True(isNumer);<br>    }<br><br>    public static readonly object[][] InsertInvalidNumbers = {<br>            new object[] { &quot;12345678912&quot;},<br>            new object[] { &quot;Ola&quot;},<br>            new object[] { &quot;So Sabi&quot;},<br>            new object[] { &quot;12345q6789&quot;},<br>    };<br>    [Theory, MemberData(nameof(InsertInvalidNumbers))]<br>    public void InvalidNumbers(string number)<br>    {<br>        // ACT<br>        bool isNumer = Numbers.IsValid(number);<br>        // ASSERT<br>        Assert.False(isNumer);<br>    }<br>}</pre><p>The test project must reference our class library to be able to test the methods available in the class library. The following command allows referencing the class library. To confirm if it’s correct, you can open the file <strong>xUnitCoverletTest.csproj</strong> and check if there is a <strong>ProjectReference</strong> tag.</p><pre>cd xUnitCoverletTest<br>dotnet add reference ../xUnitCoverletLib</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*P1l-JYbU8m-stbaH.png" /></figure><p>With the two projects created, we can create a solution and add both to the solution , for organization purposes, follow the instructions below and an image of how it should be recognized by Visual Studio.</p><pre>dotnet new sln --name xUnitCoverlet<br>dotnet sln add xUnitCoverletLib<br>dotnet sln add xUnitCoverletTest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*52sTR75ccli3Lik9.png" /></figure><p>Now we are ready to test our class library. To do this, run the command below.</p><pre>cd xUnitCoverletTest<br>dotnet test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*l8lHmxpcSb9IZBO1.png" /></figure><p>The result was eight successful tests and zero failed tests. You might wonder how that’s possible with only three methods, and it doesn’t seem to make sense?</p><p>This happens because each line in the array passed as a parameter in the methods with [Theory] annotations counts as a separate test.</p><h4>Test coverage with Coverlet</h4><p>After running the tests, we can measure the test coverage level of our example. To collect data regarding the coverage with Coverlet, we need to add the following parameter to the test command.</p><pre>dotnet test --collect:&quot;XPlat Code Coverage&quot;</pre><p>The result of executing the command creates a file named <strong>coverage.cobertura.xml</strong>, which can be found in a folder with a name that is a UUID. In our example, the folder was named <strong>fe0cc9d8–90b1–4e59–9cdd-032d8fb423a8</strong>. Each execution of the command, a new folder is generated. All the generated folders are located inside the <strong>TestResults</strong> folder, which can be found in the root of the test project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*pqVgrNBWrI6oVBni.png" /></figure><p>The visual interpretation of the <strong>coverage.cobertura.xml</strong> file doesn’t seem to be practical. To better visualize the collected data, we have the <a href="https://github.com/danielpalme/ReportGenerator"><strong>ReportGenerator</strong></a> project, which allows converting the generated file (<strong>coverage.cobertura.xml</strong>) into a report that is easy to read and understand. You can install <strong>ReportGenerator</strong> by following the instructions below.</p><pre>dotnet tool install -g dotnet-reportgenerator-globaltool</pre><p>The tool allows generating reports in various formats. The following command generates reports in <strong>HTML</strong> format.</p><p>Note: The value “fe0cc9d8–90b1–4e59–9cdd-032d8fb423a8” in the following line should be changed according to the generated folder or the folder for which you want to generate the report.</p><pre>reportgenerator &quot;-reports:TestResults\fe0cc9d8-90b1-4e59-9cdd-032d8fb423a8\coverage.cobertura.xml&quot; &quot;-targetdir:coveragereport&quot; -reporttypes:Html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ezHsh70a5DoVOiwN.png" /></figure><p>In this example, we achieved 100% test coverage. We have an aggregated view and a view that shows the tested classes, as indicated in the following images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*xtTsXIEsQBTcYeCu.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*yUfVwDN1_APqg0xj.png" /></figure><p>The project can be found in the <a href="https://github.com/belarmino/xUnitCoverlet">repository</a>.</p><p><a href="https://medium.com/@silva.belarmino/tests-and-test-coverage-with-xunit-and-coverlet-part-1-bba121f1f93d">Tests and Test Coverage with xUnit and Coverlet — Part 1</a></p><h4>Conclusion</h4><p>Any changes made to the class library that alter the expected results will fail the tests, ensuring the consistency of the software’s behavior, for example, during the maintenance process.</p><p>It’s not always feasible to achieve 100% coverage; in such cases, the tool indicates the coverage level for each class, and we can also identify which methods need to covered. Achieving 100% coverage in a real project can be a ambitious goal, so it is essential to determine what is critical to test and should have a minimum percentage to accept level of coverage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=518c15bf2f40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>