<?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 Júnior on Medium]]></title>
        <description><![CDATA[Stories by Nelson Júnior on Medium]]></description>
        <link>https://medium.com/@nelsoncvjr?source=rss-998c63412f68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h9qasRh84a1tvST9ngSpSQ.png</url>
            <title>Stories by Nelson Júnior on Medium</title>
            <link>https://medium.com/@nelsoncvjr?source=rss-998c63412f68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:52:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nelsoncvjr/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[Traduzindo método C# em SQL query no EF Core]]></title>
            <link>https://medium.com/@nelsoncvjr/traduzindo-m%C3%A9todo-c-em-sql-query-no-ef-core-25cf1a9a2c28?source=rss-998c63412f68------2</link>
            <guid isPermaLink="false">https://medium.com/p/25cf1a9a2c28</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[linq]]></category>
            <dc:creator><![CDATA[Nelson Júnior]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 03:22:46 GMT</pubDate>
            <atom:updated>2024-01-15T00:43:19.350Z</atom:updated>
            <content:encoded><![CDATA[<p>Cenário: A entidade tinha uma propriedade do tipo <strong>byte[]</strong> que representa uma coluna do tipo <strong>timestamp</strong> no SQL Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X60NfqXhVF0hjgXmbtcArQ.png" /></figure><p>Necessidade: Buscar todos os registros com uma versão maior ou igual a que foi passada pelo usuário.</p><p>Problema: Não é possível fazer operação de <em>Greater Than</em> ou <em>Greater Than Or Equals</em> em cima de byte[], logo, não compila.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gh-XyUu624113NAmnkogg.png" /></figure><p>Solução:</p><pre>public static class MyDbFunctions<br>{<br>    public static bool GreaterThanOrEqual(byte[] left, byte[] right) =&gt; throw new NotImplementedException();<br>}</pre><pre>var queryable = dbContext.SampleEntities.Where(x =&gt; MyDbFunctions.GreaterThanOrEqual(x.Version, version));</pre><p>Porém, isso nos leva a outro problema. O EF não consegue traduzir a expressão em uma query nativa para o SQL Server.</p><pre>System.InvalidOperationException: The LINQ expression &#39;DbSet&lt;SampleEntity&gt;()<br>    .Where(s =&gt; MyDbFunctions.GreaterThanOrEqual(<br>        left: s.Version, <br>        right: __version_0))&#39; could not be translated. Additional information: Translation of method &#39;MyDbFunctions.GreaterThan&#39; failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to &#39;AsEnumerable&#39;, &#39;AsAsyncEnumerable&#39;, &#39;ToList&#39;, or &#39;ToListAsync&#39;. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.</pre><p>Para resolver esse problema, vamos usar um recurso disponível no EF de tradução.</p><p>Vamos obter o MethodInfo e registrar o nome do método e a assinatura no <em>DbContext</em>, através do <em>OnModelCreating.</em></p><pre>var methodInfo = typeof(MyDbFunctions).GetMethod(nameof(MyDbFunctions.GreaterThanOrEqual), BindingFlags.Static | BindingFlags.Public, [typeof(byte[]), typeof(byte[])]);</pre><p>Obs: a sintaxe de array é C# 12.</p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    var methodInfo = typeof(MyDbFunctions).GetMethod(nameof(MyDbFunctions.GreaterThanOrEqual), BindingFlags.Static | BindingFlags.Public, [typeof(byte[]), typeof(byte[])]);<br><br>    modelBuilder<br>        .HasDbFunction(methodInfo)<br>        .HasTranslation(_ =&gt; throw new NotImplementedException());<br>}</pre><p>O próximo passo é tratar a <em>expression</em> que chega no <em>HasTranslation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1O2wuJ-fvClfjmxlbLOH2g.png" /></figure><p>A implementação final fica:</p><pre>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    var methodInfo = typeof(MyDbFunctions).GetMethod(nameof(MyDbFunctions.GreaterThanOrEqual), BindingFlags.Static | BindingFlags.Public, [typeof(byte[]), typeof(byte[])]);<br><br>    modelBuilder<br>        .HasDbFunction(methodInfo)<br>        .HasTranslation(args =&gt;<br>        {<br>            var leftArg = args[0];<br>            var expr = new SqlBinaryExpression(ExpressionType.GreaterThanOrEqual, leftArg, args[1], leftArg.Type, leftArg.TypeMapping);<br><br>            return expr;<br>        });<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6uuUsMnSXuWo7do__0yXg.png" /></figure><p>Resultado do Queryable:</p><pre>SELECT [s].[Id], [s].[Number], [s].[Version]<br>FROM [SampleEntities] AS [s]<br>WHERE [s].[Version] &gt;= @__version_0</pre><p>O código completo encontra-se no repositório: <a href="https://github.com/ircnelson/efcore-custom-functions">https://github.com/ircnelson/efcore-custom-functions</a></p><p>Referências:</p><ul><li><a href="https://jaliyaudagedara.blogspot.com/2022/03/custom-ef-core-function-to-use-transact.html">Custom EF Core Function to Use Transact-SQL AT TIME ZONE</a></li><li><a href="https://learn.microsoft.com/en-us/ef/core/querying/user-defined-function-mapping#mapping-a-method-to-a-custom-sql">User-defined function mapping - EF Core</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25cf1a9a2c28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aplicando migrations de forma resiliente com Polly em C#]]></title>
            <link>https://medium.com/@nelsoncvjr/aplicando-migrations-de-forma-resiliente-com-polly-em-c-ede56e758af5?source=rss-998c63412f68------2</link>
            <guid isPermaLink="false">https://medium.com/p/ede56e758af5</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[polly]]></category>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nelson Júnior]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 04:28:38 GMT</pubDate>
            <atom:updated>2020-10-02T12:07:46.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*awuiuSENTuPnYNJua63gLA.png" /><figcaption>Polly (logo)</figcaption></figure><p>Em vários projetos eu tenho reparado o uso do script bash conhecido como <em>wait-for-it</em> onde sua finalidade é ficar observando um determinado programa se ele já está pronto e respondendo.</p><p>Por exemplo, quando é criado uma instância de SQL Server em um container docker, o processo do SQL Server, em caso de sucesso, sinaliza a saída 0 e isso indica que não ocorreu erro no processo principal, porém isso não quer dizer que um outro programa consiga estabelecer conexão com o servidor. Ainda pode estar acontecendo rotina de restauração de backup.</p><p>Apesar do docker compose nos permitir atribuir serviços dependentes através da propriedade <em>depends_on</em>, isso não garante que o programa <em>X</em> que depende do SQL Server vai ter sucesso, exatamente pela explicação acima em relação a saída 0.</p><p>Uma das formas do programa <em>X</em> ter sucesso é usando o <em>wait-for-it</em>.</p><p>Eu confesso que não gosto muito dessa abordagem e ela sempre me incomodou um pouco. Já tive problemas usando esse script onde ele causava <em>hang</em> na aplicação.</p><p>A abordagem que trago é utilizando a biblioteca <a href="https://github.com/App-vNext/Polly">Polly</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eb7ae0071b562c79a7a5e2516e5f93d/href">https://medium.com/media/4eb7ae0071b562c79a7a5e2516e5f93d/href</a></iframe><p>Utilizando <em>Polly</em> eu consigo estabelecer uma política de tratamento pra uma determinada <em>Exception</em>, nesse caso <em>System.Data.SqlClient.SqlException</em>. No exemplo eu aplico no máximo 10 tentativas de execução da rotina em um intervalo - em segundos - determinado pelo número da tentativa atual elevado a 2.</p><p>Isso é equivalente a:</p><p>tentativa 01 - 00:00:02<br>tentativa 02 - 00:00:04<br>…<br>tentativa 06 - 00:01:04<br>tentativa 07 - 00:02:08<br>…<br>tentativa 09 - 00:08:32<br>tentativa 10 - 00:17:04</p><p>O delegate que está dentro de <em>retry.Execute(() =&gt; {});</em> é o que será executado, no nosso exemplo a rotina de migração.</p><p>Obs: Caso esteja rodando a aplicação de migration com <em>deployment</em> dentro do Kubernetes, não se faz necessário pensar nessa abordagem devido a política de <em>retry</em> nativa dentro do k8s.</p><p>Caso precise mesclar a implementação com e sem <em>retry</em>, se faz necessário verificar através de alguma variável de ambiente se a aplicação está rodando em k8s.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42fd029c37361b5f35435c84fecc12e7/href">https://medium.com/media/42fd029c37361b5f35435c84fecc12e7/href</a></iframe><p>Se a execução da migração falhar, deixa a exception vazar que isso vai causar um erro no programa, fazendo com o que o k8s aplique sua política de <em>retry</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ede56e758af5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust Macros power]]></title>
            <link>https://medium.com/@nelsoncvjr/rust-macros-power-e83eaefcd633?source=rss-998c63412f68------2</link>
            <guid isPermaLink="false">https://medium.com/p/e83eaefcd633</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Nelson Júnior]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 18:32:05 GMT</pubDate>
            <atom:updated>2020-07-12T18:41:25.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*saQiRpGtGeM-CWCvk9saJw.png" /></figure><p>Today I&#39;m started to solve some exercises in exercism.io.</p><p>In Raindrops exercise I wrote the first code to pass all tests. The code above is not too much.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78c0ab0faf59628d5d591d1fb6697b94/href">https://medium.com/media/78c0ab0faf59628d5d591d1fb6697b94/href</a></iframe><p>I’m not happy with this code, because body functions are similar enough. Although it works and I know there are Macros in the Rust lang, but I never created one, and I found the moment to learn about and apply. :).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea5312eb12354203448d5b3b63b40339/href">https://medium.com/media/ea5312eb12354203448d5b3b63b40339/href</a></iframe><p>Reference:</p><p><a href="https://doc.rust-lang.org/1.7.0/book/macros.html">https://doc.rust-lang.org/1.7.0/book/macros.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e83eaefcd633" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting configurations from environment variables and files in Rust lang application]]></title>
            <link>https://medium.com/@nelsoncvjr/getting-configurations-from-environment-variables-and-files-in-rust-lang-application-ff9368485cd6?source=rss-998c63412f68------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff9368485cd6</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Nelson Júnior]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 06:28:27 GMT</pubDate>
            <atom:updated>2020-06-22T13:27:58.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Ferris mascot" src="https://cdn-images-1.medium.com/max/600/1*saQiRpGtGeM-CWCvk9saJw.png" /></figure><p>Some things are commonly necessary when we run an application like to pass and getting external data to the inside of the application.</p><p>This data could be provided by any sources, e.g, environment variables, command-line arguments, files, etc.</p><p>In the Cargo.toml file we need to add these dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f37342bee809a284420218e7a3716e53/href">https://medium.com/media/f37342bee809a284420218e7a3716e53/href</a></iframe><p><a href="https://crates.io/crates/serde">serde</a>: responsible to serialize/deserialize data structures.<br><a href="https://crates.io/crates/dotenv">dotenv</a>: responsible to capture key/pair value from .env file.<br><a href="https://crates.io/crates/config">config</a>: responsible for aggregate any sources in a data structure.</p><p>Next, create file below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e56800932cc0aa6d5e95ca209427794f/href">https://medium.com/media/e56800932cc0aa6d5e95ca209427794f/href</a></iframe><p>In this file, have structs of application settings and the <em>new()</em> method.</p><pre>Note: <em>Settings</em> and <em>ServerConfig</em> both are annotated with <em>#[derive(Deserialize)]</em>. This is mandatory because these data structures are not primitive, different from the String and i32.</pre><p>In <em>src/config.rs:20</em> create a resource named <em>cfg, </em>initialize <em>Config struct, </em>and call merge method passing the sources.</p><p>The first source is a file <em>config/default</em>. See that not have an extension, and it&#39;s not a problem, the method <em>File::with_name</em> resolve and parse correctly.</p><pre>Note: Config supports .toml, .json, .yaml, .ini, and .hjson</pre><p>We can create a convention over configuration based on the environment name, e.g., config/development, config/testing, config/production, or config/my_env_name.</p><p>And the last source is all environment variables.</p><p>The order of .merge() is relevant because it defines the priority of replacement values.</p><p>In <em>src/config.rs:24</em> the call <em>try_into()</em> method and here occur deserialization for the struct type.</p><p>The code below is more complete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2445619f478578065f48726eb01cb0/href">https://medium.com/media/cd2445619f478578065f48726eb01cb0/href</a></iframe><p>In this example, the output will be: <strong>Server: 127.0.0.1:5001 </strong>because the loading order is:<br>1. <em>config/default.toml</em><br>2. <em>config/development.toml</em><br>3. <em>environment variables</em></p><pre>Note: Could be getting environment variables based on prefix. For example:</pre><pre>cfg.merge(Environment::with_prefix(&quot;MY_APP&quot;))?;</pre><pre>Only variables prefixed with MY_APP will be loaded. This is very useful.</pre><p>For more information, please check crates documentation and repository code, we have much to learn in these places.</p><p>That&#39;s it. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff9368485cd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>