<?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 Vitorgithub on Medium]]></title>
        <description><![CDATA[Stories by Vitorgithub on Medium]]></description>
        <link>https://medium.com/@vitorgithub?source=rss-c975e33a66e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Djz7Ssyk-vH44jBWkaPSuA.png</url>
            <title>Stories by Vitorgithub on Medium</title>
            <link>https://medium.com/@vitorgithub?source=rss-c975e33a66e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:14:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vitorgithub/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[XML e JSON — Fundamentos]]></title>
            <link>https://medium.com/@vitorgithub/xml-e-json-fundamentos-0ad188747301?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ad188747301</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 22:16:20 GMT</pubDate>
            <atom:updated>2023-10-12T05:39:03.135Z</atom:updated>
            <content:encoded><![CDATA[<h3>XML e JSON — Fundamentos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*k09wZ22aKP4JL7iBEk1qrg.png" /></figure><p>No começo dos tempos da computação moderna, precisávamos de um meio padronizado para trocar dados entre sistemas.</p><p><strong>História:</strong><br>No ano de 1996 foi criado o XML <br>No ano de 2000 foi criado o JSON</p><p>Em 1996 XML foi criado para estruturar dados de uma maneira detalhada e um pouco complicada. Imagine que você tem que detalhar cada passo de uma receita, ao invés de simplesmente listar os ingredientes e as etapas (XML é como descrever cada pequeno detalhe).</p><p>Em 2000 JSON foi criado para estruturar dados de uma maneira mais objetiva e direta. Ele se tornou o preferido para muitos desenvolvedores, especialmente aqueles focados em aplicações web, por ser mais simples e fácil de integrar com linguagens de programação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbIm69UY1gZY8UkpH22tOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8uVa11SQN7uDp1-Y3125g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmVane0UwWopeg6CWnuOOQ.png" /></figure><p><strong>Conclusão:<br></strong>A escolha entre XML e JSON vai depender muito do que você precisa. Se você está lidando com sistemas mais antigos ou precisa de um formato bem detalhado, o XML pode ser o caminho. Mas, se você quer algo mais leve, rápido e fácil de mexer, especialmente para aplicações web, o JSON é a opção mais indicada.</p><h4>Se você aprendeu POO em C# irá conseguir entender a seguir.</h4><p>Para desenvolvedores C#, especialmente aqueles familiarizados com os conceitos de Programação Orientada a Objetos (POO), trabalhar com JSON torna-se mais intuitivo. De fato, o JSON tornou-se o padrão de fato para a troca de dados em APIs RESTful.</p><h3># Bibliotecas em .NET para JSON</h3><p>Antes de mergulharmos nas operações específicas, é fundamental entender por que precisamos de bibliotecas especializadas para lidar com JSON em .NET. As bibliotecas facilitam o trabalho com JSON, evitando os erros comuns.</p><p>1. `<strong>System.Text.Json</strong>`: <br><em>É a biblioteca padrão da Microsoft, eficiente, performática, segura, usa menos memória, (porém tem menos recursos)</em><br>2. `<strong>Newtonsoft.Json</strong>` (Json.NET): <br><em>Era a biblioteca padrão, é flexível e tem mais recursos.</em></p><h4>## Por que usar uma biblioteca?</h4><p><strong>Manipular strings JSON manualmente é ineficiente e propenso a erros. As bibliotecas oferecem métodos para:</strong><br>- Serializar objetos em strings JSON.<br>- Desserializar strings JSON de volta para objetos.<br>- Lidar com cenários avançados, como herança, referências de objetos e conversões personalizadas.</p><h3>1. Serialização e Desserialização:</h3><p>Serialização é o processo de transformar um objeto em uma string formatada em JSON para, por exemplo, enviar através de uma API. Desserialização é o processo inverso, onde uma string formatada em JSON é transformada de volta em um objeto.</p><pre>// Exemplo usando System.Text.Json<br>using System.Text.Json;</pre><pre>public class Pessoa<br>{<br>    public string Nome { get; set; }<br>    public int Idade { get; set; }<br>}<br><br>// Serializar<br>Pessoa pessoa = new Pessoa { Nome = &quot;João&quot;, Idade = 30 };<br>string jsonString = JsonSerializer.Serialize(pessoa);<br><br>// Desserializar<br>Pessoa pessoaDeserializada = JsonSerializer.Deserialize&lt;Pessoa&gt;(jsonString);</pre><h3>2. Lidando com cenários avançados:</h3><p>Quando se trata de OOP, situações como herança, polimorfismo e referências cruzadas são comuns. Bibliotecas especializadas ajudam a lidar com essas complexidades:</p><ul><li><strong>Herança e Polimorfismo:</strong> <br>Ao serializar objetos que têm uma relação de herança, você deseja que o JSON reflita corretamente os tipos derivados. Por exemplo, ao serializar uma lista de `Animais` que pode conter tanto `Cachorros` quanto `Gatos`.</li></ul><pre>public class Animal<br>{<br>    public string Nome { get; set; }<br>}</pre><pre>public class Cachorro : Animal<br>{<br>    public string Raça { get; set; }<br>}<br><br>public class Gato : Animal<br>{<br>    public bool TemBigode { get; set; }<br>}<br><br>List&lt;Animal&gt; animais = new List&lt;Animal&gt; {<br>    new Cachorro { Nome = &quot;Rex&quot;, Raça = &quot;Labrador&quot; },<br>    new Gato { Nome = &quot;Mingau&quot;, TemBigode = true }<br>};<br><br>string animaisJson = JsonSerializer.Serialize(animais);</pre><ul><li><strong>Referências de Objetos:</strong> <br>Em cenários em que o mesmo objeto é referenciado várias vezes no mesmo JSON, como em uma relação pai-filho, é crucial manter essa referência ao serializar e Desserializar.<br><strong><em># Dica:</em></strong><em> Em projetos complexos, cuidado com referências circulares. Newtonsoft.Json tem a opção </em><em>ReferenceLoopHandling para lidar com isso.</em></li><li><strong>Conversões Personalizadas:</strong> Às vezes, o formato JSON que recebemos não se alinha exatamente com nosso modelo. Podemos precisar de um conversor personalizado.</li></ul><pre>public class DateTimeConverter : JsonConverter&lt;DateTime&gt;<br>{<br>    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)<br>    {<br>        return DateTime.Parse(reader.GetString());<br>    }<br> <br>    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)<br>    {<br>        writer.WriteStringValue(value.ToString(&quot;yyyy-MM-dd&quot;));<br>    }<br>}</pre><h3>3. Migração entre Bibliotecas</h3><p>Migrar de Newtonsoft.Json para System.Text.Json pode parecer um desafio, mas seguindo algumas etapas, a transição torna-se mais simples. Aqui está um exemplo prático:</p><p>Suponhamos que em Newtonsoft.Json você tenha:</p><pre>using Newtonsoft.Json;<br><br>Pessoa pessoa = new Pessoa { Nome = &quot;João&quot;, Idade = 30 };<br>string jsonString = JsonConvert.SerializeObject(pessoa, Formatting.Indented);<br>Pessoa pessoaDeserializada = JsonConvert.DeserializeObject&lt;Pessoa&gt;(jsonString);</pre><p>Em System.Text.Json`, seria assim:</p><pre>using System.Text.Json;<br><br>Pessoa pessoa = new Pessoa { Nome = &quot;João&quot;, Idade = 30 };<br>string jsonString = JsonSerializer.Serialize(pessoa);<br>Pessoa pessoaDeserializada = JsonSerializer.Deserialize&lt;Pessoa&gt;(jsonString);</pre><p>Os nomes dos métodos e propriedades mudam ligeiramente. Lembre-se também de verificar propriedades especiais e configurações que podem não ter um correspondente direto na nova biblioteca.</p><h3>4. Testes e Validação</h3><p>Ao testar:</p><ol><li><strong>Utilize casos de uso reais:</strong> Isso garante que seus testes refletem situações do mundo real.</li><li><strong>Teste ambas as serializações e desserializações:</strong> Garanta que a informação seja preservada em ambos os processos.</li><li><strong>Use ferramentas de validação de JSON:</strong> Isso pode ajudar a detectar problemas rapidamente.</li></ol><pre># Ao testar a serialização, você pode usar:<br>Assert.AreEqual(expectedJsonString, actualJsonString);<br><br># Ao testar a desserialização, você pode usar:<br>Assert.AreEqual(expectedPessoaObject, actualPessoaObject);</pre><h3>Erros e Exceções</h3><p>Manipular JSON implica estar preparado para erros, seja devido a uma string JSON mal formatada, um valor inesperado ou uma estrutura de dados desconhecida. Ambas as bibliotecas, `System.Text.Json` e `Newtonsoft.Json`, proporcionam meios de lidar com tais situações.</p><p>1. <strong>Manipulação de Erros</strong>:</p><p>Ao desserializar JSON, é comum encontrar erros se a estrutura do JSON não corresponder ao objeto de destino.</p><pre>using System;<br>using System.Text.Json;<br><br>public class Pessoa<br>{<br>    public string Nome { get; set; }<br>    public int Idade { get; set; }<br>}<br><br>string invalidJson = &quot;{ Nome : João }&quot;;  // O nome da propriedade está sem as aspas<br><br>try<br>{<br>    // Tentativa de desserializar o JSON inválido<br>    var pessoa = JsonSerializer.Deserialize&lt;Pessoa&gt;(invalidJson);<br>}<br><br>catch (JsonException e)<br>{<br>    Console.WriteLine(&quot;Erro ao desserializar o JSON: &quot; + e.Message);<br>    // Em um ambiente real, você provavelmente registraria esse erro em um log.<br>}</pre><p>Este exemplo destaca como lidar com um JSON mal formatado. A exceção `JsonException` é lançada e podemos capturá-la para tratamento adequado.</p><p><strong><em>Dica:</em></strong><em> Em ambientes de produção, evite expor detalhes de erro diretamente. Em vez disso, registre-os e ofereça uma mensagem amigável ao usuário.</em></p><p>2. <strong>Validação</strong>:</p><p>Quando a estrutura do JSON é conhecida antecipadamente, é útil validar a entrada.</p><pre>using System;<br><br>string jsonString = &quot;{ \&quot;Nome\&quot;: \&quot;João\&quot; }&quot;;<br><br>// Validação simples para verificar se uma propriedade específica está presente<br>if (!jsonString.Contains(&quot;\&quot;Nome\&quot;&quot;))<br>{<br>    throw new InvalidOperationException(&quot;JSON inválido: propriedade &#39;Nome&#39; ausente.&quot;);<br>}<br><br>// Em cenários mais complexos, considere usar validações mais elaboradas ou esquemas JSON.</pre><p>Este exemplo mostra uma forma básica de validação. Dependendo da complexidade, podem ser necessárias abordagens mais robustas, como esquemas JSON ou bibliotecas de validação dedicadas.</p><h3>Escolhendo a Biblioteca Certa:</h3><p>Para novos projetos em .NET Core ou .NET 5/6, System.Text.Json é uma excelente opção. No entanto, Newtonsoft.Json ainda é uma ferramenta valiosa, especialmente para projetos existentes ou quando se busca flexibilidade.</p><p><strong><em># Dica:</em></strong><em> Em projetos maiores, a consistência é chave. Escolha uma biblioteca e fique com ela em todo o projeto para evitar comportamentos inesperados.</em></p><p>Em resumo, é essencial ter uma compreensão clara das ferramentas e bibliotecas ao lidar com JSON em C# .NET. Isso garante a eficiência, robustez e resiliência de suas aplicações. Mantenha-se atualizado, pois o ecossistema .NET está sempre evoluindo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiR7mGlgtxZLVeyQaALExw.png" /></figure><p>Fique tranquilo! Se você é iniciante a tabela acima e as tabelas abaixo serão “nebulosas”, continue sua jornada de estudos que com o tempo você irá revisitar esse documento e irá compreender.</p><blockquote><strong><em>Recursos:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7V2ksYnOVlWVuAx12JvCMA.png" /></figure><blockquote><strong><em>Atributos de Serialização:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5-XkU6fSCMG-16IZhF1ow.png" /></figure><blockquote><strong><em>Configurações personalizadas:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkciFYKPLD0ZKcn7qf-Hog.png" /></figure><p>Abraços!</p><p><a href="https://www.linkedin.com/in/vitorgithub/">Clique aqui para acessar meu Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ad188747301" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use ELK Stack (Elasticsearch + Logstash + Kibana) + Kafka for logging]]></title>
            <link>https://medium.com/@vitorgithub/how-to-use-elk-stack-elasticsearch-logstash-kibana-kafka-for-logging-8151a436c722?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8151a436c722</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 20:11:14 GMT</pubDate>
            <atom:updated>2023-10-09T20:11:14.294Z</atom:updated>
            <content:encoded><![CDATA[<p>Logging is very important in the world of programming. When the program does not work as expected, the first source we will refer to understand the cause of the problem is the log. We can export the log to a file or database, but they are not preferred because the search feature of these tools is not very good. At this point, ELK Stack is the open-source logging platform preferred by big companies such as Netflix and LinkedIn. Thanks to the ELK Stack, we can see the logs from a common point, which becomes an important feature especially when microservices are used, because it allows us to see all the logs during a request from a single point. In addition, since ELK Stack works in a distributed structure, its performance and accessibility are quite high. ELK Stack basically consists of E(lasticsearch) + L(ogstah) + K(ibana). If the total log count is high, Kafka can be put on the front side as a temporary cache.</p><p>Basically, the build consists of 5 steps as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*ZwhKhIWjqXju2TXI.png" /></figure><p>1- First of all, your program creates the logs and sends them to Kafka with a logging library such as Serilog. We can also use Kafka’s own library for this job, but it is more efficient to use these libraries as they have features such as batch logging in groups of 50.</p><p>2- Kafka is a high-performance and distributed event stream platform. Logging is a very convenient example of event streaming. In the event stream, a source constantly throws an event and the structures listening to it are constantly processing this event. The reason why Kafka is included here, apart from ELK Stack, is to provide high performance. The logs from the application could also be thrown directly to Elasticsearch, but since the indexing process will be performed when Elasticsearch receives the logs, it is safer to send the logs first to Kafka.</p><p>3- Logs sent to Kafka are received by Logstash listening to it. Here Logstash’s task is to take the data from Kafka and send it to Elasticsearch. Logically, we could do this by writing a program that listens to Kafka and calls Elasticsearch APIs, but Logstash performs this process with configuration files and works very stable.</p><p>4- Elasticsearch is a NoSQL database that Logstash sends to store data. The reason why it is ahead of other NoSQL databases to keep logs is the Lucene search engine it uses in the back. Thanks to the Lucene search engine, it is highly specialized in full-text search.</p><p>5- After the data is stored in Elasticsearch, its interface Kibana is used to query them. Elasticsearch management can also be done from the Kibana interface.</p><p>After describing the basic flow, the task of each part is explained in more detail below.</p><h3>Elasticsearch</h3><p>Elasticsearch is basically a NoSQL database and is built on the Lucene search engine. It offers us Rest APIs to use its functions. There are structures in place to prevent the hard drive from filling up by providing automatic deletion of old data, which is called Index Lifecycle Management. The basic concepts of Elasticsearch are as follows.</p><p><strong>Cluster</strong>: Elasticsearch can use many servers (nodes) simultaneously to work with high performance, and nodes working together form a cluster. When a new node joins the cluster, the existing data is moved to the new server and the load on the other nodes is reduced. When a server is removed from the cluster, its data is multiplexed to other servers. To ensure high availability, the replica of each data is automatically copied to other servers (the number of stored copies is determined by configuration). In this way, there is no data loss if one of the servers goes down at any time.</p><p><strong>Node</strong>: Each Elasticsearch server in the cluster is called a node.</p><p><strong>Index</strong>: It is the structure corresponding to a table in the relational database. Each index consists of documents corresponding to rows in the relational database. Creating indexes in log files on a daily basis is better in terms of performance. As an example, we can create a daily index file of the form CustomerService-09.06.2023. When searching through Kibana, we can search all indexes starting with CustomerService by creating a Dataview in the form of CustomerService*. We can create as many indexes as we want in a cluster.</p><p><strong>Document</strong>: Each record that is thrown into Elasticsearch. Consists of key- value pairs in JSON. The values within each record are then indexed for quick searching.</p><p><strong>Shard</strong>: Indexes are divided into Shards to work with high performance. Each shard can run on different nodes. In this way, high performance can be achieved.</p><p><strong>Replica</strong>: The copy of each shard is called a replica. As a result of copying the shard, both queries run better and there is no data loss in case of a problem with one of the nodes.</p><p>As an example, the following Elasticsearch cluster has 3 nodes and an index is divided into 5 shards. Each shard has a replica. In this case, when Node3 fails, shard 2 and shard 5 on it have copies on the other servers, so the processes continue to run smoothly and Elasticsearch makes the copy shards the master shard and creates the new replicas in a distributed manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5JnQTmofGMgV3PVI.png" /></figure><h3>Logstash</h3><p>It is a data collection tool for Elasticsearch. It collects data from various tools, modifies it, and sends it to another tool, for which the configuration file is used. The Logstash configuration file consists of 3 sections.</p><p><strong>Input</strong>: Specifies from which source the data will be retrieved. There are many input plugins such as Kafka, Redis, s3. The following example retrieves data from the elk1 topic in Kafka with the Kafka plugin.</p><p><strong>Filter</strong>: If changes are to be made to the imported data, it is done in this section. In the example below, the name of a header in JSON has been changed.</p><p><strong>Output</strong>: Specifies where the data is transferred after it is received and modified. There are output plugins such as Elasticsearch, Kafka, Redis. The following sample data is imported into Elasticsearch. In the generated index name, the date is added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1QLx5ERC2397y5rI.png" /></figure><h3>Kibana</h3><p>It is the interface where the data in Elasticsearch is displayed. It has an easy-to-use interface and users can search it based on date. For example, you can quickly see how many times the CustomerService method has been called in the last 15 minutes, or how many have succeeded. It goes to multiple Elasticsearch nodes on the back side to ensure that queries are made quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1UL2vvFGQQ_WAIB-.png" /></figure><h3>Kafka</h3><p>It is a structure other than the ELK Stack, but it is used to guarantee that all logs are recorded, especially when the log entry is intensive. When Elasticsearch first retrieves data, it needs to index it for quick access later. During this indexing process, log records are first thrown to Kafka to avoid timeout. Logstash pulls all records by one and send them to Kafka. Kafka provides us with a structure in which all records are guaranteed to be processed. Similar to Elasticsearch, it keeps data distributed for the cluster environment and distributes the data to other nodes in case of failure on any one server. If a new server is added, it also distributes the existing load to the new nodes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8151a436c722" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to read azure secret or protected variables in an effective way.]]></title>
            <link>https://medium.com/@vitorgithub/how-to-read-azure-secret-or-protected-variables-in-an-effective-way-7aab30b0d4c0?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aab30b0d4c0</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 20:07:32 GMT</pubDate>
            <atom:updated>2023-10-09T20:07:32.238Z</atom:updated>
            <content:encoded><![CDATA[<p>Azure typically offers two sorts of variables (Plain and Secret) to create in the set of library variables. Additionally, versioning is not available in these variable groups in Azure. This implies that the previous values are overridden, and you can only view the current value. Therefore, if a secret variable is marked with an asterisk (*), neither developers nor administrators will be able to access its values directly from the Azure Library group. Using secret variables, Azure offers a quick and effective solution to store sensitive data. Protected resources include secret variables. Applications or pipelines running on Azure can access these secret variables. I’ll go over how to read Azure secret variables successfully in this short and quick-read blog. Let’s start now!</p><p><strong>Problem statement</strong>- After creating a secret variable in the library variable group, the administrator would not be able to perform this operation if they wanted to verify the value or read it. The secret values of variables are not copied by Azure when you clone a library variable group for a new environment. Therefore, you either can get in touch with the proper party who is in possession of the correct value for those parameters, or you need to override with new values, which makes it difficult for you to know the precise value, OR they must extract the value from a particular variable group.</p><p><strong>Solution</strong> that I find effective and worked for me always- read and extract Azure secret variables from a particular variable group.</p><p><strong>Step 1</strong> — Identify your secret variable from variable group that you want to extract. Let’s take example from below here are two variable and and one is apiName is plain text that I can see but is secret and I am unable to read that value. So I want to extract the value for .apiKeyapiNameapiKeyapiKey</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*IFCIz7EXHxSpTi5b.png" /></figure><p><strong>Step 2</strong>- Create a yaml file, sample below :-</p><pre>trigger:<br>- main<br>pool:<br>  vmImage: &#39;ubuntu-latest&#39;<br>variables:<br>- group: AzureVariableGroup # define your variable group name here.<br>steps:<br>- task: Bash@3<br>  inputs:<br>    targetType: &#39;inline&#39;<br>    script: |<br>      # Here `apiKey` is a secret variable that we have in `AzureVariableGroup` and  would like to read.<br>      # secretsValue.txt is a file that will be generated on workspace with an unmasked value of `apiKey` secret variable. You can give any name for this .txt file.<br>      echo &quot;Secret values are here -&gt; $(apiKey)&quot; &gt;&gt; $PIPELINE_WORKSPACE/secretsValue.txt<br>- task: PublishPipelineArtifact@1<br>  inputs:<br>    targetPath: &#39;$(Pipeline.Workspace)/secretsValue.txt&#39;<br>    artifact: &#39;Secrets&#39;<br>    publishLocation: &#39;pipeline&#39;</pre><p><strong>Step 3</strong> — Go to Pipeline tab in your board and click on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*0yAiZJ1Kr7DBL3GG.png" /></figure><p><strong>Step 4 </strong>— Now Select Your Pipeline. Here is my pipeline name `Blog.Aafridi` and Click on it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zuVPP64dVdSXSkao.png" /></figure><p><strong>Step 5</strong> — After that you will see `Run Pipeline` and Click on it. it will give you another Popup window with pre-set values. You can change these based on your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/0*golhIquwyge_05co.png" /></figure><p><strong>Step 6</strong> -Click on Run and wait till finish your pipeline. Once it will finish it will published on artifact where you can see your file and you can download it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vnR07X5n_FmYXVgV.png" /></figure><p><strong>Step 7</strong> — Click on published and you can see your file with secret variables with unmasked values inside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6mqH5QpTb5RhwOZt.png" /></figure><p><strong>Step 8</strong> — You can see the content in downloaded file. Here is the snapshot of the same and secret value of ` was `wekrjlwerlkew`.apiKey`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*HIJZPSlAuSOGOLQN.png" /></figure><p><strong>Conclusion</strong> — You can successfully read Azure secret variables while upholding security and compliance by adhering to the yaml code. Utilize Azure Key Vault’s features and follow industry standards for storing sensitive data securely. To safeguard your application and uphold data integrity within the Azure ecosystem, it is crucial that you preserve your secret variables.</p><p>Please share this blog with your friends and coworkers if you like it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aab30b0d4c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your First Azure DevOps CI CD Pipeline: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@vitorgithub/building-your-first-azure-devops-ci-cd-pipeline-a-step-by-step-guide-308bb6b898d5?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/308bb6b898d5</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 16:22:17 GMT</pubDate>
            <atom:updated>2023-10-09T16:22:17.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xge_WsYT2g4yrlFD.png" /></figure><p><strong>What and Why Azure Pipelines?</strong></p><p>Azure Pipelines provides cloud-based solutions. It develops and tests code projects automatically. It supports all major programming languages and project types, and it combines continuous integration, continuous delivery, and continuous testing to develop, test, and distribute your code to any location.</p><p>Azure Pipelines is a critical component of <strong>Azure DevOps</strong>.</p><p>Azure Pipelines offers a quick, simple, and secure solution to automate the creation of projects with consistent and high-quality code that is easily accessible to users.</p><p>Azure Pipelines can be used to enable the following scenarios:</p><ul><li><strong>It is compatible with any language or platform.</strong></li><li><strong>Deploys to multiple targets at the same time</strong>.</li><li><strong>Connects to Azure installations</strong>.</li><li><strong>Builds on Windows, Linux, and Mac computers</strong>.</li><li><strong>Connects to GitHub</strong></li><li><strong>Contributes to open-source projects</strong>.</li></ul><p><strong>Types of Azure Pipelines</strong>:</p><ul><li>Classic editor</li><li>Using <strong>YAML</strong> syntax</li></ul><p><strong>What do I need to use Azure Pipelines?</strong></p><blockquote><strong><em>Azure Account</em></strong><em> — Azure DevOps registration is possible with either a Microsoft or GitHub account.</em></blockquote><p><strong>Sign up with a Microsoft account</strong> –<br> — If you don’t have one, <a href="https://azure.microsoft.com/services/devops/">create a Microsoft account now</a>.<br> — Go to <a href="https://azure.microsoft.com/services/devops/">Azure DevOps</a> and select <strong>Start Free</strong>.<br> — Enter your login information and complete the sign-up procedure.</p><blockquote><strong><em>Environment</em></strong><em> — An environment is a set of resources that can be targeted with pipeline deployments. Dev, Test, QA, Staging, and Production are common environment names. An Azure DevOps environment is a logical destination for your pipeline’s software deployment.</em></blockquote><p><strong>How to create Environment in Azure DevOps</strong> –<br><strong>Step 1</strong> — Go to the Pipeline Tab from the left navigation and click on it. After this, a new popup window will appear. That will ask you for the environment name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WXILmdT3beILZ43C.png" /></figure><p><strong>Step 2</strong>– Enter the desired environment name, like Dev, QA, Stage, and Prod. Describe the description of the environment in the Description field. And then select the resource you want based on your requirements. Here, I do not want to use Kubernetes or a virtual machine, so i will select the first option, None. Later, if you would like to associate another resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*apTKm5f9BQEJ1T1t.png" /></figure><p><strong>Step 3</strong> — Here you go to see list of environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*NpGcQU-_jK-gY8nb.png" /></figure><blockquote><strong><em>Organization</em></strong><em> — When you join an organization, you have access to Azure DevOps Services, where you can perform the following tasks: Use our cloud service to collaborate with others on application development. Plan and track your work, as well as code for bugs and issues. Install and configure continuous integration and deployment.</em></blockquote><p><strong>How to create new organization in Azure DevOps</strong> –<br><strong>Step 1</strong> — Click on the Azure DevOps logo and then click on the New Organization link that is placed in the left navigation. Once you click on it, it will ask for further details to provide the organization name, where you want to host, and a security-based captcha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*VLN_d3ZSA4qUY85w.png" /></figure><p><strong>Step 2</strong> — Here you can select the type of project, like public or private. Here I am with a private organization. After clicking on Create Project, it will ask you to accept privacy statements to continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/0*ZbEabs27LEfRIQgn.png" /></figure><p><strong>Step 3</strong> — After finishing setup, you can click on the Azure DevOps logo, or You can see all organizations in the left-side navigation. These organizations would be associated with the user based on permission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*1t-yaNSuvXMN8HBQ.png" /></figure><blockquote><strong><em>Subscription</em></strong><em> — In Azure, a subscription is a container that stores a set of related business or technical resources. The resources are used and billed collectively. An Azure account can have many subscriptions with different access management policies and invoicing procedures.</em></blockquote><p><a href="https://learn.microsoft.com/en-us/azure/cost-management-billing/manage/create-subscription"><strong>Make a subscription to the Microsoft Customer Agreement</strong></a></p><blockquote><strong><em>Service connection</em></strong><em> — Azure DevOps Pipelines leverage Service Connections to connect to external services such as Azure, GitHub, Docker, Kubernetes, and many others.</em></blockquote><p>Choose <strong>Project Settings</strong> from the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*MoyLryBMQBb0Xcr1.png" /></figure><p>Choose <strong>Service Connection</strong> from the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/0*n8ayj2cF1DmP5ueS.png" /></figure><p>If there won’t be any service connection yet, a message will inform you. To start creating a new service connection, click <strong>Create Service Connection</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oAXkwJsbdkHsfxvZ.png" /></figure><p>Once you click on it, you need to provide further details that will show as popup window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*afvZaZ9WUeLwYh-J.png" /></figure><p>After creation service connection it will show you list of service connection under service connection tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hLKhPoDG5JflRRMe.png" /></figure><blockquote><strong><em>Version control system</em></strong><em> — Azure Pipelines requires you to have your source code in a version control system. Git and Azure Repos are the two types of versions control that Azure DevOps supports. Any changes you make to your version control repository are created and evaluated automatically.</em></blockquote><p><strong>How to create new repos in Azure DevOps</strong> –</p><p><strong>Step 1</strong> — Select the project where you wish to build the repository after logging in. Skip this step if you are already working on the project.</p><p>There is normally a navigation menu on the left side of the project dashboard. To access the repositories area, click “Repos” or “Code”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*RXeIVOFsnbp6hF0F.png" /></figure><p>There should be a button to start a new repository once you’re in the Repos area. This is typically denoted by the word “Create” or a plus sign (+). To begin the creation process, click on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*pXcT1iwk18Qe9owh.png" /></figure><p>Different repository types, including Git and TFVC (Team Foundation Version Control), are available with Azure DevOps. Choose “Git” because it is a well-liked and often used distributed version control system.</p><p>For the repository, you must provide the following configuration information:</p><p>– <strong>Repository Name</strong>: Give your repository a memorable name.<br>– Provide a <strong>description</strong> to clarify the repository’s purpose, if you choose.<br>– Choose between <strong>public visibility</strong> (everyone can see it) and private visibility (only authorized users can see it).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*baRQhnBZLOiHWzor.png" /></figure><ul><li>You have the option to include a README file when starting the repository. This is useful for giving the project’s overview information.</li><li>Another option is a .gitignore template. This makes it easier to keep some files and directories out of version control.</li><li>Choose a license template if your project is open source. This makes it easier to determine how your project will be licensed.</li><li>After you’ve entered all the essential information, click “Create” to start building the repository.</li></ul><p>Your repository will be generated in a brief period. The main page of the repository, where you can manage your code, branches, pull requests, and more, will be displayed. You must clone the repository in order to begin using it on your home computer. Copy the repository URL after clicking the “Clone” button. And you can see your repos in repos list.</p><pre>git clone &lt;repo path&gt;</pre><p>If you have already setup or configured the required elements, then you can skip that, and once you have finished all these steps, we will write our pipeline code using YAML syntax into our source code.</p><pre># Starter pipeline<br># Start with a minimal pipeline that you can customize to build and deploy your code.<br># Add steps that build, run tests, deploy, and more:<br># https://aka.ms/yaml<br><br>trigger:<br>  - main #branch name<br><br>pool:<br>  vmImage: &quot;windows-2022&quot; #image where you want to deploy.<br><br>stages: <br>- stage: Build<br>  jobs:<br>  - job: Build<br>    displayName: &quot;Install npm packages and Build&quot;<br>    workspace:<br>      clean: all<br>    steps:<br>      - checkout: self<br>        submodules: true<br>      - task: NodeTool@0<br>        inputs:<br>          versionSpec: &#39;14.x&#39;<br>          checkLatest: true<br>        displayName: &#39;Install Node.js&#39;<br><br>      - script: |<br>          npm install<br>        displayName: &#39;Install dependencies&#39;<br>      <br>      - script: |<br>          npm run build<br>        displayName: &#39;Build&#39;<br><br>      - task: CopyFiles@2<br>        inputs:<br>          SourceFolder: &#39;$(System.DefaultWorkingDirectory)/build&#39;<br>          Contents: &#39;**&#39;<br>          TargetFolder: &#39;$(Build.ArtifactStagingDirectory)&#39;<br>          OverWrite: true<br>        displayName: &#39;Copy build files to artifacts&#39;<br><br>      - task: PublishBuildArtifacts@1<br>        inputs:<br>          PathtoPublish: &#39;$(Build.ArtifactStagingDirectory)&#39;<br>          ArtifactName: &#39;drop&#39;<br>          publishLocation: &#39;Container&#39;<br>        displayName: &#39;Publish Artifact&#39;<br><br>- stage: Deploy<br>  jobs:<br>    - job: Deploy<br>      displayName: Deploying<br>      steps:<br>      - task: DownloadPipelineArtifact@2<br>        inputs:<br>          source: &#39;current&#39;<br>          artifact: &#39;drop&#39;<br>          path: &#39;$(Pipeline.Workspace)&#39;<br><br>      - task: AzureRmWebAppDeployment@4<br>        inputs:<br>          ConnectionType: &#39;AzureRM&#39; #Connection type<br>          azureSubscription: &#39;&lt;your_azure_subscription&gt;&#39;<br>          appType: &#39;webApp&#39;  #Required when ConnectionType = AzureRM. App Service type<br>          WebAppName: &#39;&lt;your_web_app_name&gt;&#39; #&lt;App Service Name.&gt;<br>          packageForLinux: &#39;$(Pipeline.Workspace)&#39;</pre><pre>git add &lt;files&gt;<br>git commit -m &quot;your message here&quot;<br>git push</pre><p>After pushing your code, you need to create the first pipeline in the pipeline section that will come from the left-side navigation of the Azure dashboard.</p><p><strong>How to create or configure Azure Pipeline</strong>: –</p><p><strong>Step 1 </strong>— Choose Pipelines from the dashboard, then click Builds. There won’t be any build pipelines yet, a message will inform you. To start building the pipeline, click <strong>create pipeline</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yq0cUGPPaxoO4jFJ.png" /></figure><p><strong>Step 2</strong> — You will then be asked to specify the location of your code. The code for this project is kept in a GitHub repository. Decide on GitHub. The triggers for calling the build will originate from this location, where code is also kept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p><strong>Step 3</strong> — After selecting repos, you will get new screen to choose pipeline template. Here we are going to select option. If you want to write from scratch, then you can select .Existing Azure Pipeline YAML fileStarter Pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p><strong>Step 4</strong> — If you would select then it will ask for new values from another popup window. Like you need to provide name and the of YAML file. And click on continue.Existing Azure Pipeline YAML filethe path</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p><strong>Step 5</strong> — In the final step you will do review your pipeline what you are going to run, and here are few other options such as variables. If you want to make it input parameter, you can add or set variables. And last, you can either save or run your pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j82vUf1V1mPjy_-Q.png" /></figure><p>When you run your pipeline for the first time, a permission request to authorize your service connection will be made. Once you permit it to execute, your first pipeline will begin to function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v2cAecDejhrAJQzk.png" /></figure><p>Your pipeline will appear in the pipeline tab once it has successfully run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kwoB2Ex3ls5yCqK0.png" /></figure><p><strong>Examining resources from deployed Azure WebApps.</strong></p><p>Check out the results of your labour now that the procedure is finished.</p><p>Enter the <a href="https://portal.azure.com/">Azure Portal</a>, find the Azure <strong>App Service</strong> you chose as the target in the release process, and copy the URL as displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4EYKolfa2t0YWkY_.png" /></figure><p><strong>Please share this blog with your friends and coworkers if you like it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=308bb6b898d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trabalhando com filtros dinâmicos utilizando o Gridify no .NET]]></title>
            <link>https://medium.com/@vitorgithub/trabalhando-com-filtros-din%C3%A2micos-utilizando-o-gridify-no-net-6a3a03100a73?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a3a03100a73</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 14:51:16 GMT</pubDate>
            <atom:updated>2023-10-09T14:51:16.669Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trabalhando com filtros dinâmicos utilizando o Gridify no .NET</h3><p>Neste artigo vou apresentar uma forma simples, fácil e dinâmica de configurar filtros nos <em>endpoints </em>de <em>APIs </em>utilizando o .NET.</p><p>O <a href="https://alirezanet.github.io/Gridify/">Gridify</a> é uma biblioteca pouco conhecida, mas de grande utilidade. Criado pelo <a href="https://github.com/alirezanet">Alireza Sabouri</a>, ela tem o objetivo de facilitar a vida do desenvolvedor que precisa criar vários <em>endpoints </em>de filtragens, como por exemplo: <em>GetById</em>, <em>GetByName</em>, <em>GetByDate</em>. Com o Gridify é possível ter apenas um <em>endpoint </em>de filtragem para cada tipo de entidade.</p><p><strong>Pré-requisitos</strong></p><ul><li>.NET 7.0</li><li>Visual Studio 2022</li><li>Nuget package <a href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore"><em>Entity Framework Core</em></a><em>, </em><a href="https://www.nuget.org/packages/Gridify/"><em>Gridify</em></a></li></ul><p><strong>Web API</strong></p><p>Na classe <em>program.cs</em> da API, configure conforme o código abaixo:</p><pre>using Microsoft.EntityFrameworkCore;<br>using Sample.Gridify.Core.Context;<br>using Sample.Gridify.Core.Extensions;<br><br>var builder = WebApplication.CreateBuilder(args);<br>builder.AddSerilog();<br><br>builder.Services.AddRouting(options =&gt; options.LowercaseUrls = true);<br>builder.Services.AddControllers();<br>builder.Services.AddDbContext&lt;BookContext&gt;(opt =&gt; opt.UseInMemoryDatabase(&quot;BookContext&quot;));<br><br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>var app = builder.Build();<br><br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.MapControllers();<br><br>app.Run();</pre><p>O próximo passo é criar o contexto (<strong><em>BookContext)</em></strong>. Neste exemplo, utilizaremos o Entity Framework <em>InMemory </em>para persistir e consultar as informações com o Gridify:</p><pre><br>namespace Sample.Gridify.Core.Context;<br><br>public class BookContext : DbContext<br>{<br>    protected BookContext(DbContextOptions options) <br>        : base(options) { }<br><br>    public BookContext(DbContextOptions&lt;BookContext&gt; options) <br>        : this((DbContextOptions)options)<br>    {<br>    }<br><br>    public DbSet&lt;Book&gt; Books { get; set; }<br>}<br><br>public class Book<br>{<br>    public Guid BookId { get; set; } = Guid.NewGuid();<br>    public string Title { get; set; }<br>    public DateTime Date { get; set; }<br>}</pre><p>Em seguida, crie uma controller com o nome de <em>GridifyController </em>e insira o código abaixo para testes:</p><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class GridifyController : ControllerBase<br>{<br>    private readonly BookContext _context;<br><br>    public GridifyController(BookContext context)<br>    {<br>        _context = context;<br>    }<br><br>    [HttpGet(&quot;books&quot;)]<br>    public IActionResult GetBooks([FromQuery]GridifyQuery model)<br>    {<br>        if (!_context.Books.Any())<br>        {<br>            _context.Books.AddRange(SeedsExtensions.ReturnBooks());<br>            _context.SaveChanges();<br>        }<br><br>        var result = _context.Books.GridifyQueryable(model);<br><br>        return Ok(result);<br>    }<br>}</pre><p>O <strong><em>GridifyQuery </em></strong>é uma classe simples para configurar filtros, ordenação e paginação, já o método <strong><em>GridifyQueryable</em></strong> aplica esses filtros na entidade <em>Books</em>.</p><p><strong>Testando</strong></p><p>Para realizar os testes, execute o <em>endpoint </em><strong><em>GET /gridify/books </em></strong>no <em>Swagger</em> passando os parâmetros do filtro a serem realizados no banco pelo Gridify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*4a_2uFjdd4OAhZyb" /></figure><p>Como teste, pesquisei pelo título <em>“Programming Pearls”</em> e trouxe um registro, caso não existisse este título, seria retornado uma lista vazia, e caso não existisse a propriedade <em>“title”</em> no contexto, seria retornado um erro informando que esta coluna não existe no banco.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*_s0M6NgM7O6Fazk7" /></figure><p>Por questões de segurança, também é possível utilizar o <a href="https://henriquemauri.net/mapeando-objetos-com-o-automapper-no-net"><em>Automapper</em></a><em> </em>para realização de mapeamentos entre a <em>ViewModel </em>e Entidade, assim o usuário final não precisa ter o conhecimento dos nomes das colunas no banco de dados.</p><p>Para mais detalhes e melhores práticas de utilização, sugiro seguir a documentação: <a href="https://alirezanet.github.io/Gridify/guide/">https://alirezanet.github.io/Gridify/guide</a></p><p><strong>Finalizando</strong></p><p>O Gridify é uma ferramenta extremamente útil para o desenvolvedor, evitando que sejam criados vários métodos de filtragens, praticando a reutilização de códigos.</p><p>A utilização deste <em>package </em>é muito simples, e ainda há a possibilidade de utilizar de forma detalhada com o <a href="https://alirezanet.github.io/Gridify/guide/queryBuilder.html">QueryBuilder</a>, deixando você ainda mais no controle.</p><p>Os detalhes completo deste exemplo você encontra no <a href="https://github.com/hgmauri"><strong>GitHub</strong></a><strong> dele</strong>: <a href="https://github.com/hgmauri/sample-gridify">https://github.com/hgmauri/sample-gridify</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a3a03100a73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Otimizando o desempenho com o Output Caching no .NET 7]]></title>
            <link>https://medium.com/@vitorgithub/otimizando-o-desempenho-com-o-output-caching-no-net-7-70b373e0090f?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b373e0090f</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 14:49:14 GMT</pubDate>
            <atom:updated>2023-10-09T14:49:14.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Otimizando o desempenho com o Output Caching no .NET 7</h3><p>Existem vários recursos que chamaram minha atenção no .NET 7 e decidi experimentar o <a href="https://learn.microsoft.com/en-us/aspnet/core/performance/caching/output"><em>Output Caching</em></a>.</p><p>O <em>Output Caching</em> é um <a href="https://learn.microsoft.com/pt-br/aspnet/core/fundamentals/middleware"><em>middleware</em></a><em> </em>que armazena em cache toda a saída de um <em>request</em>, em vez de executar o <em>request </em>por completo sempre que solicitado. Isso torna seus <em>endpoints </em>muito mais performáticos.</p><p>Este <em>middleware </em>melhora o desempenho reduzindo a carga em uma <em>API</em>. Ele também pode acelerar as experiências do usuário, pois os dados podem ser fornecidos a partir da memória ou de um cache centralizado, em vez de ter que fazer viagens de ida e volta a um recurso como um banco de dados toda vez que uma <em>API </em>é solicitada.</p><p><strong>Pré-requisitos</strong></p><ul><li>.NET 7.0</li><li>Visual Studio 2022</li></ul><p><strong>Web API</strong></p><p>O primeiro passo é configurar o recurso <em>Output Caching </em>conforme a classe<strong> <em>program.cs</em></strong> abaixo:</p><pre>using Sample.OutputCaching.WebApi.Extensions;<br><br>var builder = WebApplication.CreateBuilder(args);<br>builder.AddSerilog();<br><br>builder.Services.AddRouting(options =&gt; options.LowercaseUrls = true);<br>builder.Services.AddControllers();<br><br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>builder.Services.AddOutputCache(options =&gt;<br>{<br>    options.DefaultExpirationTimeSpan = TimeSpan.FromSeconds(20);<br>});<br><br>var app = builder.Build();<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseOutputCache();<br>app.MapControllers();<br><br>app.Run();</pre><p>Os métodos <strong><em>AddOutputCache()</em></strong> e <strong><em>UseOutputCache()</em></strong> são responsáveis por configurar o <em>middleware </em>de cache na aplicação.</p><p>O método de extensão <em>AddSerilog()</em> contém a configuração de <em>logs </em>da aplicação:</p><pre>public static class SerilogExtension<br>{<br>    public static WebApplicationBuilder AddSerilog(this WebApplicationBuilder builder)<br>    {<br>        Log.Logger = new LoggerConfiguration()<br>            .MinimumLevel.Override(&quot;Microsoft.AspNetCore&quot;, LogEventLevel.Information)<br>            .Enrich.FromLogContext()<br>            .Enrich.WithExceptionDetails()<br>            .Enrich.WithProperty(&quot;ApplicationName&quot;, &quot;API Output Caching&quot;)<br>            .Filter.ByExcluding(Matching.FromSource(&quot;Microsoft.AspNetCore.Hosting.Diagnostics&quot;))<br>            .WriteTo.Console(outputTemplate: &quot;[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}&quot;)<br>            .CreateLogger();<br><br>        builder.Logging.ClearProviders();<br>        builder.Host.UseSerilog(Log.Logger, true);<br><br>        return builder;<br>    }<br>}</pre><p>Para habilitar o cache é necessário utilizar o atributo <strong>[OutputCache]</strong>, conforme o <em>endpoint</em> <strong><em>GetCountries()</em></strong> da <em>controller </em>de exemplo (<em>CacheController</em>) abaixo:</p><pre>namespace Sample.OutputCaching.WebApi.Controllers;<br><br>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class CacheController : ControllerBase<br>{<br>    private static readonly string[] Countries =<br>    {<br>        &quot;Argentina&quot;, &quot;Australia&quot;, &quot;Brazil&quot;, &quot;Colombia&quot;, &quot;Egypt&quot;, &quot;Italy&quot;, &quot;Mexico&quot;, &quot;Russia&quot;, &quot;Ukraine&quot;, &quot;Uruguay&quot;<br>    };<br><br>    [HttpGet(&quot;countries&quot;)]<br>    [OutputCache]<br>    public IActionResult GetCountries()<br>    {<br>        var result = new<br>        {<br>            Date = DateTime.Now,<br>            Countries<br>        };<br><br>        return Ok(result);<br>    }<br>}</pre><p>Ao registrar o atributo <em>OutputCache</em>, o <em>endpoint </em>passa a utilizar as configurações registradas na classe <em>program.cs</em>, neste caso, o cache terá a duração de 20 segundos.</p><p><strong>Testando</strong></p><p>Para realizar os testes, execute o <em>endpoint </em><strong><em>GET /cache/countries </em></strong>no <em>Swagger</em> para obter a lista de países.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*xRvE6d9ZSt1hdvFp" /></figure><p>Através dos <em>logs </em>gerados no console, é possível entender que na primeira requisição ao <em>endpoint</em> foi executado normalmente, e nas próximas requisições para o mesmo <em>endpoint</em>, o resultado foi retornado pelo cache feito no servidor, conforme a imagem abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*olkigv_oul4tsxpE" /></figure><p><strong>Finalizando</strong></p><p>Observando a <em>API </em>no exemplo, vimos que quase não requer código para usar o <em>middleware </em>de cache, embora seja flexível para ser configurada de acordo com suas próprias necessidades.</p><p>Este foi um caso de uso básico de utilização do <em>Output Caching</em>, existem diversos cenários em que é possível aproveitar este <em>middleware</em> para obter performance e escalabilidade das aplicações.</p><p>Os detalhes completo deste exemplo você encontra no <a href="https://github.com/hgmauri"><strong>GitHub</strong></a><strong> dele</strong>: <a href="https://github.com/hgmauri/sample-output-caching">https://github.com/hgmauri/sample-output-caching</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b373e0090f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tratamento global de erros no .NET 6.0]]></title>
            <link>https://medium.com/@vitorgithub/tratamento-global-de-erros-no-net-6-0-00dbced71548?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/00dbced71548</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 14:47:42 GMT</pubDate>
            <atom:updated>2023-10-09T14:47:42.813Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tratamento global de erros no .NET 6.0</h3><p>Esta é uma postagem rápida sobre como implementar um manipulador de exceção global no .NET 6.0.</p><p>Um manipulador de erros global é utilizado para capturar todos os <em>exceptions </em>e remover a necessidade de criar vários códigos de tratamento em toda aplicação .NET.</p><p>Neste exemplo utilizaremos o <a href="https://docs.microsoft.com/pt-br/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0"><em>middleware</em></a><em> </em>e <em>Serilog </em>para centralizar as configurações de captura e destino da coleta de logs.</p><p><strong>Pré-requisitos</strong></p><ul><li>Visual Studio 2022 (.NET 6.0)</li><li>Nuget package <a href="https://www.nuget.org/packages/Serilog.AspNetCore/"><em>Serilog.AspNetCore</em></a>, <a href="https://www.nuget.org/packages/Serilog.Enrichers.Environment/">Serilog.Enrichers.Environment</a> e <a href="https://www.nuget.org/packages/Serilog.Exceptions/"><em>Serilog.Exceptions</em></a></li></ul><p><strong>Middleware</strong></p><p>Os <em>middlewares </em>basicamente são componentes que <strong>definem o pipeline de execução das chamadas HTTP</strong>, ou seja, todos os passos que uma solicitação faz dentro da aplicação desde a sua <em>request </em>até o <em>response</em>. Eles são encadeados, então, um middleware pode executar outro através de <em>delegates </em>repassando o mesmo contexto da requisição.</p><p>O primeiro <em>middleware</em> necessário criar é o <em>ErrorHandlingMiddleware</em>, responsável por capturar todos os erros (sem tratamento) da aplicação:</p><pre><br>public class ErrorHandlingMiddleware<br>{<br>    private readonly RequestDelegate next;<br><br>    public ErrorHandlingMiddleware(RequestDelegate next)<br>    {<br>        this.next = next;<br>    }<br><br>    public async Task Invoke(HttpContext context)<br>    {<br>        try<br>        {<br>            await next(context);<br>        }<br>        catch (Exception ex)<br>        {<br>            await HandleExceptionAsync(context, ex);<br>        }<br>    }<br><br>    private static Task HandleExceptionAsync(HttpContext context, Exception exception)<br>    {<br>        Log.Error(exception, &quot;Erro na aplicação&quot;);<br><br>        var code = HttpStatusCode.InternalServerError;<br><br>        if (exception is Exception) code = HttpStatusCode.BadRequest;<br>        // else if (exception is MyUnauthorizedException) code = HttpStatusCode.Unauthorized;<br>        // else if (exception is MyException)             code = HttpStatusCode.BadRequest;<br><br>        var result = JsonConvert.SerializeObject(new { error = exception.Message });<br><br>        context.Response.ContentType = &quot;application/json&quot;;<br>        context.Response.StatusCode = (int)code;<br>        return context.Response.WriteAsync(result);<br>    }<br>}</pre><p>O segundo <em>middleware </em>(<em>RequestSerilLogMiddleware</em>) será utilizado para capturar informações adicionais, como por exemplo: e-mail do usuário credenciado, IP do usuário e informações do <em>header</em>.</p><pre>public class RequestSerilLogMiddleware<br>{<br>    private readonly RequestDelegate _next;<br><br>    public RequestSerilLogMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br><br>    public Task Invoke(HttpContext context)<br>    {<br>        using (LogContext.PushProperty(&quot;UserName&quot;, context?.User?.Identity?.Name ?? &quot;anônimo&quot;))<br>        using (LogContext.PushProperty(&quot;CorrelationId&quot;, GetCorrelationId(context)))<br>        {<br>            return _next.Invoke(context);<br>        }<br>    }<br>}</pre><p>Em seguida, é necessário configurar o Serilog, informando os principais <em>enrich</em> para adicionar mais informações no registro do log:</p><pre>public static class SerilogExtensions<br>{<br>    public static void AddSerilogApi(IConfiguration configuration)<br>    {<br>        Log.Logger = new LoggerConfiguration()<br>            .ReadFrom.Configuration(configuration)<br>            .Enrich.WithProperty(&quot;ApplicationName&quot;, $&quot;API Exceptions - {Environment.GetEnvironmentVariable(&quot;DOTNET_ENVIRONMENT&quot;)}&quot;)<br>            .Enrich.FromLogContext()<br>            .Enrich.WithMachineName()<br>            .Enrich.WithEnvironmentUserName()<br>            .Enrich.WithExceptionDetails()<br>            .WriteTo.Console()<br>            .WriteTo.Console(outputTemplate: &quot;[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}&quot;)<br>            .CreateLogger();<br>    }<br>}</pre><p>E por fim, na classe <em>program.cs</em>, é necessário registrar a utilização dos dois middlewares criados:</p><pre>var builder = WebApplication.CreateBuilder(args);<br>SerilogExtensions.AddSerilogApi(builder.Configuration);<br>builder.Host.UseSerilog(Log.Logger);<br><br>builder.Services.AddRouting(options =&gt; options.LowercaseUrls = true);<br>builder.Services.AddSwaggerApi(builder.Configuration);<br>builder.Services.AddControllers();<br><br>var app = builder.Build();<br><br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseDeveloperExceptionPage();<br>}<br><br>app.UseMiddleware&lt;RequestSerilLogMiddleware&gt;();<br>app.UseMiddleware&lt;ErrorHandlingMiddleware&gt;();<br><br>app.UseSwaggerDocApi();<br><br>app.UseHttpsRedirection();<br>app.UseRouting();<br>app.MapControllers();<br><br>app.Run();</pre><p><strong>Testando</strong></p><p>Ao executar a API, é possível testar a coleta de erros chamando o <em>endpoint </em><strong>/api/log/exception</strong>, que lança um erro no <em>controller </em>da aplicação e é capturado pelo <em>middleware ErrorHandlingMiddleware</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*z4k5hLxqn0mQE8ic" /></figure><p><strong>Finalizando</strong></p><p>A captura de exceções é uma parte crucial em todas as aplicações e a utilização de <em>middleware </em>é o modo mais seguro da sua aplicação não “desarmar” por falta de tratamento de erros, além de ser um local centralizado para coletar logs, personalizar mensagens de retorno e obter informações do usuário credencial.</p><p>Os detalhes completos deste exemplo você encontra no GitHub dele: <a href="https://github.com/hgmauri/exceptions-handler">https://github.com/hgmauri/exceptions-handler</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00dbced71548" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RabbitMQ com MassTransit no .NET 6]]></title>
            <link>https://medium.com/@vitorgithub/rabbitmq-com-masstransit-no-net-6-6833aab70a13?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6833aab70a13</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 14:45:55 GMT</pubDate>
            <atom:updated>2023-10-09T14:45:55.506Z</atom:updated>
            <content:encoded><![CDATA[<h3>RabbitMQ com MassTransit no .NET 6</h3><p>MassTransit é um framework fantástico para comunicação assíncrona em aplicações distribuídas, tanto que a própria <a href="https://masstransit-project.com/">documentação</a><a href="https://masstransit-project.com/"> </a>cita:</p><blockquote>MassTransit é uma estrutura de aplicação distribuída de código aberto para .NET que facilita a criação de aplicações e serviços que potencializam a comunicação assíncrona, baseada em mensagens e fracamente acoplada para maior disponibilidade, confiabilidade e escalabilidade.</blockquote><p><strong>Vantagens do MassTransit</strong></p><ul><li>Código aberto e gratuito</li><li>Fácil de configurar e utilizar</li><li>Contém muitos padrões de mensagem de <em>microservices </em>(<em>Retry</em>, <em>circuit braker</em>)</li><li>Tratamento de exceções integrado</li><li>Transação distribuída (Saga, <em>event-drive</em>, roteamento)</li><li>Agendamento de mensagens</li><li>Monitoramento</li></ul><p>A facilidade e a resiliência que o MassTransit nos oferece é absolutamente tudo o que precisamos saber.</p><p>Neste artigo, mas uma vez vamos direto ao ponto: Configurar uma API no .NET 6.0 com o cenário de envio de mensagens <em>(publish)</em> para um <em>Worker Service</em> que recebe <em>(subscribe)</em> e processa essas mensagens utilizando o MassTransit.</p><p><strong>Pré-requisitos</strong></p><ul><li>Visual Studio 2022 (.NET 6.0)</li><li>Docker Compose com RabbitMQ</li><li>Nuget package <a href="https://www.nuget.org/packages/MassTransit.AspNetCore/"><em>MassTransit.AspNetCore</em></a> e <a href="https://www.nuget.org/packages/MassTransit.RabbitMQ/"><em>MassTransit.RabbitMQ</em></a></li></ul><p><strong>API</strong></p><p>O primeiro passo é configurar o <em>docker-compose </em>com a imagem do RabbitMQ (que é um dos <em>message broker</em> de código aberto mais populares). Basicamente, ele oferece à suas aplicações uma plataforma comum para enviar e receber mensagens, garantindo que os dados nunca sejam perdidos e recebidos com êxito pelos consumidores, além de oferecer suporte a vários protocolos de mensagens.</p><pre>version: &quot;3.8&quot;<br>services:</pre><pre>rabbitmq:<br>    image: masstransit/rabbitmq<br>    ports:<br>      - 5672:5672<br>      - 15672:15672</pre><p>Caso não queira utilizar o Docker, é possível utilizar o RabbitMQ em uma conta gratuita no <a href="https://www.cloudamqp.com/">CloudAMQP</a>.</p><p>Em seguida é preciso configurar a classe <em>Program </em>da API:</p><pre>using MassTransit;<br>using Microsoft.AspNetCore.Builder;<br>using Microsoft.Extensions.Configuration;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddControllers();<br>builder.Services.AddSwaggerGen(c =&gt;<br>{<br>    c.SwaggerDoc(&quot;v1&quot;, new() { Title = &quot;Sample.Masstransit.WebApi&quot;, Version = &quot;v1&quot; });<br>});<br><br>builder.Services.AddMassTransit(bus =&gt;<br>{<br>    bus.UsingRabbitMq((ctx, busConfigurator) =&gt;<br>    {<br>        busConfigurator.Host(builder.Configuration.GetConnectionString(&quot;RabbitMq&quot;));<br>    });<br>});<br>builder.Services.AddMassTransitHostedService();<br><br>var app = builder.Build();<br><br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;Sample.Masstransit.WebApi v1&quot;));<br>}<br><br>app.UseHttpsRedirection();<br><br>app.UseAuthorization();<br><br>app.MapControllers();<br><br>app.Run();</pre><p>Neste código temos a extensão <em>AddMassTransit </em>responsável por registrar o <em>service bus</em> do RabbitMQ, que está configurado no <em>appsettings.json</em>:</p><pre>  &quot;ConnectionStrings&quot;: {<br>    &quot;RabbitMq&quot;: &quot;amqp://guest:guest@localhost:5672&quot;<br>  }</pre><pre>Em seguida, precisamos configurar o envio de mensagens na ClientController:</pre><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class ClientController : ControllerBase<br>{<br>    private readonly IPublishEndpoint _publisher;<br>    private readonly ILogger&lt;ClientController&gt; _logger;<br><br>    public ClientController(ILogger&lt;ClientController&gt; logger, IPublishEndpoint publisher)<br>    {<br>        _logger = logger;<br>        _publisher = publisher;<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; Post([FromBody] ClientModel model)<br>    {<br>        await _publisher.Publish&lt;ClientModel&gt;(model);<br>        _logger.LogInformation($&quot;Send {nameof(ClientModel)}&quot;);<br><br>        return Ok();<br>    }<br>}</pre><p>O <em>IPublishEndpoint </em>é a interface genérica responsável pelo envio de mensagens. Independente do provedor escolhido (In Memory, RabbitMQ, Azure Service Bus, etc).</p><p><strong>Worker Service</strong></p><p>O <a href="https://docs.microsoft.com/en-us/dotnet/core/extensions/workers"><em>Worker Service</em></a><em> </em>trabalha como uma aplicação executada em segundo plano, responsável apenas por consumir e processar mensagens. Esse tipo de aplicação é uma ótima escolha em ambientes distribuídos / <em>microservices</em> por ser extremamente leve e carregando apenas o necessário, facilitando na escala.</p><p>O próximo passo é configurar a classe <em>Program </em>do <em>Worker Service</em>:</p><pre>using System;<br>using System.Threading;<br>using MassTransit;<br>using Microsoft.Extensions.Configuration;<br>using Microsoft.Extensions.Hosting;<br>using Sample.Masstransit.WebApi.Core.Extensions;<br>using Sample.Masstransit.Worker.Workers;<br><br>var configuration = new ConfigurationBuilder()<br>    .AddEnvironmentVariables()<br>    .AddCommandLine(args)<br>    .AddJsonFile(&quot;appsettings.json&quot;)<br>    .Build();<br><br>var host = Host.CreateDefaultBuilder(args)<br>    .ConfigureAppConfiguration(builder =&gt;<br>    {<br>        builder.Sources.Clear();<br>        builder.AddConfiguration(configuration);<br>    })<br>    .ConfigureServices((context, collection) =&gt;<br>    {<br>        collection.AddMassTransitExtension(context.Configuration);<br>    })<br>    .Build();<br><br>var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =&gt;<br>{<br>    cfg.ReceiveEndpoint(&quot;queue-teste&quot;, e =&gt;<br>    {<br>        e.PrefetchCount = 10;<br>        e.UseMessageRetry(p =&gt; p.Interval(3, 100));<br>        e.Consumer&lt;WorkerClient&gt;();<br>    });<br>});<br>var source = new CancellationTokenSource(TimeSpan.FromSeconds(10));<br>await busControl.StartAsync(source.Token);<br><br>Console.WriteLine(&quot;Waiting for new messages.&quot;);<br><br>while (true);</pre><p>A classe <em>Bus </em>(<em>Bus.Factory</em>) é responsável por configurar o consumo das mensagens do RabbitMQ, onde é necessário configurar o <em>ReceiveEndpoint </em>com o nome da <em>queue</em> (que pode ser qualquer nome, já que o envio e recebimento das mensagens pelo MassTransit é definido pelo nome do tipo de objeto, incluindo o <em>namespace</em>).</p><p>Outra configuração importante é o <em>UseMessageRetry</em> responsável pela resiliência nas tentativas em caso de erro. Neste exemplo foi configurado em 3 tentativas no intervalo de 100 milissegundos.</p><p>No código abaixo temos a definição do <em>Consumer</em>, chamado de <em>WorkerClient</em>:</p><pre><br>public class WorkerClient : IConsumer&lt;ClientModel&gt;<br>{<br>    public Task Consume(ConsumeContext&lt;ClientModel&gt; context)<br>    {<br>        var id = context.Message.ClientId;<br>        var name = context.Message.Name;<br><br>        Console.WriteLine($&quot;New client: [{id}] - {name}&quot;);<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>Tanto na <em>controller </em>como no <em>worker </em>é utilizado o mesmo objeto <em>(ClientModel)</em> para o envio e recebimento.</p><p><strong>Solução Completa</strong></p><p>No final, a solução fica com essa estrutura:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*1x2LVgCZvpWY-ebg" /></figure><ul><li><strong>Sample.Masstransit.WebAP</strong>I: API responsável pelo envio de mensagens.</li><li><strong>Sample.Masstransit.Worker: </strong><em>Worker Service</em> responsável pelo recebimento das mensagens.</li><li><strong>Sample.Masstransit.WebApi.Core: </strong>Abstrações genéricas utilizado pela API e <em>Worker</em></li></ul><p>Para realizar os testes é preciso configurar a solução com a inicialização simultânea do projeto <em>WebApi </em>e <em>Worker </em>e executar o comando <em>docker-compose</em> na pasta raiz do projeto:</p><pre>docker-compose up</pre><p>Testando a aplicação é possível ver o envio e recebimento de mensagens orquestrado MassTransit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*FVq9eg3uQCLAupW5" /></figure><p>Finalizando, o MassTransit é sem dúvida a melhor abstração na utilização de <em>message brokers</em>, podendo ser utilizado em vários cenários, como por exemplo, em migrações de aplicações legadas para novas arquiteturas, onde é necessário manter várias bases de dados atualizadas, sendo necessário o envio de mensagens para <em>topics </em>em um <a href="https://masstransit-project.com/usage/transports/rabbitmq.html#broker-topology"><em>bus</em></a> para a sincronização das bases.</p><p>Os detalhes completo sobre a implementação do MassTransit no .NET 6.0 você encontra no GitHub dele:<br><a href="https://github.com/hgmauri/sample-masstransit">https://github.com/hgmauri/sample-masstransit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6833aab70a13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agendando tarefas com o Cronos no .NET]]></title>
            <link>https://medium.com/@vitorgithub/agendando-tarefas-com-o-cronos-no-net-2aaf0774190d?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aaf0774190d</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 14:43:22 GMT</pubDate>
            <atom:updated>2023-10-09T14:43:22.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>Agendando tarefas com o Cronos no .NET</h3><p><a href="https://github.com/HangfireIO/Cronos">Cronos</a> é uma biblioteca de agendamento de tarefas para .NET que permite agendar e executar tarefas em horários ou intervalos específicos utilizando o padrão <a href="https://en.wikipedia.org/wiki/Cron">CRON</a>.</p><p>Neste artigo, apresentarei como configurar e utilizar o agendamento de tarefas em segundo plano em uma aplicação .NET 7.</p><p><strong>Pré-requisitos</strong></p><ul><li>.NET 7.0</li><li>Visual Studio 2022</li><li>Nuget package <a href="https://www.nuget.org/packages/Cronos"><em>Cronos</em></a></li></ul><p><strong>Web API</strong></p><p>Na classe<strong> <em>Program.cs</em></strong> da API, configure conforme o código abaixo:</p><pre>using Sample.Scheduler.Core.Extensions;<br>using Sample.Scheduler.Core.TimerSchedulers;<br><br>var builder = WebApplication.CreateBuilder(args);<br>builder.AddSerilog();<br><br>builder.Services.AddRouting(options =&gt; options.LowercaseUrls = true);<br>builder.Services.AddControllers();<br><br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>builder.Services.AddCronJob&lt;TimerSendEmail&gt;(c =&gt; c.CronExpression = @&quot;0 */1 * * * *&quot;);<br>builder.Services.AddCronJob&lt;TimerCheckDatabase&gt;(c =&gt; c.CronExpression = @&quot;* * * * * *&quot;);<br><br>var app = builder.Build();<br><br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.MapControllers();<br><br>app.Run();</pre><p>O próximo passo é criar a classe de extensão <strong><em>CronJobExtensions</em></strong>, responsável por controlar os próximos agendamentos de cada tarefa utilizando o <em>CronExpression</em>:</p><pre>public abstract class CronJobExtensions : BackgroundService<br>{<br>	private readonly CronExpression _expression;<br>	private readonly TimeZoneInfo _timeZoneInfo;<br>	private readonly IServiceProvider _serviceProvider;<br><br>	protected CronJobExtensions(string cronExpression, TimeZoneInfo timeZoneInfo, IServiceProvider serviceProvider)<br>	{<br>		_expression = CronExpression.Parse(cronExpression, CronFormat.IncludeSeconds);<br>		_timeZoneInfo = timeZoneInfo;<br>		_serviceProvider = serviceProvider;<br>	}<br><br>	protected override async Task ExecuteAsync(CancellationToken cancellationToken)<br>	{<br>		while (!cancellationToken.IsCancellationRequested)<br>		{<br>			var now = DateTimeOffset.Now;<br>			var next = _expression.GetNextOccurrence(now, _timeZoneInfo);<br>			if (!next.HasValue) continue;<br><br>			var delay = next.Value - now;<br>			await Task.Delay(delay, cancellationToken);<br><br>			if (cancellationToken.IsCancellationRequested) continue;<br><br>			try<br>			{<br>				using var scope = _serviceProvider.CreateScope();<br>				await DoWork(scope, cancellationToken);<br>			}<br>			catch (Exception ex)<br>			{<br>				Log.Error(ex, nameof(ExecuteAsync));<br>			}<br>		}<br>	}<br><br>	public abstract Task DoWork(IServiceScope scope, CancellationToken cancellationToken);<br>}<br><br>public interface IScheduleConfig&lt;T&gt;<br>{<br>	string CronExpression { get; set; }<br>	TimeZoneInfo TimeZoneInfo { get; set; }<br>}<br><br>public class ScheduleConfig&lt;T&gt; : IScheduleConfig&lt;T&gt;<br>{<br>	public string CronExpression { get; set; }<br>	public TimeZoneInfo TimeZoneInfo { get; set; } = TimeZoneInfo.Local;<br>}</pre><p>Na sequência, é necessário criar a classe de extensão <strong><em>ScheduledServiceExtensions</em></strong> responsável por registrar os agendamentos:</p><pre>public static class ScheduledServiceExtensions<br>{<br>	public static IServiceCollection AddCronJob&lt;T&gt;(this IServiceCollection services, Action&lt;IScheduleConfig&lt;T&gt;&gt; options) where T : CronJobExtensions<br>	{<br>		var config = new ScheduleConfig&lt;T&gt;();<br>		options.Invoke(config);<br><br>		services.AddSingleton&lt;IScheduleConfig&lt;T&gt;&gt;(config);<br><br>		services.AddHostedService&lt;T&gt;();<br><br>		return services;<br>	}<br>}</pre><p>E por fim, vamos criar a classe de agendamento das ações, neste exemplo criaremos um agendamento para ser disparado a cada segundo e outro para ser disparado a cada minuto. Esses dois agendamentos são registrados na classe <strong><em>Program.cs</em></strong></p><pre>public class TimerCheckDatabase : CronJobExtensions<br>{<br>	public TimerCheckDatabase(IScheduleConfig&lt;TimerCheckDatabase&gt; config, IServiceProvider serviceProvider)<br>		: base(config.CronExpression, config.TimeZoneInfo, serviceProvider)<br>	{<br>	}<br><br>	public override Task DoWork(IServiceScope scope, CancellationToken cancellationToken)<br>	{<br>		Serilog.Log.Information(&quot;Verified Database!&quot;);<br>		return Task.CompletedTask;<br>	}<br>}<br><br>public class TimerSendEmail : CronJobExtensions<br>{<br>	public TimerSendEmail(IScheduleConfig&lt;TimerSendEmail&gt; config, IServiceProvider serviceProvider)<br>		: base(config.CronExpression, config.TimeZoneInfo, serviceProvider)<br>	{<br>	}<br><br>	public override Task DoWork(IServiceScope scope, CancellationToken cancellationToken)<br>	{<br>		Serilog.Log.Information(&quot;Email sent!&quot;);<br>		return Task.CompletedTask;<br>	}<br>}</pre><p><strong>Testando</strong></p><p>Para testar os agendamentos, execute a API e analise os <em>logs </em>gerados pelo <a href="https://henriquemauri.net/coletando-logs-com-o-serilog-no-net-6/"><em>Serilog</em></a><em> </em>no <em>console </em>da aplicação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*hhemQNYsN8Whxf_-" /></figure><p>É possível analisar que o agendamento da tarefa que verifica o banco de dados é disparado a cada segundo, enquanto o agendamento que envia e-mail é disparado a cada minuto.</p><p><strong>Finalizando</strong></p><p>O <em>Cronos </em>é uma biblioteca para analisar expressões <em>Cron </em>e calcular as próximas ocorrências, com ele é possível agendar tarefas importantes em segundo plano, exemplos: Realizar manutenção no banco de dados toda madruga, capturar dados de uma origem de tempos em tempos, criação de alertas, etc.</p><p>Os detalhes completo deste exemplo você encontra no <a href="https://github.com/hgmauri"><strong>GitHub</strong></a><strong> dele</strong>: <a href="https://github.com/hgmauri/sample-task-scheduler">https://github.com/hgmauri/sample-task-scheduler</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aaf0774190d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Melhores pacotes NuGet para projetos .NET]]></title>
            <link>https://medium.com/@vitorgithub/melhores-pacotes-nuget-para-projetos-net-1fe01a6e8a0f?source=rss-c975e33a66e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe01a6e8a0f</guid>
            <dc:creator><![CDATA[Vitorgithub]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 14:41:00 GMT</pubDate>
            <atom:updated>2023-10-09T14:41:00.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>Melhores pacotes NuGet para projetos .NET</h3><p>O desenvolvimento de software é uma tarefa complexa e, como desenvolvedor, você não ganha nada em “reinventar a roda”. Acredito firmemente que devemos tornar sua vida o mais simples possível no desenvolvimento de aplicações, utilizando pacotes testados e aprovados sempre que possível, que ajudam em uma melhor experiência na codificação.</p><p>Abaixo estão alguns dos pacotes que utilizo na maioria dos meus projetos. Acredito que eles facilitam no desenvolvimento e tornam o código muito mais simples e organizado.</p><p><strong>1 — Serilog</strong></p><p><em>Log </em>é tudo o que você precisa para entender sua aplicação, sem ele é impossível compreender seu comportamento, identificar gargalos, alertas e erros, por isso coloquei o Serilog como o primeiro da lista.</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/serilog">https://www.nuget.org/packages/serilog</a></li><li><strong>Projeto</strong>: <a href="https://github.com/serilog/serilog">https://github.com/serilog/serilog</a></li><li><strong>Dicas</strong>: <a href="https://benfoster.io/blog/serilog-best-practices">https://benfoster.io/blog/serilog-best-practices</a></li></ul><p><strong>2 — Polly</strong></p><p>Polly é uma biblioteca .NET de resiliência de conexões e tratamento de <em>exceptions</em>, permitindo configurar políticas de <em>retry</em>, <em>circuit break</em>er e <em>timeout</em> de maneira simples. É possível utilizar o Polly como resiliência em qualquer dependência externa da sua sua aplicação.</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/Polly">https://www.nuget.org/packages/Polly</a></li><li><strong>Projeto</strong>: <a href="https://github.com/App-vNext/Polly">https://github.com/App-vNext/Polly</a></li><li><strong>Dicas</strong>: <a href="https://anthonygiretti.com/2019/03/26/best-practices-with-httpclient-and-retry-policies-with-polly-in-net-core-2-part-1">https://anthonygiretti.com/2019/03/26/best-practices-with-httpclient-and-retry-policies-with-polly-in-net-core-2-part-1</a></li></ul><p><strong>3 — FluentValidation</strong></p><p>Fluent Validation<strong> </strong>é uma biblioteca para realizar validação de classes utilizadas como <em>View Models, Commands</em> (conceito de <em>CQRS</em>), <em>DTOs </em>(objetos de transferência de dados), ou entidades de domínio, com o objetivo de realizar a implementação de regras de validação de forma simples e rápida (<a href="https://en.wikipedia.org/wiki/Fail-fast"><em>Fail-fast</em></a>).</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/FluentValidation">https://www.nuget.org/packages/FluentValidation</a></li><li><strong>Projeto</strong>: <a href="https://github.com/FluentValidation/FluentValidation">https://github.com/FluentValidation/FluentValidation</a></li><li><strong>Dicas</strong>: <a href="https://docs.fluentvalidation.net/en/latest/aspnet.html">https://docs.fluentvalidation.net/en/latest/aspnet.html</a></li></ul><p><strong>4 — Humanizer</strong></p><p>Humanizer atende a todas as suas necessidades .NET para manipular e exibir <em>string, enum, datetime, times, timespan, timestamp, </em>número e quantidades.</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/Humanizer">https://www.nuget.org/packages/Humanizer</a></li><li><strong>Projeto</strong>: <a href="https://github.com/Humanizr/Humanizer">https://github.com/Humanizr/Humanizer</a></li><li><strong>Dicas</strong>: <a href="https://blog.iteris.com.br/humanizer-a-biblioteca-definitiva-para-manipular-strings-em-net">https://blog.iteris.com.br/humanizer-a-biblioteca-definitiva-para-manipular-strings-em-net</a></li></ul><p><strong>5 — RestSharper</strong></p><p>RestSharp é a biblioteca <em>HttpClient </em>mais popular em aplicações .NET, trabalhando com serialização e desserialização automáticas, detecção de tipo de <em>request </em>e <em>response</em>, variedade de autenticações e recursos úteis para se comunicar com outras APIs no seu projeto. (<em>* outra ótima opção também é o pacte </em><a href="https://github.com/reactiveui/refit"><em>Refit</em></a>)</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/RestSharp">https://www.nuget.org/packages/RestSharp</a></li><li><strong>Projeto</strong>: <a href="https://github.com/restsharp/RestSharp">https://github.com/restsharp/RestSharp</a></li><li><strong>Dicas</strong>: <a href="https://restsharp.dev/getting-started/getting-started.html">https://restsharp.dev/getting-started/getting-started.html</a></li></ul><p><strong>6 — Automapper</strong></p><p>AutoMapper é uma biblioteca open-source criada por <a href="https://jimmybogard.com/">Jimmy Bogard</a> para resolver problemas de mapeamento de um objeto para outro. Este tipo de tarefa geralmente é sensível, e essa biblioteca foi criada para resolver esta situação de forma simples (* <em>mas cuidado para ele não se tornar um vidão de performance no seu projeto. Outra ótima alternativa é o </em><a href="https://github.com/MapsterMapper/Mapster"><em>Mapter</em></a>).</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/automapper">https://www.nuget.org/packages/automapper</a></li><li><strong>Projeto</strong>: <a href="https://github.com/AutoMapper/AutoMapper">https://github.com/AutoMapper/AutoMapper</a></li><li><strong>Dicas</strong>: <a href="https://docs.automapper.org/en/latest/Configuration.html">https://docs.automapper.org/en/latest/Configuration.html</a></li></ul><p><strong>7 — FluentAssertions</strong></p><p>Fluent Assertions é um conjunto de métodos de extensão que nos permitem especificar de forma natural o resultado esperado de um teste de unidade no estilo <a href="https://pt.wikipedia.org/wiki/Test-driven_development"><em>TDD</em></a><em> </em>ou <a href="https://pt.wikipedia.org/wiki/Behavior_Driven_Development"><em>BDD</em></a>.</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/FluentAssertions">https://www.nuget.org/packages/FluentAssertions</a></li><li><strong>Projeto</strong>: <a href="https://github.com/fluentassertions/fluentassertions">https://github.com/fluentassertions/fluentassertions</a></li><li><strong>Dicas</strong>: <a href="https://fluentassertions.com/introduction">https://fluentassertions.com/introduction</a></li></ul><p><strong>8 — NSubstitute</strong></p><p>NSubstitute é uma ótima biblioteca para <em>mock </em>de objetos em <em>Test Driven Development (TDD)</em> em .NET. Com a abordagem de jogar fora a confusão em torno de <em>Dummies</em>, <em>Mocks</em>, <em>Stubs</em>, <em>Fakes</em>, <em>Spies </em>e <em>Test Doubles</em> facilitando nas escritas dos testes.</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/NSubstitute">https://www.nuget.org/packages/NSubstitute</a></li><li><strong>Projeto</strong>: <a href="https://github.com/nsubstitute/NSubstitute">https://github.com/nsubstitute/NSubstitute</a></li><li><strong>Dicas</strong>: <a href="https://nsubstitute.github.io/">https://nsubstitute.github.io</a></li></ul><p><strong>9 — StackExchange.Redis</strong></p><p>StackExchange.Redis é uma biblioteca que facilita a comunicação com o Redis, com vários métodos de extensão úteis deixando muito mais simples a comunicação e a manutenção de <em>cache </em>com o banco de dados.</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/StackExchange.Redis">https://www.nuget.org/packages/StackExchange.Redis</a></li><li><strong>Projeto</strong>: <a href="https://github.com/StackExchange/StackExchange.Redis">https://github.com/StackExchange/StackExchange.Redis</a></li><li><strong>Dicas</strong>: <a href="https://stackexchange.github.io/StackExchange.Redis">https://stackexchange.github.io/StackExchange.Redis</a></li></ul><p><strong>10 — Dapper</strong></p><p>Dapper trabalha com a conexão de banco de dados existente e adiciona métodos de extensão para executar <em>queries</em> SQL e mapeá-lo de volta para classes em C#. Com o Dapper.Contrib fica ainda mais fácil manusear as operações <em>CRUD </em>com seu banco de dados.</p><ul><li><strong>Nuget</strong>: <a href="https://www.nuget.org/packages/Dapper">https://www.nuget.org/packages/Dapper</a> e <a href="https://www.nuget.org/packages/Dapper.Contrib">https://www.nuget.org/packages/Dapper.Contrib</a></li><li><strong>Projeto</strong>: <a href="https://github.com/DapperLib/Dapper">https://github.com/DapperLib/Dapper</a></li><li><strong>Dicas</strong>: <a href="https://dapper-tutorial.net/">https://dapper-tutorial.net</a></li></ul><p><strong>Finalizando</strong></p><p>Esses foram os principais pacotes Nuget que utilizo em quase todos projetos. Acredito que eles contribuem para uma experiência de desenvolvimento e manutenção muito mais agradável e espero que também sejam úteis em seus projetos. Se você conhece qualquer outro pacote e acha que deveria estar nesta lista, por favor, me informe que atualizo este artigo.</p><p>Agradecimentos especiais a todos os autores e colaboradores desses pacotes, vocês tornam a vida de vários desenvolvedores muito mais fácil.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe01a6e8a0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>