<?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"><channel><title><![CDATA[Jhon's Blog]]></title><description><![CDATA[Jhon's Blog]]></description><link>https://blog.jhonatanoliveira.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 13 Nov 2026 17:34:58 GMT</lastBuildDate><atom:link href="https://blog.jhonatanoliveira.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Getting started with gRPC Service with .NET 7]]></title><description><![CDATA[gRPC, a high-performance, open-source RPC (Remote Procedure Call) framework developed by Google, has gained immense popularity among developers for…]]></description><link>https://blog.jhonatanoliveira.dev/getting-started-with-grpc-service-with-net-7</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/getting-started-with-grpc-service-with-net-7</guid><category><![CDATA[gRPC]]></category><category><![CDATA[C#]]></category><category><![CDATA[.NET]]></category><category><![CDATA[asp.net core]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sun, 22 Oct 2023 21:36:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/xG8IQMqMITM/upload/8367f0f1c3054951088d0cf4a8e28126.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>gRPC, a high-performance, open-source RPC (Remote Procedure Call) framework developed by Google, has gained immense popularity among developers for building efficient and robust APIs. This blog post will explore how to get started with gRPC services using .NET 7.</p>
<h1 id="heading-what-is-grpc"><strong>What is gRPC?</strong></h1>
<p>gRPC is an open-source framework developed by Google that facilitates efficient and robust communication between distributed systems. It is based on the Remote Procedure Call (RPC) protocol, where a program can cause a procedure (subroutine) to execute in another address space (commonly on another server) without the programmer explicitly coding the details for remote communication. gRPC stands for Google Remote Procedure Calls.</p>
<h2 id="heading-why-was-grpc-created"><strong>Why was gRPC Created?</strong></h2>
<p>gRPC was created to address the need for a high-performance, language-agnostic, and platform-independent framework for building efficient APIs and microservices. It was designed to replace the traditional REST APIs and overcome their limitations. Some of the key reasons for its creation include:</p>
<ol>
<li><p><strong>Efficiency:</strong> gRPC uses Protocol Buffers (protobufs) as its interface definition language (IDL). Protocol Buffers are a language-agnostic binary serialization format that is compact and efficient. This results in smaller message sizes and faster serialization/deserialization processes compared to JSON or XML used in REST APIs.</p>
</li>
<li><p><strong>Performance:</strong> gRPC supports multiplexing, where multiple requests can be sent concurrently over a single TCP connection. This feature significantly improves performance, especially in scenarios with high-latency connections, making it ideal for microservices architectures.</p>
</li>
<li><p><strong>Language Independence:</strong> gRPC supports many programming languages, making it easy to build polyglot systems where different services are implemented in other languages but can still communicate seamlessly.</p>
</li>
<li><p><strong>Streaming:</strong> gRPC supports unary (single request/response) and streaming RPCs. Bidirectional streaming allows clients and servers to send a stream of messages to each other, enabling real-time communication patterns.</p>
</li>
<li><p><strong>Code Generation:</strong> gRPC uses Protocol Buffers to define service methods and message types. This definition can be used to generate client and server code in multiple programming languages, ensuring type safety and reducing the chance of errors.</p>
</li>
</ol>
<h2 id="heading-key-concepts-in-grpc"><strong>Key Concepts in gRPC:</strong></h2>
<ol>
<li><p><strong>Service Definition:</strong> gRPC services are defined using Protocol Buffers. A <code>.proto</code> file defines the service methods and the message types used in the service.</p>
</li>
<li><p><strong>RPC Methods:</strong> gRPC services expose remote methods clients can call. These methods are defined in the <code>.proto</code> file and can be unary or streaming.</p>
</li>
<li><p><strong>Protocol Buffers (protobufs):</strong> Protocol Buffers are used to serialize structured data. They provide a language-agnostic interface definition, allowing you to define your data models and service methods.</p>
</li>
<li><p><strong>Streaming:</strong> gRPC supports streaming, enabling clients and servers to send and receive a stream of messages, making it suitable for real-time applications.</p>
</li>
<li><p><strong>Code Generation:</strong> Protocol Buffers are compiled to generate client and server code in various programming languages. This generated code handles the serialization/deserialization and network communication, making it easy for developers to work with gRPC.</p>
</li>
</ol>
<h1 id="heading-implementation"><strong>Implementation</strong></h1>
<p>First, we will create the gRPC project with the following command.</p>
<pre><code class="lang-csharp">dotnet <span class="hljs-keyword">new</span> grpc -n MyGrpcService
</code></pre>
<h2 id="heading-nuget-packages"><strong>Nuget packages</strong></h2>
<p>We will use the following nuget packages:</p>
<ol>
<li><p><a target="_blank" href="http://Grpc.Tools">Grpc.Tools</a>: provides tools and utilities for working with gRPC in .NET applications. It includes the Protocol Buffers compiler (<code>protoc</code>) plugin for C# code generation. This plugin is essential for generating C# client and server code from the <code>.proto</code> files (Protocol Buffers files), which define the gRPC service methods and message types.</p>
</li>
<li><p><a target="_blank" href="https://www.nuget.org/packages/Microsoft.AspNetCore.Grpc.JsonTranscoding">Microsoft.AspNetCore.Grpc.JsonTranscoding</a>: creates RESTful JSON APIs for gRPC services.</p>
</li>
</ol>
<h2 id="heading-define-a-proto-file"><strong>Define a .proto File</strong></h2>
<p>Defining services in gRPC involves creating a Protocol Buffers (<code>.proto</code>) file where we specify the service methods and message types used for communication. Protocol Buffers provide a language-agnostic way to define our API, allowing us to generate client and server code in multiple programming languages.</p>
<p>The following <code>proto</code> has:</p>
<ul>
<li><p><code>CreateMuscleRequest</code> and <code>ReadMuscleResponse</code> are message types. Message types define the data structure that can be sent or received in gRPC methods.</p>
</li>
<li><p><code>CoachPlanService</code> is the service containing the RPC method <code>CreateMuscle</code>. <code>rpc CreateMuscle(CreateMuscleRequest) returns (ReadMuscleResponse) {}</code> defines a unary RPC method called <code>CreateMuscle</code> that takes a <code>CreateMuscleRequest</code> message as input and returns a <code>ReadMuscleResponse</code> message.</p>
</li>
<li><p>In the context of Protocol Buffers (protobuf), "repeated" is a keyword used to define repeated fields within a message. Repeated fields are used to represent a list of values of the same type. They allow us to have multiple occurrences of a field within a single message</p>
</li>
<li><p>When creating the fields of the message, it is possible to define the order of the fields.</p>
</li>
</ul>
<pre><code class="lang-csharp">syntax = <span class="hljs-string">"proto3"</span>;

option csharp_namespace = <span class="hljs-string">"CoachPlan.gRPC"</span>;

service CoachPlan {
    <span class="hljs-function">rpc <span class="hljs-title">CreateMuscle</span>(<span class="hljs-params">CreateMuscleRequest</span>) <span class="hljs-title">returns</span> (<span class="hljs-params">ReadMuscleResponse</span>)</span>{

    }

    <span class="hljs-function">rpc <span class="hljs-title">ReadMuscle</span>(<span class="hljs-params">ReadMuscleRequest</span>) <span class="hljs-title">retuns</span> (<span class="hljs-params">ReadMuscleResponse</span>)</span> {

    }

    <span class="hljs-function">rpc <span class="hljs-title">ListMuscle</span>(<span class="hljs-params">GetAllMuscleRequest</span>) <span class="hljs-title">returns</span> (<span class="hljs-params">GetAllMuscleResponse</span>)</span> {

    } 

    <span class="hljs-function">rpc <span class="hljs-title">UpdateMuscle</span>(<span class="hljs-params">UpdateMuscleRequest</span>) <span class="hljs-title">returns</span> (<span class="hljs-params">ReadMuscleResponse</span>)</span> {

    }

    <span class="hljs-function">rpc <span class="hljs-title">DeleteMuscle</span>(<span class="hljs-params">DeleteMuscleRequest</span>) <span class="hljs-title">returns</span> (<span class="hljs-params">DeleteMuscleResponse</span>)</span> {

    }    
}

message CreateMuscleRequest {
    <span class="hljs-keyword">string</span> name = <span class="hljs-number">1</span>;
}

message ReadMuscleRequest {
    int32 id = <span class="hljs-number">1</span>;
}

message ReadMuscleResponse {
    int32 id = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">string</span> name = <span class="hljs-number">2</span>;
}

message GetAllMuscleRequest {}

message GetAllMuscleResponse {
    repeated ReadMuscleResponse muscles = <span class="hljs-number">1</span>;
}

message UpdateMuscleRequest {
    int32 id = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">string</span> name = <span class="hljs-number">2</span>;
}

message DeleteMuscleRequest {
    int32 id = <span class="hljs-number">1</span>;
}

message DeleteMuscleResponse {
    int32 id = <span class="hljs-number">1</span>;
}
</code></pre>
<h2 id="heading-service-implementation"><strong>Service implementation</strong></h2>
<p>Before implementing the service, we must add the <code>coachPlan.proto</code> in the <code>csproj</code> file and build the project.</p>
<pre><code class="lang-csharp">  &lt;ItemGroup&gt;
    &lt;Protobuf Include=<span class="hljs-string">"Protos\greet.proto"</span> GrpcServices=<span class="hljs-string">"Server"</span> /&gt;
     &lt;Protobuf Include=<span class="hljs-string">"Protos\coachPlan.proto"</span> GrpcServices=<span class="hljs-string">"Server"</span> /&gt;
  &lt;/ItemGroup&gt;
</code></pre>
<p>After building the project, a file containing an abstract class with the methods defined in the proto file will be generated. We will inherit our service from this class and override the methods.</p>
<pre><code class="lang-csharp"><span class="hljs-comment"><span class="hljs-doctag">///</span> <span class="hljs-doctag">&lt;summary&gt;</span>Base class for server-side implementations of CoachPlan<span class="hljs-doctag">&lt;/summary&gt;</span></span>
    [<span class="hljs-meta">grpc::BindServiceMethod(typeof(CoachPlan), <span class="hljs-meta-string">"BindService"</span>)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CoachPlanBase</span>
    {
      [<span class="hljs-meta">global::System.CodeDom.Compiler.GeneratedCode(<span class="hljs-meta-string">"grpc_csharp_plugin"</span>, null)</span>]
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">global</span>::System.Threading.Tasks.Task&lt;<span class="hljs-keyword">global</span>::CoachPlan.gRPC.ReadMuscleResponse&gt; CreateMuscle(<span class="hljs-keyword">global</span>::CoachPlan.gRPC.CreateMuscleRequest request, grpc::ServerCallContext context)
      {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> grpc::RpcException(<span class="hljs-keyword">new</span> grpc::Status(grpc::StatusCode.Unimplemented, <span class="hljs-string">""</span>));
      }

      [<span class="hljs-meta">global::System.CodeDom.Compiler.GeneratedCode(<span class="hljs-meta-string">"grpc_csharp_plugin"</span>, null)</span>]
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">global</span>::System.Threading.Tasks.Task&lt;<span class="hljs-keyword">global</span>::CoachPlan.gRPC.ReadMuscleResponse&gt; ReadMuscle(<span class="hljs-keyword">global</span>::CoachPlan.gRPC.ReadMuscleRequest request, grpc::ServerCallContext context)
      {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> grpc::RpcException(<span class="hljs-keyword">new</span> grpc::Status(grpc::StatusCode.Unimplemented, <span class="hljs-string">""</span>));
      }

      [<span class="hljs-meta">global::System.CodeDom.Compiler.GeneratedCode(<span class="hljs-meta-string">"grpc_csharp_plugin"</span>, null)</span>]
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">global</span>::System.Threading.Tasks.Task&lt;<span class="hljs-keyword">global</span>::CoachPlan.gRPC.GetAllMuscleResponse&gt; ListMuscle(<span class="hljs-keyword">global</span>::CoachPlan.gRPC.GetAllMuscleRequest request, grpc::ServerCallContext context)
      {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> grpc::RpcException(<span class="hljs-keyword">new</span> grpc::Status(grpc::StatusCode.Unimplemented, <span class="hljs-string">""</span>));
      }

      [<span class="hljs-meta">global::System.CodeDom.Compiler.GeneratedCode(<span class="hljs-meta-string">"grpc_csharp_plugin"</span>, null)</span>]
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">global</span>::System.Threading.Tasks.Task&lt;<span class="hljs-keyword">global</span>::CoachPlan.gRPC.ReadMuscleResponse&gt; UpdateMuscle(<span class="hljs-keyword">global</span>::CoachPlan.gRPC.UpdateMuscleRequest request, grpc::ServerCallContext context)
      {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> grpc::RpcException(<span class="hljs-keyword">new</span> grpc::Status(grpc::StatusCode.Unimplemented, <span class="hljs-string">""</span>));
      }

      [<span class="hljs-meta">global::System.CodeDom.Compiler.GeneratedCode(<span class="hljs-meta-string">"grpc_csharp_plugin"</span>, null)</span>]
      <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">global</span>::System.Threading.Tasks.Task&lt;<span class="hljs-keyword">global</span>::CoachPlan.gRPC.DeleteMuscleResponse&gt; DeleteMuscle(<span class="hljs-keyword">global</span>::CoachPlan.gRPC.DeleteMuscleRequest request, grpc::ServerCallContext context)
      {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> grpc::RpcException(<span class="hljs-keyword">new</span> grpc::Status(grpc::StatusCode.Unimplemented, <span class="hljs-string">""</span>));
      }

    }
</code></pre>
<p>The following code shows the implementation of the service.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CoachPlanService</span> : <span class="hljs-title">CoachPlan.CoachPlanBase</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMuscleService _muscleService;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CoachPlanService</span>(<span class="hljs-params">IMuscleService muscleService</span>)</span>
    {
        _muscleService = muscleService;
    }

     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task&lt;ReadMuscleResponse&gt; <span class="hljs-title">CreateMuscle</span>(<span class="hljs-params">CreateMuscleRequest request, ServerCallContext context</span>)</span>
     {
        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">string</span>.IsNullOrEmpty(request.Name) || <span class="hljs-keyword">string</span>.IsNullOrEmpty(request.Name))
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RpcException(<span class="hljs-keyword">new</span> Status(StatusCode.InvalidArgument, <span class="hljs-string">"The property 'Name' is required."</span>));

        MuscleDto dto = request.ToDto();

        <span class="hljs-keyword">var</span> id = <span class="hljs-keyword">await</span> _muscleService.Create(dto);

        <span class="hljs-keyword">var</span> muscleDto = <span class="hljs-keyword">await</span> _muscleService.GetById(id);

        <span class="hljs-keyword">var</span> response = muscleDto.ToGrpcModel();

        <span class="hljs-keyword">return</span> response;
     }

     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task&lt;GetAllMuscleResponse&gt; <span class="hljs-title">ListMuscle</span>(<span class="hljs-params">GetAllMuscleRequest request, ServerCallContext context</span>)</span>
     {
        <span class="hljs-keyword">var</span> muscles = <span class="hljs-keyword">await</span> _muscleService.GetAll();

        <span class="hljs-keyword">var</span> response = muscles.ToGrpcModel();

        <span class="hljs-keyword">return</span> response;
     }

     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task&lt;ReadMuscleResponse&gt; <span class="hljs-title">ReadMuscle</span>(<span class="hljs-params">ReadMuscleRequest request, ServerCallContext context</span>)</span>
     {
         <span class="hljs-keyword">var</span> muscle = <span class="hljs-keyword">await</span> _muscleService.GetById(request.Id);

         <span class="hljs-keyword">if</span>(muscle == <span class="hljs-literal">null</span>)
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RpcException(<span class="hljs-keyword">new</span> Status(StatusCode.NotFound, <span class="hljs-string">"Not Found"</span>));


         <span class="hljs-keyword">return</span> muscle.ToGrpcModel();
     }

      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task&lt;ReadMuscleResponse&gt; <span class="hljs-title">UpdateMuscle</span>(<span class="hljs-params">UpdateMuscleRequest request, ServerCallContext context</span>)</span>
      {
         <span class="hljs-keyword">if</span>(<span class="hljs-keyword">string</span>.IsNullOrEmpty(request.Name) || <span class="hljs-keyword">string</span>.IsNullOrEmpty(request.Name))
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RpcException(<span class="hljs-keyword">new</span> Status(StatusCode.InvalidArgument, <span class="hljs-string">"The property 'Name' is required."</span>));

         <span class="hljs-keyword">var</span> muscle = <span class="hljs-keyword">await</span> _muscleService.GetById(request.Id);

         <span class="hljs-keyword">if</span>(muscle == <span class="hljs-literal">null</span>)
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RpcException(<span class="hljs-keyword">new</span> Status(StatusCode.NotFound, <span class="hljs-string">"Not Found"</span>));

         muscle.Name = request.Name;

         <span class="hljs-keyword">await</span> _muscleService.Update(muscle); 

         <span class="hljs-keyword">return</span> muscle.ToGrpcModel();
      }

      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task&lt;DeleteMuscleResponse&gt; <span class="hljs-title">DeleteMuscle</span>(<span class="hljs-params">DeleteMuscleRequest request, ServerCallContext context</span>)</span>
      {
         <span class="hljs-keyword">var</span> muscle = <span class="hljs-keyword">await</span> _muscleService.GetById(request.Id);

         <span class="hljs-keyword">if</span>(muscle == <span class="hljs-literal">null</span>)
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RpcException(<span class="hljs-keyword">new</span> Status(StatusCode.NotFound, <span class="hljs-string">"Not Found"</span>));

         <span class="hljs-keyword">await</span> _muscleService.Delete(muscle);

         <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> DeleteMuscleResponse()
         {
            Id = muscle.Id
         };
      }
}
</code></pre>
<p>And then, we need to configure the service in the app.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Configure the HTTP request pipeline.</span>
app.MapGrpcService&lt;GreeterService&gt;();
app.MapGrpcService&lt;CoachPlanService&gt;();
</code></pre>
<h3 id="heading-testing">Testing</h3>
<p>We need to create a gRPC request to test the implementation with Postman. After that, it is necessary to import the <code>proto</code> file. On the next page, it is required to define a name for the API that will be imported. After that, the methods will be listed on the request page. The following images show the step-by-step.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697991389578/87cfc4ee-d99d-4322-86d8-3294b6d139c5.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697991568256/d9c265ab-befb-4711-9025-42689be68afd.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697991990723/70adfcb1-b932-4110-beca-e93a669e0188.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697992047044/229a55f4-2075-49b3-bb27-582d6a0cc29a.png" alt class="image--center mx-auto" /></p>
<p>We must pick a method from the list and define the message with the fields defined in the project's proto file to execute a method.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697992235104/893846e3-c195-43e0-823a-686114083d7c.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697992419960/aec6207b-91b9-4bde-96d6-24e685332fc8.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697992429064/ada56f42-7c0a-4a96-afd1-2f0b998da085.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>This was a simple introduction to building a gRPC with .NET. The seamless integration of gRPC with .NET brings the power of Google's innovative technology to the Microsoft ecosystem and highlights the importance of efficient, real-time, bidirectional communication. With its support for streaming, code generation, and multiplexing, gRPC simplifies the complexities of distributed systems, allowing developers to focus on building meaningful features instead of worrying about network intricacies.</p>
<p>You can find the complete code on my <a target="_blank" href="https://github.com/jhonatanfernando/coachplan"><strong>GitHub</strong></a><strong>.</strong></p>
]]></content:encoded></item><item><title><![CDATA[Getting started with GraphQL in Asp.Net Core]]></title><description><![CDATA[GraphQL is a powerful query language and runtime that efficiently fetches and manipulates data from APIs. This blog post will explore how to get started…]]></description><link>https://blog.jhonatanoliveira.dev/getting-started-with-graphql-in-aspnet-core</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/getting-started-with-graphql-in-aspnet-core</guid><category><![CDATA[C#]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[asp.ne]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Tue, 16 May 2023 16:04:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/FHnnjk1Yj7Y/upload/af4aeca40dc8da0769bd1f0f41fff900.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>GraphQL is a powerful query language and runtime that efficiently fetches and manipulates data from APIs. This blog post will explore how to get started with GraphQL in Asp.Net Core.</p>
<h1 id="heading-what-is-graphql">What is GraphQL?</h1>
<p>GraphQL is a query language and runtime for APIs that Facebook developed. It was designed to overcome some of the limitations of REST (Representational State Transfer) APIs by allowing clients to request only the data they need in the exact format they need and reducing the number of round-trips to the server.</p>
<p>In GraphQL, clients can specify the exact data they need, including nested relationships and fields, and the server will return exactly that data in a single response. This avoids over-fetching (getting more data than needed) and under-fetching (not getting enough data), which are common issues with REST APIs.</p>
<p>GraphQL also provides a type system for APIs, allowing developers to define the types of data that can be queried and returned and the relationships between them. This allows for more efficient and reliable API development and consumption.</p>
<p>GraphQL provides a more flexible and efficient way to build and consume APIs than traditional REST APIs, especially in complex or dynamic applications with changing data requirements.</p>
<h2 id="heading-core-concepts-of-graphql">Core concepts of GraphQL</h2>
<p>Here are the core concepts of GraphQL:</p>
<ol>
<li><p><strong>Schema</strong>: The schema defines the types of data that can be queried, as well as the queries, mutations, and subscriptions that are available. The schema is written in the GraphQL Schema Definition Language (SDL) and describes the shape and relationships of the data.</p>
</li>
<li><p><strong>Types</strong>: GraphQL defines its own type system, which includes scalars (like <code>String</code>, <code>Int</code>, <code>Float</code>, and <code>Boolean</code>) and complex types (like <code>Object</code>, <code>Interface</code>, <code>Union</code>, and <code>Enum</code>). Types are used to define the shape and relationships of the data in the schema.</p>
</li>
<li><p><strong>Fields</strong>: Fields are the basic unit of data in GraphQL. Each field has a name and a type and represents a single piece of data that can be queried. Fields can also have arguments which filter or modify the data returned by the field.</p>
</li>
<li><p><strong>Queries</strong>: Queries are used to fetch data from the server. A query specifies the fields to be retrieved and their associated arguments, and the server responds with the requested data.</p>
</li>
<li><p><strong>Mutations</strong>: Mutations are used to modify data on the server. Like queries, mutations specify the fields to be modified and their associated arguments, but the server responds with the updated data.</p>
</li>
<li><p><strong>Subscriptions</strong>: Subscriptions are used to receive real-time updates from the server. A subscription specifies the fields to be subscribed to and their associated arguments, and the server pushes updates to the client as they occur.</p>
</li>
<li><p><strong>Directives</strong>: Directives are used to modify the behavior of fields or operations. They can conditionally include or exclude fields based on variables, paginate results, or apply custom logic to fields.</p>
</li>
<li><p><strong>Fragments</strong>: Fragments are used to reuse common selections of fields in queries. They allow us to define a set of fields once and then reference them from multiple places in our query.</p>
</li>
<li><p><strong>Variables</strong>: Variables are used to parameterize queries and mutations. They allow us to pass values into the query at runtime, making queries more dynamic and reusable.</p>
</li>
</ol>
<p>These are the core concepts of GraphQL, and understanding them is the key to using GraphQL effectively. We can create powerful, flexible APIs that provide a better user experience by leveraging these concepts.</p>
<h2 id="heading-operations-in-graphql">Operations in GraphQL</h2>
<p>GraphQL supports three main types of operations: queries, mutations, and subscriptions.</p>
<ol>
<li><strong>Queries</strong>: Queries are used to retrieve data from the server. A query specifies the fields to be retrieved and their associated arguments, and the server responds with the requested data. Queries are executed using the <code>query</code> keyword.</li>
</ol>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> {
  getUser(<span class="hljs-symbol">id:</span> <span class="hljs-string">"123"</span>) {
    name
    email
    age
  }
}
</code></pre>
<ol>
<li><strong>Mutations</strong>: Mutations are used to modify data on the server. Like queries, mutations specify the fields to be modified and their associated arguments, but the server responds with the updated data. Mutations are executed using the <code>mutation</code> keyword.</li>
</ol>
<pre><code class="lang-graphql"><span class="hljs-keyword">mutation</span> {
  updateUser(<span class="hljs-symbol">id:</span> <span class="hljs-string">"123"</span>, <span class="hljs-symbol">name:</span> <span class="hljs-string">"John Doe"</span>, <span class="hljs-symbol">email:</span> <span class="hljs-string">"john@example.com"</span>, <span class="hljs-symbol">age:</span> <span class="hljs-number">30</span>) {
    name
    email
    age
  }
}
</code></pre>
<ol>
<li><strong>Subscriptions</strong>: Subscriptions are used to receive real-time updates from the server. A subscription specifies the fields to be subscribed to and their associated arguments, and the server pushes updates to the client as they occur. Subscriptions are executed using the <code>subscription</code> keyword.</li>
</ol>
<pre><code class="lang-graphql"><span class="hljs-keyword">subscription</span> {
  newMessages(<span class="hljs-symbol">channelId:</span> <span class="hljs-string">"123"</span>) {
    id
    content
    createdAt
    user {
      name
      avatarUrl
    }
  }
}
</code></pre>
<p>In addition to these core operations, GraphQL supports directives, which modify the behavior of fields or operations, and fragments, which reuse a common selection of fields in queries.</p>
<h1 id="heading-graphql-vs-rest">GraphQL vs REST</h1>
<p>GraphQL and REST are popular approaches to building APIs but have some key differences. Here are some of the main differences between GraphQL and REST:</p>
<ol>
<li><p><strong>Data Fetching</strong>: In REST, multiple endpoints often fetch different resource parts. This can result in over-fetching or under-fetching of data, as the client has limited control over the returned data. With GraphQL, clients can fetch exactly the data they need, and the server responds with only that data, eliminating over-fetching and under-fetching.</p>
</li>
<li><p><strong>Response Structure</strong>: In REST, the server defines the structure of the response, and the client has limited control over the returned data. With GraphQL, the client defines the structure of the response by specifying the fields they want to fetch, and the server responds with only those fields.</p>
</li>
<li><p><strong>Versioning</strong>: In REST, versioning is typically done by creating new endpoints with different URLs or adding version numbers to the URL. This can result in a proliferation of endpoints and increased complexity. With GraphQL, versioning is handled at the schema level, and clients can request specific schema versions.</p>
</li>
<li><p><strong>Schema Validation</strong>: In REST, there is no standard for schema validation, and clients can receive unexpected responses if the server changes its response structure. With GraphQL, the schema is defined in advance, and clients can validate their queries against the schema to ensure they will receive the expected response.</p>
</li>
<li><p><strong>Tooling</strong>: GraphQL has a rich ecosystem of tools and libraries for query validation, auto-completion, and debugging. REST has a more limited tooling ecosystem, and many tools are specific to particular frameworks or languages.</p>
</li>
</ol>
<p>GraphQL provides more flexibility and control over data fetching and response structure, while REST has a more straightforward and well-established approach to building APIs. The choice between GraphQL and REST depends on the application's specific needs, the resources available, and the development team's preferences.</p>
<h1 id="heading-graphql-frameworks-in-net">GraphQL Frameworks in .NET</h1>
<p>GraphQL is becoming increasingly popular in .NET development, and several frameworks are available that make it easier to build GraphQL APIs in .NET. Here are some of the most popular GraphQL frameworks for .NET:</p>
<ol>
<li><p><strong>Hot Chocolate</strong>: Hot Chocolate is a high-performance GraphQL server for .NET that supports the latest GraphQL features and integrates with <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core. It includes features like schema stitching, data loaders, and real-time subscriptions and provides a clean and intuitive API for building GraphQL APIs.</p>
</li>
<li><p><strong>GraphQL.NET</strong>: GraphQL.NET is a popular GraphQL framework for .NET that implements the GraphQL specification completely. It includes features like schema validation, query parsing, and execution and provides a powerful query execution engine that supports complex queries and data fetching strategies.</p>
</li>
<li><p><strong>Strawberry Shake</strong>: Strawberry Shake is a GraphQL client library for .NET that provides a strongly-typed API for querying GraphQL APIs. It includes features like query validation, auto-completion, and caching and integrates with popular .NET tools like Visual Studio and .NET Core.</p>
</li>
<li><p><strong>GraphQL for .NET</strong>: GraphQL for .NET is a lightweight GraphQL framework for .NET that provides a simple and intuitive API for building GraphQL APIs. It includes features like schema validation, query parsing, and execution and provides a flexible data fetching mechanism that allows using any data source.</p>
</li>
<li><p><strong>GraphQL.Conventions</strong>: GraphQL.Conventions are a convention-based GraphQL framework for .NET that provides a simple and intuitive API for building GraphQL APIs. It includes features like schema validation, query parsing, and execution and automatically uses conventions to generate resolvers and data types from the .NET classes.</p>
</li>
</ol>
<h1 id="heading-implementation">Implementation</h1>
<h2 id="heading-nuget-packages">Nuget packages</h2>
<p>We will use the following nuget packages:</p>
<ol>
<li><p><a target="_blank" href="https://github.com/ChilliCream/graphql-platform"><strong>HotChocolate.AspNetCore</strong></a><strong>:</strong> this is a library that provides integration between the Hot Chocolate GraphQL server and <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core.</p>
</li>
<li><p><a target="_blank" href="https://github.com/graphql-dotnet/server"><strong>GraphQL.Server.Ui.Voyager</strong></a>: this tool allows us to explore and interact with a GraphQL API visually. Voyager is a popular tool used to visualize GraphQL APIs and their schemas. It provides a user-friendly interface to explore the API, understand its structure and relationships, and test queries and mutations.</p>
</li>
<li><p><a target="_blank" href="https://github.com/ChilliCream/graphql-platform"><strong>HotChocolate.Data.EntityFramework</strong></a><strong>:</strong> this extension to the Hot Chocolate GraphQL server provides seamless integration with the Entity Framework for data access. With this package, we can define a GraphQL schema that maps to Entity Framework models and expose them as queryable types in the GraphQL API. We can also leverage the package's powerful filtering, sorting, and pagination capabilities to make complex queries on our data.</p>
</li>
</ol>
<p>After installing the packages, it is necessary to register some services and configure the endpoint.</p>
<pre><code class="lang-csharp">builder.Services
    .AddGraphQLServer();
</code></pre>
<pre><code class="lang-csharp">app.MapGraphQL();

app.UseGraphQLVoyager(options: <span class="hljs-keyword">new</span> VoyagerOptions()
{
    GraphQLEndPoint = <span class="hljs-string">"/graphql"</span>,
});
</code></pre>
<h2 id="heading-queries">Queries</h2>
<p>To define the queries, adding a class that exposes the models is necessary. The implementation of the method has a service that calls an Entity Framework repository to get the data.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Query</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;MuscleDto&gt;&gt; GetMuscles(MuscleService service)
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> service.GetAll();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;ExerciseDto&gt;&gt; GetExercises(ExerciseService service)
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> service.GetAll();
    }
}
</code></pre>
<p>The services and the query need to be registered into the services so the app can recognize them.</p>
<pre><code class="lang-csharp">builder.Services
    .AddGraphQLServer()
    .RegisterService&lt;MuscleService&gt;()
    .RegisterService&lt;ExerciseService&gt;()
    .AddQueryType&lt;Query&gt;();
</code></pre>
<h3 id="heading-voyager-view">Voyager View</h3>
<p>Accessing the endpoint <em>/ui/voyager</em> will show the GraphQL APIs and their schemas. We can see in the following image that it shows the two queries and the models that are being used. We can also define descriptions for each type and property, which will be displayed on this page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684109831293/0360d261-e0da-4f1a-84f6-e87b716eb739.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-executing-queries">Executing Queries</h3>
<p>To execute a query, it is necessary to use the reserved word <strong><em>query</em></strong>, the model that the data will be fetched and the properties.</p>
<p>To execute the queries, we can navigate to the endpoint <em>/graphql/</em> where an environment will be loaded, and we will be able to run the queries and see the schema definition. The following image shows how the page looks like.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684207192019/d80e6061-a0e0-4ea2-89c0-515f986d8b29.png" alt class="image--center mx-auto" /></p>
<p>Or we can use an application like <a target="_blank" href="https://insomnia.rest/">Insomnia</a> to execute the queries.</p>
<p>The following codes show the query to get the properties from the Muscle model and the query result.</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> {
    muscles{
        id,
        name,
        exercises {
            id,
            name
        }
    }
}
</code></pre>
<pre><code class="lang-json">{
    <span class="hljs-attr">"data"</span>: {
        <span class="hljs-attr">"muscles"</span>: [
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Back"</span>,
                <span class="hljs-attr">"exercises"</span>: <span class="hljs-literal">null</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Leg"</span>,
                <span class="hljs-attr">"exercises"</span>: <span class="hljs-literal">null</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Biceps"</span>,
                <span class="hljs-attr">"exercises"</span>: <span class="hljs-literal">null</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Triceps"</span>,
                <span class="hljs-attr">"exercises"</span>: <span class="hljs-literal">null</span>
            }
        ]
    }
}
</code></pre>
<p>GraphQL allows parallel queries like the following query. To allow the app to execute this type of query, it is necessary to change how DBContext is registered and how to resolve it inside the repositories.</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> {
    <span class="hljs-symbol">a:</span> muscles {
        id
        name
    }

        <span class="hljs-symbol">b:</span> muscles {
        id
        name
    }
}
</code></pre>
<p>When injecting a <code>DbContext</code> using the <code>DbContextKind.Pool</code>, Hot Chocolate will retrieve one <code>DbContext</code> instance from the pool for each invocation of a resolver. Once the resolver has finished executing, the instance will be returned to the pool.</p>
<pre><code class="lang-csharp">builder.Services.AddPooledDbContextFactory&lt;CoachPlanContext&gt;(options =&gt;
       options.UseSqlServer(builder.Configuration.GetConnectionString(<span class="hljs-string">"DefaultConnection"</span>)));
</code></pre>
<p>When creating services/repositories, they must inject the <code>IDbContextFactory&lt;T&gt;</code> instead of the <code>DbContext</code> directly. The services/repositories also need to be of a transient lifetime. Otherwise, we could be faced with the <code>DbContext</code> concurrency issue if the same <code>DbContext</code> instance is accessed by two resolvers through our service in parallel.</p>
<pre><code class="lang-csharp">builder.Services.AddTransient&lt;IMuscleRepository, MuscleRepository&gt;();
builder.Services.AddTransient&lt;MuscleService&gt;();
</code></pre>
<pre><code class="lang-csharp">
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MuscleRepository</span>: <span class="hljs-title">IMuscleRepository</span>, <span class="hljs-title">IAsyncDisposable</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> CoachPlanContext _coachPlanContext;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MuscleRepository</span>(<span class="hljs-params">IDbContextFactory&lt;CoachPlanContext&gt; dbContextFactory</span>)</span>
    {
        _coachPlanContext = dbContextFactory.CreateDbContext();
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span>  IEnumerable&lt;Muscle&gt; <span class="hljs-title">GetAll</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">return</span> _coachPlanContext.Muscles;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> ValueTask <span class="hljs-title">DisposeAsync</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">return</span> _coachPlanContext.DisposeAsync();
    }
}
</code></pre>
<p>After the changes, the parallel query can be executed without errors, and the following code shows the result of it.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"data"</span>: {
        <span class="hljs-attr">"a"</span>: [
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Back"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Leg"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Biceps"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Triceps"</span>
            }
        ],
        <span class="hljs-attr">"b"</span>: [
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Back"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Leg"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Biceps"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Triceps"</span>
            }
        ]
    }
}
</code></pre>
<h3 id="heading-object-type">Object Type</h3>
<p>GraphQL Objects represent a list of named fields, and each yield a specific type value. Object values should be serialized as ordered maps, where the selected field names (or aliases) are the keys, and the result of evaluating the field is the value, ordered by the order in which they appear in the selection set. All fields defined within an Object type must not have a name which begins with "__" (two underscores), as this is used exclusively by GraphQL’s introspection system.</p>
<p>Creating an ObjectType, we can add a resolver for a specific property of the model. For example, we can resolve the values for the Exercises property for the Muscle model.</p>
<p>The following codes show how to create the ObjectTye and register it. For the Exercises property, a method will be called to retrieve all the exercises by MuscleId.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MuscleType</span>: <span class="hljs-title">ObjectType</span>&lt;<span class="hljs-title">MuscleDto</span>&gt;
{
   <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Configure</span>(<span class="hljs-params">IObjectTypeDescriptor&lt;MuscleDto&gt; descriptor</span>)</span>
    {
        descriptor
            .Field(c=&gt; c.Exercises)
            .ResolveWith&lt;Resolvers&gt;(p=&gt; p.GetExercises(<span class="hljs-keyword">default</span>!, <span class="hljs-keyword">default</span>!));
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Resolvers</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;ExerciseDto&gt;&gt; GetExercises([Parent] MuscleDto muscle, ExerciseService service)
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> service.GetByMuscleId(muscle.Id);
    }
}
</code></pre>
<pre><code class="lang-csharp">builder.Services
    .AddGraphQLServer()
    .RegisterService&lt;MuscleService&gt;()
    .RegisterService&lt;ExerciseService&gt;()
    .AddType&lt;MuscleType&gt;()
    .AddQueryType&lt;Query&gt;();
</code></pre>
<p>Now executing the query to bring all muscles, we can also have the exercises related to each.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"data"</span>: {
        <span class="hljs-attr">"muscles"</span>: [
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Back"</span>,
                <span class="hljs-attr">"exercises"</span>: [
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Deadlifts"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">10</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Dumbbell Row"</span>
                    }
                ]
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Leg"</span>,
                <span class="hljs-attr">"exercises"</span>: [
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Air Squat"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Chair Squat"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Leg Press"</span>
                    }
                ]
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Biceps"</span>,
                <span class="hljs-attr">"exercises"</span>: [
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">5</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Barbell Curl"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">6</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Cable Curl With Bar"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">7</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Spider Curl"</span>
                    }
                ]
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Triceps"</span>,
                <span class="hljs-attr">"exercises"</span>: [
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">8</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Bench Dip"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">9</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Close-Grip Push-Up"</span>
                    }
                ]
            }
        ]
    }
}
</code></pre>
<p>We also can use the ObjectType to add a description for the model and its properties. The descriptions will be displayed on the Voyager page.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MuscleType</span>: <span class="hljs-title">ObjectType</span>&lt;<span class="hljs-title">MuscleDto</span>&gt;
{
   <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Configure</span>(<span class="hljs-params">IObjectTypeDescriptor&lt;MuscleDto&gt; descriptor</span>)</span>
    {
        descriptor.Description(<span class="hljs-string">"Represents the muscles of the body."</span>);

        descriptor
            .Field(c=&gt; c.Id)
            .Description(<span class="hljs-string">"Represents the Id of the entry in the table"</span>);

        descriptor
            .Field(c=&gt; c.Name)
            .Description(<span class="hljs-string">"Represents the name of the muscle"</span>);    


        descriptor
            .Field(c=&gt; c.Exercises)
            .Description(<span class="hljs-string">"Represents the exercises for the muscle"</span>)
            .ResolveWith&lt;Resolvers&gt;(p=&gt; p.GetExercises(<span class="hljs-keyword">default</span>!, <span class="hljs-keyword">default</span>!));
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684179688393/b214a447-3fc3-401d-814f-46a7ba155f5b.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-filtering">Filtering</h3>
<p>With Hot Chocolate filters, we can expose complex filter objects through the GraphQL API that translates to native database queries. The default filter implementation translates filters to expression trees that are applied to <code>IQueryable</code>. Hot Chocolate, by default, will inspect the model and infer its possible filter operations. Filters use <code>IQueryable</code> (<code>IEnumerable</code>) by default, but we can also easily customize them to use other interfaces.</p>
<p>First, it is necessary to register the filtering option.</p>
<pre><code class="lang-csharp">builder.Services
    .AddGraphQLServer()
    .RegisterService&lt;MuscleService&gt;()
    .RegisterService&lt;ExerciseService&gt;()
    .AddType&lt;MuscleType&gt;()
    .AddQueryType&lt;Query&gt;()
    .AddFiltering();
</code></pre>
<p>Hot Chocolate will infer the filters directly from the model and then use a Middleware to apply filters to <code>IQueryable&lt;T&gt;</code> or <code>IEnumerable&lt;T&gt;</code> on execution.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Query</span>
{
    [<span class="hljs-meta">UseFiltering</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IEnumerable&lt;MuscleDto&gt; <span class="hljs-title">GetMuscles</span>(<span class="hljs-params">MuscleService service</span>)</span>
    {
        <span class="hljs-keyword">return</span> service.GetAll();
    }

    [<span class="hljs-meta">UseFiltering</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IEnumerable&lt;ExerciseDto&gt; <span class="hljs-title">GetExercises</span>(<span class="hljs-params">ExerciseService service</span>)</span>
    {
        <span class="hljs-keyword">return</span> service.GetAll();
    }
}
</code></pre>
<p>The following codes show the query and the results using filters to fetch the data.</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> {  
    <span class="hljs-symbol">a:</span> muscles(
        <span class="hljs-symbol">where:</span> { <span class="hljs-symbol">id:</span> {<span class="hljs-symbol">eq:</span> <span class="hljs-number">1</span>} }) 
      {
            id,
            name,
            exercises {
                id,
                name
            }
        }

    <span class="hljs-symbol">b:</span> muscles(
        <span class="hljs-symbol">where:</span> {
            <span class="hljs-symbol">or:</span> [{<span class="hljs-symbol">name:</span> {<span class="hljs-symbol">startsWith:</span> <span class="hljs-string">"L"</span>}}, {<span class="hljs-symbol">id:</span> {<span class="hljs-symbol">gte:</span> <span class="hljs-number">3</span>}}]
        })
      {
            id,
            name,
            exercises {
                id,
                name
            }
      }
}
</code></pre>
<pre><code class="lang-json">{
    <span class="hljs-attr">"data"</span>: {
        <span class="hljs-attr">"a"</span>: [
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Back"</span>,
                <span class="hljs-attr">"exercises"</span>: [
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Deadlifts"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">10</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Dumbbell Row"</span>
                    }
                ]
            }
        ],
        <span class="hljs-attr">"b"</span>: [
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Leg"</span>,
                <span class="hljs-attr">"exercises"</span>: [
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Air Squat"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Chair Squat"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Leg Press"</span>
                    }
                ]
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Biceps"</span>,
                <span class="hljs-attr">"exercises"</span>: [
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">5</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Barbell Curl"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">6</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Cable Curl With Bar"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">7</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Spider Curl"</span>
                    }
                ]
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Triceps"</span>,
                <span class="hljs-attr">"exercises"</span>: [
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">8</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Bench Dip"</span>
                    },
                    {
                        <span class="hljs-attr">"id"</span>: <span class="hljs-number">9</span>,
                        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Close-Grip Push-Up"</span>
                    }
                ]
            }
        ]
    }
}
</code></pre>
<h3 id="heading-sorting">Sorting</h3>
<p>Ordering results of a query dynamically is a common case. With Hot Chocolate sorting, we can expose a sorting argument that abstracts the complexity of ordering logic. With a little configuration, the GraphQL API has sorting capabilities, translating to native database queries.</p>
<p>It is also necessary to register it and then use the attribute in the method inside of the query.</p>
<pre><code class="lang-csharp">builder.Services
    .AddGraphQLServer()
    .RegisterService&lt;MuscleService&gt;()
    .RegisterService&lt;ExerciseService&gt;()
    .AddType&lt;MuscleType&gt;()
    .AddQueryType&lt;Query&gt;()
    .AddFiltering()
    .AddSorting();
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Query</span>
{
    [<span class="hljs-meta">UseFiltering</span>]
    [<span class="hljs-meta">UseSorting</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IEnumerable&lt;MuscleDto&gt; <span class="hljs-title">GetMuscles</span>(<span class="hljs-params">MuscleService service</span>)</span>
    {
        <span class="hljs-keyword">return</span> service.GetAll();
    }

    [<span class="hljs-meta">UseFiltering</span>]
    [<span class="hljs-meta">UseSorting</span>]
    <span class="hljs-function"><span class="hljs-keyword">public</span> IEnumerable&lt;ExerciseDto&gt; <span class="hljs-title">GetExercises</span>(<span class="hljs-params">ExerciseService service</span>)</span>
    {
        <span class="hljs-keyword">return</span> service.GetAll();
    }
}
</code></pre>
<p>We use the tag order to define the list of fields and the ordering we want to order a query.</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> {
    muscles(<span class="hljs-symbol">order:</span> [{ <span class="hljs-symbol">name:</span> ASC }]) {
        id,
        name
    }
}
</code></pre>
<pre><code class="lang-json">{
    <span class="hljs-attr">"data"</span>: {
        <span class="hljs-attr">"muscles"</span>: [
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Back"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Biceps"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Leg"</span>
            },
            {
                <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
                <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Triceps"</span>
            }
        ]
    }
}
</code></pre>
<h2 id="heading-mutation">Mutation</h2>
<p>As we saw, mutations are used to modify data on the server. GraphQL defines mutations as top-level fields on the mutation type. Meaning only the fields on the mutation root type itself are mutations. Everything that is returned from a mutation field represents the changed state of the server.</p>
<p>In GraphQL, it is best practice to have a single argument on mutations called <code>input</code>, and each mutation should return a payload object. The payload object allows to read the changes of the mutation or to access the domain errors caused by a mutation.</p>
<p>The following code shows the mutation type for Muscle and the methods that we will allow to be executed. It also defined the Input and the Payload types for each one of the methods.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Mutation</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;MusclePayload&gt; <span class="hljs-title">AddMuscle</span>(<span class="hljs-params">AddMuscleInput input, MuscleService service</span>)</span>
    {
        <span class="hljs-keyword">var</span> muscle = <span class="hljs-keyword">new</span> MuscleDto
        {
            Name = input.Name
        };

        <span class="hljs-keyword">var</span> savedMuscle = <span class="hljs-keyword">await</span> service.Create(muscle);

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> MusclePayload(savedMuscle);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;MusclePayload&gt; <span class="hljs-title">UpdateMuscle</span>(<span class="hljs-params">UpdateMuscleInput input, MuscleService service</span>)</span>
    {
        <span class="hljs-keyword">var</span> muscle = <span class="hljs-keyword">new</span> MuscleDto
        {
            Id = input.Id,
            Name = input.Name            
        };

        <span class="hljs-keyword">var</span> updateMuscle = <span class="hljs-keyword">await</span> service.Update(muscle);

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> MusclePayload(updateMuscle);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;MusclesPayload&gt; <span class="hljs-title">DeleteMuscle</span>(<span class="hljs-params">DeleteMuscleInput input, MuscleService service</span>)</span>
    {
        <span class="hljs-keyword">var</span> muscle = <span class="hljs-keyword">new</span> MuscleDto
        {
            Id = input.Id          
        };

        <span class="hljs-keyword">await</span> service.Delete(muscle);

        <span class="hljs-keyword">var</span> muscles = service.GetAll();

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> MusclesPayload(muscles);
    }
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">CoachPlan.GraphQL.Features.Muscle</span>;

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">AddMuscleInput</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> Name</span>)</span>; 

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">UpdateMuscleInput</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> Id, <span class="hljs-keyword">string</span> Name</span>)</span>; 

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">DeleteMuscleInput</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> Id</span>)</span>; 

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">MusclePayload</span>(<span class="hljs-params">MuscleDto muscle</span>)</span>;

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">MusclesPayload</span>(<span class="hljs-params">IEnumerable&lt;MuscleDto&gt; muscle</span>)</span>;
</code></pre>
<p>Like the other functionalities, it is necessary to register the Mutation type.</p>
<pre><code class="lang-csharp">builder.Services
    .AddGraphQLServer()
    .RegisterService&lt;MuscleService&gt;()
    .RegisterService&lt;ExerciseService&gt;()
    .AddType&lt;MuscleType&gt;()
    .AddType&lt;ExerciseType&gt;()
    .AddQueryType&lt;Query&gt;()
    .AddMutationType&lt;Mutation&gt;()
    .AddFiltering()
    .AddSorting();
</code></pre>
<p>The following images show the execution of the Mutation's methods.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684203297074/fb716151-35f0-4a91-9de9-46eeded217f8.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684203430271/c338d163-460c-4913-83d7-a20e9f9ab9da.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684203486118/cd58a86a-e675-4eb2-8d09-ad942c5a0fdd.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>There are more features we can use with GraphQL, and this blog post was just an introduction to learn the basics of it.</p>
<p>You can find the complete code on my <a target="_blank" href="https://github.com/jhonatanfernando/coachplan"><strong>GitHub</strong></a><strong>.</strong></p>
]]></content:encoded></item><item><title><![CDATA[Asp.Net Core Apps: A Guide to Observability - Part 1]]></title><description><![CDATA[Observability is a key concept in modern software development. It refers to the ability of a system to be monitored, measured, and understood in order to…]]></description><link>https://blog.jhonatanoliveira.dev/aspnet-core-apps-a-guide-to-observability-part-1</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/aspnet-core-apps-a-guide-to-observability-part-1</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[observability]]></category><category><![CDATA[logging]]></category><category><![CDATA[metrics]]></category><category><![CDATA[tracing]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Mon, 27 Mar 2023 22:31:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/y7GlIdTUOvo/upload/12f98e6d3f4ffa2f84ecb50fab86a322.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Observability is a key concept in modern software development. It refers to the ability of a system to be monitored, measured, and understood in order to identify and address issues. In the context of <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core, observability can help developers and operations teams diagnose and fix application issues quickly and efficiently.</p>
<p>In this blog post, we'll explore what observability means in the context of <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core, its benefits, and how we can implement observability in our <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core applications.</p>
<h1 id="heading-what-is-observability">What is observability?</h1>
<p>Observability is a term used to describe the ability to measure and understand the internal workings of a system. In software development, observability refers to the ability to measure and understand the behaviour of an application to diagnose and fix issues.</p>
<p>Observability is typically achieved through the use of telemetry data. Telemetry data is a set of measurements and events collected from an application and used to gain insights into its behaviour. Telemetry data can include information about performance, errors, exceptions, and other key metrics.</p>
<h1 id="heading-benefits-of-observability">Benefits of observability</h1>
<p>Observability provides several benefits to developers and operations teams. Here are some of the key benefits:</p>
<ol>
<li><p>Faster Issue Resolution - Collecting and analyzing telemetry data can quickly identify and resolve issues. This can help reduce downtime and improve the application's overall performance.</p>
</li>
<li><p>Improved Performance - Observability can help identify performance bottlenecks and other issues that may be impacting the application's performance. This can help to optimize the application and improve its overall performance.</p>
</li>
<li><p>Better User Experience - Observability can help identify issues that may impact the user experience. By resolving these issues, the user experience can be improved.</p>
</li>
</ol>
<h1 id="heading-implementing-observability">Implementing observability</h1>
<p><a target="_blank" href="http://ASP.NET">ASP.NET</a> Core provides several features that can be used to implement observability in our applications. Here are some of the key features:</p>
<ol>
<li><p>Logging - <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core provides a built-in logging framework that can be used to collect telemetry data. This framework can be used to log information about performance, errors, exceptions, and other key metrics.</p>
</li>
<li><p>Application Insights - Application Insights is a cloud-based telemetry service that can be used to monitor and analyze the behaviour of our application. We can use Application Insights to collect telemetry data and gain insights into the behaviour of our application.</p>
</li>
<li><p>Metrics - <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core provides a metrics framework that can be used to collect and analyze performance metrics. We can use this metrics framework to collect metrics such as CPU usage, memory usage, and request latency.</p>
</li>
<li><p>Tracing - <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core provides a tracing framework that can be used to collect and analyze traces of our application. We can use tracing to understand the flow of requests through our application and identify issues that may be impacting performance.</p>
</li>
</ol>
<h2 id="heading-logging">Logging</h2>
<p>Logging is an essential part of any software application, including <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications. Logging allows developers to collect and analyze information about the application's behaviour, which can help them identify issues, troubleshoot bugs, and improve performance. Here are some examples of popular logging frameworks that can be used in <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications:</p>
<ol>
<li><p>Serilog Serilog is a popular logging framework that is designed to be fast, flexible, and easy to use. It provides various features for logging structured and unstructured data, including support for structured logging, log enrichment, and filtering. Serilog also provides integrations with other technologies, such as Elasticsearch and Seq.</p>
</li>
<li><p>NLog NLog is a flexible and extensible logging framework that can be used to log messages to various destinations, including files, databases, and email. NLog provides a variety of features for logging structured and unstructured data, including support for log levels, targets, and layouts. NLog also provides integrations with a variety of other technologies, such as Log4net and <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core.</p>
</li>
<li><p>Log4net is a mature and widely used logging framework that can be used to log messages to various destinations, including files, databases, and email. Log4net provides a variety of features for logging structured and unstructured data, including support for log levels, appenders, and patterns. Log4net also provides integrations with a variety of other technologies, such as NLog and <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core.</p>
</li>
<li><p>Microsoft.Extensions.Logging Microsoft.Extensions.Logging is a logging framework that is built into <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core. It provides a simple and flexible API for logging messages to various destinations, including the console, files, and databases. Microsoft.Extensions.Logging also provides a variety of features for logging structured and unstructured data, including support for log levels, scopes, and providers. It is easy to use and can be configured through the application's configuration files.</p>
</li>
</ol>
<p>These are just a few examples of the many logging frameworks that are available for <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications. The choice of logging framework will depend on our specific requirements, such as the type of logging we need to do, the scalability of the framework, and the integration options available.</p>
<h2 id="heading-application-insights">Application Insights</h2>
<p>Application Insights is a comprehensive application performance monitoring and management service offered by Microsoft Azure. It is designed to help developers and IT professionals monitor, diagnose, and improve the performance and availability of the applications, including <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications.</p>
<p>Here are some key features of Application Insights:</p>
<ol>
<li><p>Performance Monitoring: Application Insights can monitor the performance of the <a target="_blank" href="http://ASP.NET">ASP.NET</a> application in real-time, including response times, availability, and server performance. It can also help us identify performance bottlenecks and optimize the performance of your application.</p>
</li>
<li><p>Error Monitoring: Application Insights can monitor the errors and exceptions that occur in your <a target="_blank" href="http://ASP.NET">ASP.NET</a> application and provide detailed diagnostic information, including the stack trace, request details, and custom properties. It can also help us prioritize and address errors that impact the application's performance.</p>
</li>
<li><p>Dependency Tracking: Application Insights can track the dependencies the <a target="_blank" href="http://ASP.NET">ASP.NET</a> application relies on, such as databases, external APIs, and services. It can help you understand how these dependencies impact the performance and availability of the application and identify any issues that arise.</p>
</li>
<li><p>Analytics and Dashboards: Application Insights provides powerful analytics and dashboarding tools that can help us visualize and analyze the performance and usage data collected by the service. We can use these tools to identify trends, monitor key metrics, and make data-driven decisions about the application.</p>
</li>
<li><p>Integration with Azure: Application Insights is tightly integrated with Microsoft Azure, which means we can use it to monitor and manage your <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications deployed on Azure. It also integrates with a variety of other Azure services, such as Azure Functions, Azure Kubernetes Service, and Azure DevOps.</p>
</li>
</ol>
<p>Overall, Application Insights is a powerful and comprehensive tool for monitoring and managing the performance and availability of <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications. It provides developers and IT professionals with the tools they need to diagnose and address issues, optimize performance, and improve the user experience.</p>
<h2 id="heading-metrics">Metrics</h2>
<p>A metrics framework is a tool or library that allows developers to collect and analyze metrics about the performance and behaviour of an application. Metrics frameworks can be used to track a wide range of data points, such as response times, error rates, and resource usage.</p>
<p>Here are some popular metrics frameworks that can be used in <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications:</p>
<ol>
<li><p>Prometheus is an open-source metrics framework widely used in cloud-native environments. It provides a flexible data model, a powerful query language, and a variety of integrations with other technologies. Prometheus can be used to collect metrics from <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications, including performance metrics, error rates, and resource usage.</p>
</li>
<li><p>StatsD is a lightweight metrics framework designed to be easy to use and highly configurable. It provides a simple protocol for sending metrics from an application to a StatsD server, which can then be used to store, analyze, and visualize the metrics data. StatsD can collect metrics from <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications, including request/response times, error rates, and custom application-specific metrics.</p>
</li>
<li><p>InfluxDB is a time-series database that is designed to store and analyze large volumes of metrics data. It provides a powerful query language, a flexible data model, and a variety of integrations with other technologies. InfluxDB can store metrics data collected from <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications, including performance metrics, error rates, and resource usage.</p>
</li>
<li><p>Graphite is a metrics framework designed to be highly scalable and easy to use. It provides a simple protocol for sending metrics from an application to a Graphite server, which can then be used to store, analyze, and visualize the metrics data. Graphite can collect metrics from <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications, including request/response times, error rates, and custom application-specific metrics.</p>
</li>
</ol>
<p>These are just a few examples of the many metrics frameworks that are available for <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications.</p>
<h2 id="heading-tracing">Tracing</h2>
<p>Tracing is the process of recording and following the flow of requests or transactions as they move through a system. In software development, tracing is often used to diagnose and troubleshoot performance issues or errors within an application.</p>
<p>Tracing typically involves adding code to an application that records information about each request or transaction as it progresses through the system. This information can include things like the duration of each step, the components involved in processing the request, and any errors or exceptions.</p>
<p>Here are some popular tracing frameworks that can be used in <a target="_blank" href="http://ASP.NET">ASP.NET</a> applications:</p>
<ol>
<li><p>OpenTelemetry is an open-source project that provides a set of tools and libraries for collecting and exporting trace data. It is designed to be vendor-neutral and supports various languages and platforms, including <a target="_blank" href="http://ASP.NET">ASP.NET</a>. OpenTelemetry can be used to trace requests as they move through an <a target="_blank" href="http://ASP.NET">ASP.NET</a> application, providing detailed information about the performance and behaviour of the application.</p>
</li>
<li><p>Jaeger is an open-source tracing framework widely used in cloud-native environments. It provides a powerful query language and a variety of integrations with other technologies. Jaeger can be used to trace requests as they move through an <a target="_blank" href="http://ASP.NET">ASP.NET</a> application, providing detailed information about the performance and behaviour of the application.</p>
</li>
<li><p>Zipkin is an open-source tracing framework designed to be easy to use and highly configurable. It provides a simple protocol for sending trace data from an application to a Zipkin server, which can then be used to store, analyze, and visualize the trace data. Zipkin can be used to trace requests as they move through an <a target="_blank" href="http://ASP.NET">ASP.NET</a> application, providing detailed information about the performance and behaviour of the application.</p>
</li>
</ol>
<p>Tracing can be a powerful tool for diagnosing and troubleshooting issues within an application. By tracing requests as they move through the system, developers can better understand the application's performance and behaviour and identify areas for improvement.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Observability is an essential aspect of modern software development, and <a target="_blank" href="http://ASP.NET">ASP.NET</a> provides several frameworks that can be used to implement observability in our applications. Using these frameworks, we can gain insights into the application's behaviour, identify issues more quickly, and provide a better user experience. The logging framework, Application Insights, metrics framework, and tracing framework are some key frameworks we can use for observability in <a target="_blank" href="http://ASP.NET">ASP.NET</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Blazor - Part 1: Getting Started]]></title><description><![CDATA[Blazor is a web framework from Microsoft that allows developers to build interactive web applications using C# and HTML. With Blazor, we can create web…]]></description><link>https://blog.jhonatanoliveira.dev/introduction-to-blazor-part-1-getting-started</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/introduction-to-blazor-part-1-getting-started</guid><category><![CDATA[C#]]></category><category><![CDATA[Blazor]]></category><category><![CDATA[WebAssembly]]></category><category><![CDATA[asp.net core]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Tue, 07 Mar 2023 12:59:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/VieM9BdZKFo/upload/49260468bd11137c98a5c442e03a798c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction-to-blazor">Introduction to Blazor</h1>
<p>Blazor is a web framework from Microsoft that allows developers to build interactive web applications using C# and HTML. With Blazor, we can create web applications that run entirely in the browser without the need for plugins or code running on the server.</p>
<h2 id="heading-blazor-webassemby">Blazor WebAssemby</h2>
<p>Blazor uses WebAssembly to execute .NET code in the browser, meaning we can write client-side code in C# instead of JavaScript. This makes writing and maintaining code easier, as we can use the same language on both the client and server.</p>
<p>Blazor WebAssembly is a client-side hosting model where the entire Blazor application is downloaded to the client's browser and executed directly in the browser's WebAssembly runtime. This means that the application runs entirely on the client side and does not require any communication with the server during runtime. This hosting model is ideal for building highly interactive and responsive applications requiring minimal server communication.</p>
<h2 id="heading-blazor-server">Blazor Server</h2>
<p>Blazor also supports server-side rendering, which allows developers to build web applications that can run on the server and be rendered in the browser. This can improve the performance of web applications, as the server can handle some processing and rendering.</p>
<p>Blazor Server is a server-side hosting model where the Blazor application is executed on the server, and the UI is rendered in the client's browser using SignalR. In this model, the client sends UI events to the server, and the server processes them and sends back the updated UI to the client. This hosting model is ideal for building applications that require real-time updates and can handle large amounts of data.</p>
<h1 id="heading-creating-a-new-blazor-application">Creating a new Blazor application</h1>
<p>To create a new Blazor application, we can select "Create a new project" and search for blazor project templates. For this demo, we will create a Blazor WebAssembly App.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678144866284/d5c95a01-60a7-44c9-b271-748c3f60d9a1.png" alt class="image--center mx-auto" /></p>
<p>After defining the name and location of the project, another window will be displayed where we can choose some configurations.</p>
<p>One of these configurations is <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core Hosted. It is a project template in Visual Studio that provides a solution structure for building a Blazor application hosted on the server side. This template includes three projects: a client project, a server project, and a shared project.</p>
<p>We will only check the Configure for the HTTPS box for this demo.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678145142773/92b95d60-382a-4d99-8f8c-1a789505544d.png" alt class="image--center mx-auto" /></p>
<p>Once the application is created, we can start building the UI and adding functionality to the application. We can use C# to write the client-side and server-side code and HTML and CSS to create the UI. We can also use third-party libraries and frameworks to enhance the application's functionality and appearance.</p>
<p>The following image shows the default layout of the Blazor App.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678146251531/149758f7-dedb-4e1c-b03d-41d81f64f4e4.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-understanding-the-blazor-project-structure">Understanding the Blazor project structure</h2>
<p>When the Blazor application is created, it will have a project structure that includes several folders and files. Here's a brief overview of the most important files and folders in a Blazor project:</p>
<ul>
<li><p><strong>App.razor</strong>: is a special Razor component in a Blazor application that serves as the application's root component. It is the entry point for the application and is responsible for rendering the UI of the application. It contains a <code>Router</code> component that handles navigation within the application.</p>
</li>
<li><p><strong>_Imports.razor:</strong> is a special file in a Blazor application that defines global namespace imports for the application. It is located in the project's root directory and is automatically created when a new Blazor application is created. Any namespace added to this file will be available for use in all Razor components in the project. This can be useful for reducing the amount of code required to import namespaces in each component.</p>
</li>
<li><p><strong>Pages</strong>: This folder contains the Razor components that define the UI of the application. Each Razor component is a combination of HTML and C# code that defines a part of the UI.</p>
</li>
<li><p><strong>Shared</strong>: This folder contains Razor components that can be used across multiple pages in the application.</p>
</li>
<li><p><strong>wwwroot</strong>: This folder contains static files that will be served to the client, such as HTML, CSS, and JavaScript files.</p>
</li>
<li><p><strong>Program.cs</strong>: This file contains the application's services and middleware configuration.</p>
</li>
</ul>
<h1 id="heading-creating-a-basic-blazor-component">Creating a basic Blazor component</h1>
<p>The <code>FetchData.razor</code> page lists the weather forecast reading the data from a JSON file. Let's create a new Blazor component that calls an API's endpoint to get the data.</p>
<h2 id="heading-service">Service</h2>
<p>To call the API, let's create a service responsible for that. First, we will add a folder called Services in the Blazor project and then create the <code>MuscleService</code> class that will implement the interface <code>IMuscleService</code>, defined in the Domain project of the solution.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MuscleService</span>: <span class="hljs-title">IMuscleService</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> HttpClient httpClient;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MuscleService</span>(<span class="hljs-params">HttpClient httpClient</span>)</span>
    {
        <span class="hljs-keyword">this</span>.httpClient = httpClient;
    }   

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;GetMuscleDto&gt;&gt; GetAll()
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> httpClient.GetFromJsonAsync&lt;GetMuscleDto[]&gt;(<span class="hljs-string">"/muscles"</span>);
    }
}
</code></pre>
<p>The class is receiving the <code>HttpClient</code> by injection so that the API calls can be made using it.</p>
<p>To configure the base address of the API, the following code will be added to the <code>Program.cs</code> file of the Blazor project.</p>
<pre><code class="lang-csharp">builder.Services.AddHttpClient&lt;IMuscleService, MuscleService&gt;(client =&gt;
{
    client.BaseAddress = <span class="hljs-keyword">new</span> Uri(<span class="hljs-string">"https://localhost:7218/"</span>);
});
</code></pre>
<h2 id="heading-blazor-component">Blazor component</h2>
<p>Inside the folder Pages, let's add a new blazor component called <code>Muscles.razor</code>.</p>
<p>In this component, we will use the <code>IMuscleService</code> to get the data and show it inside an HTML table.</p>
<p>The following code shows the complete code of the component.</p>
<pre><code class="lang-csharp">@page <span class="hljs-string">"/muscles"</span>
@inject IMuscleService muscleService

&lt;PageTitle&gt;Muscles&lt;/PageTitle&gt;

&lt;h1&gt;Muscles&lt;/h1&gt;

@if (muscles == <span class="hljs-literal">null</span>)
{
    &lt;p&gt;&lt;em&gt;Loading...&lt;/em&gt;&lt;/p&gt;
}
<span class="hljs-keyword">else</span>
{
    &lt;table <span class="hljs-keyword">class</span>=<span class="hljs-string">"table"</span>&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;Id&lt;/th&gt;
                &lt;th&gt;Name&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
            @foreach (<span class="hljs-keyword">var</span> muscle <span class="hljs-keyword">in</span> muscles)
            {
                &lt;tr&gt;
                    &lt;td&gt;@muscle.Id&lt;/td&gt;
                    &lt;td&gt;@muscle.Name&lt;/td&gt;
                &lt;/tr&gt;
            }
        &lt;/tbody&gt;
    &lt;/table&gt;
}


@code {
    <span class="hljs-keyword">private</span> IEnumerable&lt;GetMuscleDto&gt;? muscles;

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">OnInitializedAsync</span>(<span class="hljs-params"></span>)</span>
    {
        muscles = <span class="hljs-keyword">await</span> muscleService.GetAll();
    }
}
</code></pre>
<p>Let's discuss some of the elements used in this component.</p>
<p><code>@page</code> is a directive in Blazor that defines a Razor component as a page in the application. When a Razor component is marked with the <code>@page</code> directive, Blazor will generate a URL for the component, which will be accessible via that URL.</p>
<p><code>@inject</code> is a directive in Blazor that is used to inject services into a Razor component. When we use the <code>@inject</code> directive, Blazor will automatically create an instance of the specified service and make it available in the component.</p>
<p><code>@code</code> is a directive in Blazor that is used to define the C# code for a Razor component. Using the <code>@code</code>directive, we can define C# code directly in the Razor component without creating a separate code-behind file.</p>
<p><code>OnInitializedAsync</code> is a lifecycle method in Blazor called when a component is initialized. This method is called after the component has been constructed and all its dependencies have been injected before it is rendered. We can use the <code>OnInitializedAsync</code> method to perform any initialization tasks that the component requires, such as loading data from a server or initializing state variables. The <code>OnInitializedAsync</code> method has an asynchronous signature, which means it can perform asynchronous operations such as making HTTP requests.</p>
<p>Now, let's add a new menu item in <code>NavMenu.razor</code> file that will call the new blazor component that we created.</p>
<pre><code class="lang-javascript">        &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"nav-item px-3"</span>&gt;
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">NavLink</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-link"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"muscles"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"oi oi-list-rich"</span> <span class="hljs-attr">aria-hidden</span>=<span class="hljs-string">"true"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span> Muscles
            <span class="hljs-tag">&lt;/<span class="hljs-name">NavLink</span>&gt;</span></span>
        &lt;/div&gt;
</code></pre>
<p>We can see the new menu item and open the new page by running the application.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678154160573/274494f2-7626-4bd9-8986-8ca7769855d6.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678154186275/7a92399e-d927-48c7-962e-ac3536f5f219.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>This was the first part of building the first blazor application. Next, let's add a popup page and do some refactoring in the code.</p>
<p>You can find the complete code on my <a target="_blank" href="https://github.com/jhonatanfernando/coachplan"><strong>GitHub</strong></a>.</p>
]]></content:encoded></item><item><title><![CDATA[Using Redis for caching in Asp.Net Core]]></title><description><![CDATA[In this previous article, we learned about caching in Asp.Net Core. We talked about In-Memory cache and Distributed cache using SQL Server cache. This…]]></description><link>https://blog.jhonatanoliveira.dev/using-redis-for-caching-in-aspnet-core</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/using-redis-for-caching-in-aspnet-core</guid><category><![CDATA[Azure]]></category><category><![CDATA[Redis]]></category><category><![CDATA[caching]]></category><category><![CDATA[asp.net core]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sun, 19 Feb 2023 13:57:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/1SAnrIxw5OY/upload/9bf130d9739e79c0a54fb2247ca9bbf1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this previous <a target="_blank" href="https://blog.jhonatanoliveira.dev/using-caching-in-aspnet-core-minimal-apis">article</a>, we learned about caching in Asp.Net Core. We talked about In-Memory cache and Distributed cache using SQL Server cache.</p>
<p>This article will discuss how to use Redis for caching in Asp.Net Core.</p>
<h1 id="heading-what-is-redis">What is Redis?</h1>
<p>Redis (<strong>RE</strong>mote <strong>DI</strong>ctionary <strong>S</strong>erver) is an open-source, high-performance, in-memory that allows us to store and retrieve data in our applications.</p>
<p>Used primarily as a database, cache, or message broker, it also supports several data structures such as hashes, lists, sets, sorted sets, bitmaps and others.</p>
<h1 id="heading-azure-cache-for-redis">Azure Cache for Redis</h1>
<p>Azure Cache for Redis provides an in-memory data store based on the Redis software. Redis improves the performance and scalability of an application that uses backend data stores heavily. It can process large volumes of application requests by keeping frequently accessed data in the server memory, which can be written to and read from quickly.</p>
<p>Azure Cache for Redis can be deployed as a standalone or with other Azure database services, such as Azure SQL or Azure Cosmos DB.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676742308238/c47418f2-c04f-4495-9a98-1b85eea442d1.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-configure-azure-cache-for-redis">Configure Azure Cache for Redis</h2>
<p>To create a new Azure Cache for Redis, first, we need to sign in to the <a target="_blank" href="https://portal.azure.com/">Azure portal</a>. You can create one for <a target="_blank" href="https://azure.microsoft.com/en-us/free/">free</a> if you don't have an account. After that, click on <strong>Create a resource</strong> and then <strong>Compute.</strong> You should see the item <strong>Azure Cache for Redis.</strong> The following image shows what you should see.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676743580138/93b6c617-598c-48bb-b195-471350461c81.png" alt class="image--center mx-auto" /></p>
<p>In the <strong>New Redis Cache</strong> page, we need to specify the subscription plan, the resource group, the DNS name, the server location for using Redis, and the cache type. Please feel free to use the following image for reference.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676743708234/80e8ea5e-1ec5-4a90-97fc-732af637f75d.png" alt class="image--center mx-auto" /></p>
<p>In the <strong>Advanced</strong> tab, we can define the Redis version to be used. After that, we can click on <strong>Review + Create</strong> to create the Redis resource in Azure.</p>
<h1 id="heading-implementation">Implementation</h1>
<p>First, we need to install the NuGet package <a target="_blank" href="https://www.nuget.org/packages/Microsoft.Extensions.Caching.StackExchangeRedis">Microsoft.Extensions.Caching.StackExchangeRedis</a>, and then we can register the Redis in our services.</p>
<pre><code class="lang-csharp">builder.Services.AddStackExchangeRedisCache(opt =&gt;
{
    opt.Configuration = builder.Configuration.GetConnectionString(<span class="hljs-string">"Redis"</span>);
});
</code></pre>
<p>We will need the string connection of the Redis in Azure. We need to access the resource and click on the link for <strong>Access Keys</strong>, the image below shows where you can find the links.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676763056311/3a463996-9f5e-42ee-8a09-080f180fdf5f.png" alt class="image--center mx-auto" /></p>
<p>The next step is to define the connection string in the <code>appsettings.json</code> file.</p>
<pre><code class="lang-json">  <span class="hljs-string">"ConnectionStrings"</span>: {
    <span class="hljs-attr">"DefaultConnection"</span>: <span class="hljs-string">"Server=localhost\\MSSQLSERVER01; Database=CoachPlan; Trusted_Connection=True; MultipleActiveResultSets=true"</span>,
    <span class="hljs-attr">"Redis"</span>: <span class="hljs-string">"Add the Primary connection string here."</span>
  },
</code></pre>
<p>Now, we are going to change the implementation of our services. The package that we are using contains the implementation of the <code>IDistributedCache</code> interface so that we can inject this interface into our services.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMuscleRepository _muscleRepository;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IDistributedCache _distributedCache;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> JsonSerializerSettings _jsonSerializerSettings;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MuscleService</span>(<span class="hljs-params">IMuscleRepository muscleRepository, IDistributedCache distributedCache</span>)</span>
    {
        _muscleRepository = muscleRepository;
        _distributedCache = distributedCache;

        _jsonSerializerSettings = <span class="hljs-keyword">new</span>()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };
    }
</code></pre>
<p>The following code shows the implementation of the <code>GetById</code> method. So, before going to the database to get the data, we verify if it is cached and then return it; otherwise, the data will be fetched from the database and cached.</p>
<p>To get the cached data, we need to use the method <code>GetStringAsync</code> which will return the <code>Json</code> of the cached data if it exists.</p>
<p>To send the data to Redis, we use the method <code>SetStringAsync,</code> which uses the data we want to cache as a parameter.</p>
<pre><code class="lang-csharp">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;GetMuscleDto&gt; <span class="hljs-title">GetById</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>
    {
        <span class="hljs-keyword">string</span> key = <span class="hljs-string">$"muscle-<span class="hljs-subst">{id}</span>"</span>;

        <span class="hljs-keyword">string</span> cachedMuscle = <span class="hljs-keyword">await</span> _distributedCache.GetStringAsync(key);

        Muscle muscle = <span class="hljs-literal">null</span>;

        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">string</span>.IsNullOrEmpty(cachedMuscle))
        {
            muscle = <span class="hljs-keyword">await</span> _muscleRepository.GetById(id);

            <span class="hljs-keyword">if</span> (muscle <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">await</span> _distributedCache.SetStringAsync(key, JsonConvert.SerializeObject(muscle, _jsonSerializerSettings));
            }
        }
        <span class="hljs-keyword">else</span>
        {
            muscle = JsonConvert.DeserializeObject&lt;Muscle&gt;(cachedMuscle);
        }

        <span class="hljs-keyword">return</span> muscle.ToGetDto();
    }
</code></pre>
<p>In case we want to use the cache expiration, we have two options:</p>
<ol>
<li><p>Absolute expiration means no matter the frequency of accessing cached data, and it will be removed after a fixed time.</p>
</li>
<li><p>Sliding expiration provides a way to remove the cached data which are not frequently accessed. If an object's sliding expiration of 30 seconds is enabled, it will expire only if the data was not accessed in the last 30 seconds.</p>
</li>
</ol>
<p>We can create an instance of <code>DistributedCacheEntryOptions</code> and define the type of cache expiration we want to use. The following code shows how to create and use the instance in the method <code>SetStringAsync</code>.</p>
<pre><code class="lang-csharp"> <span class="hljs-keyword">var</span> expiration = <span class="hljs-keyword">new</span> DistributedCacheEntryOptions
 {
    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(<span class="hljs-number">30</span>),
    SlidingExpiration = TimeSpan.FromSeconds(<span class="hljs-number">25</span>)
 };

 <span class="hljs-keyword">await</span> _distributedCache.SetStringAsync(key, JsonConvert.SerializeObject(muscles, _jsonSerializerSettings), expiration);
</code></pre>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>If you don't need more Azure Cache for Redis, remember to delete it in the Azure Portal.</p>
<p>You can find the complete code on my <a target="_blank" href="https://github.com/jhonatanfernando/coachplan"><strong>GitHub</strong></a>.</p>
]]></content:encoded></item><item><title><![CDATA[Using Rate Limiting in Asp.Net Core Minimal APIs]]></title><description><![CDATA[In this blog post will learn about Rate Limiting and how we can implement it in Asp.net Core Minimal API. Rate limiting is the process of limiting how much…]]></description><link>https://blog.jhonatanoliveira.dev/using-rate-limiting-in-aspnet-core-minimal-apis</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/using-rate-limiting-in-aspnet-core-minimal-apis</guid><category><![CDATA[C#]]></category><category><![CDATA[APIs]]></category><category><![CDATA[ratelimit]]></category><category><![CDATA[minimal-apis]]></category><category><![CDATA[asp.net core]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sun, 29 Jan 2023 19:01:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/_UeY8aTI6d0/upload/337402d6602bb732c9e35ce5fd1a90d9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog post will learn about Rate Limiting and how we can implement it in Asp.net Core Minimal API.</p>
<h1 id="heading-rate-limiting">Rate Limiting</h1>
<h2 id="heading-what-is-it">What is it?</h2>
<p>Rate limiting is the process of limiting how much a resource can be accessed. In the APIs environment, we can define a rate limiter that allows 100 requests every minute and rejects any more requests until restarting the counter again.</p>
<h2 id="heading-how-does-it-work">How does it work?</h2>
<p>Rate limiting is based on tracking the client IP where the requests are sent from and monitoring how much time elapses between each request.</p>
<p>The rate-limiting middleware measures the time between each request from the client IP and the number of requests within a specified rule. If the application gets too many requests from a single client IP in the defined period, the rate-limiting middleware will only allow the request from the client once the reset point is reached. Usually, this will be displayed in the response header to the client.</p>
<h2 id="heading-what-are-the-benefits-of-using-rate-limiting">What are the benefits of using Rate Limiting?</h2>
<p>Using rate limiting can motivate third-party developers to pay more to use our API(s).</p>
<p>Another benefit of implementing rate limiting is to protect our API against malicious bot attacks.</p>
<h1 id="heading-implementation">Implementation</h1>
<p>First, it is necessary to install the nugget package <a target="_blank" href="https://www.nuget.org/packages/AspNetCoreRateLimit">AspNetCoreRateLimit</a>. After we need to do some configurations:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// needed to store rate limit counters and ip rules</span>
builder.Services.AddMemoryCache();

<span class="hljs-comment">//load general configuration from appsettings.json</span>
builder.Services.Configure&lt;IpRateLimitOptions&gt;(builder.Configuration.GetSection(<span class="hljs-string">"IpRateLimiting"</span>));

<span class="hljs-comment">//load ip rules from appsettings.json</span>
builder.Services.Configure&lt;IpRateLimitPolicies&gt;(builder.Configuration.GetSection(<span class="hljs-string">"IpRateLimitPolicies"</span>));

<span class="hljs-comment">// inject counter and rules stores    </span>
builder.Services.AddInMemoryRateLimiting();

<span class="hljs-comment">// configuration (resolvers, counter key builders)</span>
builder.Services.AddSingleton&lt;IIpPolicyStore, MemoryCacheIpPolicyStore&gt;();
builder.Services.AddSingleton&lt;IRateLimitConfiguration, RateLimitConfiguration&gt;();
</code></pre>
<p>To use the middleware, we should use the following code. We need to register the middleware before any other components.</p>
<pre><code class="lang-csharp">app.UseIpRateLimiting();
</code></pre>
<p>We can add the rules in the <code>appsettings.json</code> file. The following code shows a basic sample of rules.</p>
<pre><code class="lang-json">  <span class="hljs-string">"IpRateLimitingSettings"</span>: {
    <span class="hljs-attr">"EnableEndpointRateLimiting"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"StackBlockedRequests"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"RealIpHeader"</span>: <span class="hljs-string">"X-Real-IP"</span>,
    <span class="hljs-attr">"ClientIdHeader"</span>: <span class="hljs-string">"X-ClientId"</span>,
    <span class="hljs-attr">"HttpStatusCode"</span>: <span class="hljs-number">429</span>,
    <span class="hljs-attr">"GeneralRules"</span>: [
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"10s"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">5</span>
      }
    ]
  }
</code></pre>
<p>Let's understand the rules that were defined in the <code>appsettings</code> file.</p>
<p><code>EnableEndpointRateLimiting</code> is set to <code>false,</code> and then the limits will apply globally, and only the rules that have as endpoint <code>*</code> will apply. For example, if we put a limit of five calls per ten seconds, any HTTP call to any endpoint will count towards that limit. If set to <code>true</code>, the client can call <code>{HTTP_METHOD}{PATH}</code> five times per ten seconds for each HTTP method (<strong>GET, POST, PUT, DELETE</strong>).</p>
<p>If <code>StackBlockedRequests</code> is set to <code>false</code>, rejected calls are not added to the throttle counter. If a client makes three requests per second and we've selected a limit of one call per second, other limits like per minute or per day counters will only record the first call, which wasn't blocked. If we want rejected requests to count toward the other limits, we must set <code>StackBlockedRequests</code> to <code>true</code>.</p>
<p>The <code>RealIpHeader</code> extracts the client IP when your Kestrel server is behind a reverse proxy. If the proxy uses a different header, then <code>X-Real-IP</code> uses this option to set it up.</p>
<p>The <code>ClientIdHeader</code> is used to extract the client id for whitelisting. If a client id is present in this header and matches a value specified in ClientWhitelist, then no rate limits are applied.</p>
<p>The rate limit values are displayed in the headers when an endpoint is called.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675004248740/054c47e1-5c38-4f53-9057-9904e411a65f.png" alt class="image--center mx-auto" /></p>
<p>The following image shows the results when the client exceeds the limit of calls.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675002545452/e2053e9e-9592-43da-8fa5-d150e1651411.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-rate-limit-general-rules">Rate Limit General Rules</h2>
<p>We can have multiple rules in our application, changing the endpoint, period and limit. We've defined in our settings for all the endpoints a limit of five calls in a period of ten seconds. The following code shows two rules for all the endpoints but with different limits and periods. The behaviour will depend on the property <code>StackBlockedRequests</code> if rejected calls are added or not to the throttle counter.</p>
<pre><code class="lang-json">    <span class="hljs-string">"GeneralRules"</span>: [
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"10s"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">5</span>
      },
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"10m"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">100</span>
      }
    ]
</code></pre>
<p>We also can define different settings per endpoint.</p>
<pre><code class="lang-json"><span class="hljs-string">"GeneralRules"</span>: [
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"get:/muscles"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"5s"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">3</span>
      },
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"get:/muscles/*"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1m"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">10</span>
      },
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"post:/muscles"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1m"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">3</span>
      }
    ]
</code></pre>
<p>The <code>EndpointWhitelist</code> property is used to define the endpoints with no limitations.</p>
<pre><code class="lang-json"><span class="hljs-string">"EndpointWhitelist"</span>: [ <span class="hljs-string">"get:/license"</span>, <span class="hljs-string">"*:/status"</span> ],
</code></pre>
<p>We can use the <code>ClientWhitelist</code> property to define the list of <code>X-ClientId</code> values with no limitations in calling the endpoints. For this, the <code>X-ClientId</code> should be present in the headers.</p>
<pre><code class="lang-json"><span class="hljs-string">"ClientWhitelist"</span>: [ <span class="hljs-string">"dev-id-1"</span>, <span class="hljs-string">"dev-id-2"</span> ],
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675006747283/29e8e277-0854-4bdd-88f7-8bb74bbc096a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-overriding-general-rules">Overriding General Rules</h3>
<p>The general rules can be overridden using the <code>IpRateLimitPolicies</code> settings. The IP field supports IP v4 and v6 values and ranges like <code>192.168.0.0/24</code>, <code>fe80::/10</code> or <code>192.168.0.0-192.168.0.255</code>.</p>
<p>To load the <code>IpRateLimitPolicies,</code> the following code should be registered.</p>
<pre><code class="lang-json">builder.Services.Configure&lt;IpRateLimitPolicies&gt;(builder.Configuration.GetSection(<span class="hljs-string">"IpRateLimitPolicies"</span>));

builder.Services.AddSingleton&lt;IIpPolicyStore, MemoryCacheIpPolicyStore&gt;();
</code></pre>
<pre><code class="lang-json"><span class="hljs-string">"IpRateLimitPolicies"</span>: {
    <span class="hljs-attr">"IpRules"</span>: [
      {
        <span class="hljs-attr">"Ip"</span>: <span class="hljs-string">"84.247.85.224"</span>,
        <span class="hljs-attr">"Rules"</span>: [
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1s"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">10</span>
          },
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"15m"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">200</span>
          }
        ]
      },
      {
        <span class="hljs-attr">"Ip"</span>: <span class="hljs-string">"192.168.3.22/25"</span>,
        <span class="hljs-attr">"Rules"</span>: [
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1s"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">5</span>
          },
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"15m"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">150</span>
          },
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"12h"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">500</span>
          }
        ]
      }
    ]
  }
</code></pre>
<h3 id="heading-client-rate-limiting">Client Rate Limiting</h3>
<p>We can have all the configurations we saw for the IP Rate for the Client Rate, so instead of creating settings for the IP address, we will use ClientId.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// configure client rate limiting middleware</span>
builder.Services.Configure&lt;ClientRateLimitOptions&gt;(builder.Configuration.GetSection(<span class="hljs-string">"ClientRateLimiting"</span>));
builder.Services.Configure&lt;ClientRateLimitPolicies&gt;(builder.Configuration.GetSection(<span class="hljs-string">"ClientRateLimitPolicies"</span>));
</code></pre>
<pre><code class="lang-json">  <span class="hljs-string">"ClientRateLimiting"</span>: {
    <span class="hljs-attr">"EnableEndpointRateLimiting"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"ClientIdHeader"</span>: <span class="hljs-string">"X-ClientId"</span>,
    <span class="hljs-attr">"HttpStatusCode"</span>: <span class="hljs-number">429</span>,
    <span class="hljs-attr">"EndpointWhitelist"</span>: [ <span class="hljs-string">"*:/api/values"</span>, <span class="hljs-string">"delete:/api/clients"</span>, <span class="hljs-string">"get:/"</span> ],
    <span class="hljs-attr">"ClientWhitelist"</span>: [ <span class="hljs-string">"cl-key-a"</span>, <span class="hljs-string">"cl-key-b"</span> ],
    <span class="hljs-attr">"GeneralRules"</span>: [
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1s"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">2</span>
      },
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1m"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">5</span>
      },
      {
        <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"post:/muscles"</span>,
        <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"5m"</span>,
        <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">3</span>
      },
    ]
  },

  <span class="hljs-string">"ClientRateLimitPolicies"</span>: {
    <span class="hljs-attr">"ClientRules"</span>: [
      {
        <span class="hljs-attr">"ClientId"</span>: <span class="hljs-string">"cl-key-1"</span>,
        <span class="hljs-attr">"Rules"</span>: [
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1s"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">10</span>
          },
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"get:/muscles"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1m"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">2</span>
          },
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"put:/muscles"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"5m"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">2</span>
          }
        ]
      },
      {
        <span class="hljs-attr">"ClientId"</span>: <span class="hljs-string">"cl-key-2"</span>,
        <span class="hljs-attr">"Rules"</span>: [
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"*"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1s"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">10</span>
          },
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"get:/muscles"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1m"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">0</span>
          },
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"post:/muscles"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"5m"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">50</span>
          }
        ]
      },
      {
        <span class="hljs-attr">"ClientId"</span>: <span class="hljs-string">"cl-key-3"</span>,
        <span class="hljs-attr">"Rules"</span>: [
          {
            <span class="hljs-attr">"Endpoint"</span>: <span class="hljs-string">"post:/muscles"</span>,
            <span class="hljs-attr">"Period"</span>: <span class="hljs-string">"1s"</span>,
            <span class="hljs-attr">"Limit"</span>: <span class="hljs-number">3</span>
          }
        ]
      }
    ]
  }
</code></pre>
<h2 id="heading-custom-rate-limit-configuration">Custom Rate Limit configuration</h2>
<p>The AspNetCoreRateLimit middleware supports customization in case we want to use a different header or the value we want to configure is present in the query.</p>
<p>For example, for this call, <code>https://localhost:7218/muscles?X-ClientId=dev-id-1,</code> even having the <code>dev-id-1</code> value as <code>ClientWhitelist</code>, the middleware would not apply the setting because it is expecting it as a header.</p>
<p>To customize, first, we need to create a class that inherits from <code>RateLimitConfiguration</code> class and then create another class that implements the interface <code>IClientResolveContributor</code> so we can get the value from the query parameters. We also need to add it in the <code>ClientResolvers</code> property of <code>CustomRateLimitConfiguration</code> class.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CustomRateLimitConfiguration</span> : <span class="hljs-title">RateLimitConfiguration</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CustomRateLimitConfiguration</span>(<span class="hljs-params">IOptions&lt;IpRateLimitOptions&gt; ipOptions, IOptions&lt;ClientRateLimitOptions&gt; clientOptions</span>) : <span class="hljs-title">base</span>(<span class="hljs-params">ipOptions, clientOptions</span>)</span>
    {
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">RegisterResolvers</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">base</span>.RegisterResolvers();
        ClientResolvers.Add(<span class="hljs-keyword">new</span> QueryStringClientIdResolveContributor());
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">QueryStringClientIdResolveContributor</span> : <span class="hljs-title">IClientResolveContributor</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> Task&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">ResolveClientAsync</span>(<span class="hljs-params">HttpContext httpContext</span>)</span>
    {
        <span class="hljs-keyword">return</span> Task.FromResult&lt;<span class="hljs-keyword">string</span>&gt;(httpContext.Request.Query[<span class="hljs-string">"X-ClientId"</span>]);
    }
}
</code></pre>
<p>To finalize, we need to tell the application to use our custom implementation.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">//builder.Services.AddSingleton&lt;IRateLimitConfiguration, RateLimitConfiguration&gt;();</span>
builder.Services.AddSingleton&lt;IRateLimitConfiguration, CustomRateLimitConfiguration&gt;();
</code></pre>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>In this <a target="_blank" href="https://devblogs.microsoft.com/dotnet/announcing-rate-limiting-for-dotnet/">link</a>, you can see that built-in Rate Limiting support is now part of .NET 7.</p>
<p>You can find the complete code on my <a target="_blank" href="https://github.com/jhonatanfernando/coachplan">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Applying CQRS and Mediator in Asp.Net Core]]></title><description><![CDATA[This blog post will discuss CQRS and Mediator patterns and apply them in an Asp.Net Core application. CQS is a design pattern, and the acronym stands for…]]></description><link>https://blog.jhonatanoliveira.dev/applying-cqrs-and-mediator-in-aspnet-core</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/applying-cqrs-and-mediator-in-aspnet-core</guid><category><![CDATA[#CQRS]]></category><category><![CDATA[mediator]]></category><category><![CDATA[asp.net core]]></category><category><![CDATA[C#]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sun, 15 Jan 2023 12:14:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UgA3Xvi3SkA/upload/dbd88724c71bd159133d11db846fe96f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This blog post will discuss CQRS and Mediator patterns and apply them in an Asp.Net Core application.</p>
<h1 id="heading-what-is-cqs">What is <em>CQS</em>?</h1>
<p><em>CQS</em> is a design pattern, and the acronym stands for Command Query Separation. It states that every method should either be a command that executes a task or a query that returns data to the caller, but not both. Methods should return a value only if they create no side effects.</p>
<h1 id="heading-what-is-cqrs">What is <em>CQRS</em>?</h1>
<p>Command Query Responsibility Segregation (<em>CQRS</em>) is the segregation of the responsibilities of the commands and queries in a system. It divides a system’s actions into commands and queries, and it is related to <em>CQS</em>.</p>
<p>Because of the flexibility created by migrating to <em>CQRS</em>, the system evolves better over time and prevents update commands from causing merge conflicts at the domain level.</p>
<h2 id="heading-when-to-use-it">When to use it?</h2>
<p>For Martin Fowler: <em>Like any pattern, CQRS is useful in some places but not others. CQRS is a significant mental leap for all concerned, so it should only be tackled if the benefit is worth the jump. In particular, CQRS should only be used on specific portions of a system and not the system as a whole.</em></p>
<p><em>CQRS</em> is an excellent pattern to use when the solution has rich/complex business logic.</p>
<p>Also, in scenarios where:</p>
<ul>
<li><p>performance of data reads must be fine-tuned separately from the performance of data writes.</p>
</li>
<li><p>one team of developers can focus on the complex domain model that is part of the write model, and another team can concentrate on the read model and the user interfaces.</p>
</li>
<li><p>the system is expected to evolve and might contain multiple versions of the model or where business rules change regularly.</p>
</li>
</ul>
<h2 id="heading-principles">Principles</h2>
<p>The core principle of <em>CQRS performs</em> fundamentally different roles within a system. Separating them means that each can be optimized as needed, which can be hugely beneficial for distributed systems. </p>
<h3 id="heading-commands">Commands</h3>
<p>A command is an instruction, a directive to perform a specific task. It is an intention to change something and is created when data is to be mutated.</p>
<p>For Alexey Zimarev: handling <em>a command should result in one transaction on one aggregate; basically, each command should clearly state one well-defined change</em>. </p>
<h3 id="heading-queries">Queries</h3>
<p>A query is a request for information and is only created when data is to be retrieved from the data store.</p>
<p>It is used to get data or the status of data, and the request should not change the data.</p>
<h1 id="heading-what-is-mediator">What is Mediator?</h1>
<p>In software engineering, the Mediator pattern defines an object that encapsulates how objects interact.</p>
<p>Instead of having two or more objects that take a direct dependency on each other, they interact with a <em>mediator</em>, who is in charge of sending those interactions to the other component/object.</p>
<p>This pattern is considered a behavioural pattern because it can change the program’s running behaviour.</p>
<h1 id="heading-implementation">Implementation</h1>
<p>First, let’s create a new Asp.Net Core Web API project; in my case, I will make it a minimal API project.</p>
<h2 id="heading-structure">Structure</h2>
<p>Before implementing the commands and queries, let's create some structure for the app.</p>
<h3 id="heading-domain">Domain</h3>
<p>In the Domain project, it was created the entities that are going to be used for now.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Exercise</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> MuscleId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> Muscle Muscle { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Muscle</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> List&lt;Exercise&gt; Exercises { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>And also the interfaces for the repository and the service.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IMuscleRepository</span>
{
    Task&lt;IEnumerable&lt;Muscle&gt;&gt; GetAll();
    <span class="hljs-function">Task&lt;Muscle&gt; <span class="hljs-title">GetById</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>;
    <span class="hljs-function">Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Create</span>(<span class="hljs-params">Muscle muscle</span>)</span>;
    <span class="hljs-function">Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Update</span>(<span class="hljs-params">Muscle muscle</span>)</span>;
    <span class="hljs-function">Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Delete</span>(<span class="hljs-params">Muscle muscle</span>)</span>;
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IMuscleService</span>
{
    Task&lt;IEnumerable&lt;Muscle&gt;&gt; GetAll();
    <span class="hljs-function">Task&lt;Muscle&gt; <span class="hljs-title">GetById</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>;
    <span class="hljs-function">Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Create</span>(<span class="hljs-params">Muscle muscle</span>)</span>;
    <span class="hljs-function">Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Update</span>(<span class="hljs-params">Muscle muscle</span>)</span>;
    <span class="hljs-function">Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Delete</span>(<span class="hljs-params">Muscle muscle</span>)</span>;
}
</code></pre>
<h3 id="heading-data">Data</h3>
<p>For the Data project, the Entity Framework was used as an ORM. The following code shows the implementation of the context.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CoachPlanContext</span> : <span class="hljs-title">DbContext</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> DbSet&lt;Muscle&gt; Muscles { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> DbSet&lt;Exercise&gt; Exercises { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CoachPlanContext</span>(<span class="hljs-params">DbContextOptions&lt;CoachPlanContext&gt; options</span>)
 : <span class="hljs-title">base</span>(<span class="hljs-params">options</span>)</span>
    {
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnModelCreating</span>(<span class="hljs-params">ModelBuilder modelBuilder</span>)</span>
    {
        <span class="hljs-keyword">base</span>.OnModelCreating(modelBuilder);

        modelBuilder.Entity&lt;Exercise&gt;(entity =&gt;
        {
            entity.HasOne(d =&gt; d.Muscle)
                .WithMany(d =&gt; d.Exercises)
                .HasForeignKey(d =&gt; d.MuscleId);

            entity.Property(e =&gt; e.Name)
                .IsRequired(<span class="hljs-literal">true</span>)
                .HasMaxLength(<span class="hljs-number">200</span>);

        });

        modelBuilder.Entity&lt;Muscle&gt;(entity =&gt;
        {
            entity.Property(e =&gt; e.Name)
                .IsRequired(<span class="hljs-literal">true</span>)
                .HasMaxLength(<span class="hljs-number">200</span>);
        });
    }
}
</code></pre>
<p>Also, was created a repository for the entity <code>Muscle</code>.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MuscleRepository</span> : <span class="hljs-title">IMuscleRepository</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> CoachPlanContext _coachPlanContext;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MuscleRepository</span>(<span class="hljs-params">CoachPlanContext coachPlanContext</span>)</span>
        {
            _coachPlanContext = coachPlanContext;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Create</span>(<span class="hljs-params">Muscle muscle</span>)</span>
        {
            _coachPlanContext.Muscles.Add(muscle);

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _coachPlanContext.SaveChangesAsync();
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Delete</span>(<span class="hljs-params">Muscle muscle</span>)</span>
        {
            _coachPlanContext.Remove(muscle);

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _coachPlanContext.SaveChangesAsync();
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;Muscle&gt;&gt; GetAll()
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _coachPlanContext.Muscles.ToListAsync();
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;Muscle&gt; <span class="hljs-title">GetById</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _coachPlanContext.Muscles.Where(m =&gt; m.Id == id).SingleOrDefaultAsync();
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Update</span>(<span class="hljs-params">Muscle muscle</span>)</span>
        {
            _coachPlanContext.Muscles.Update(muscle);

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _coachPlanContext.SaveChangesAsync();
        }
    }
</code></pre>
<h3 id="heading-service">Service</h3>
<p>So far was created only the <code>MuscleService</code> for this project.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MuscleService</span> : <span class="hljs-title">IMuscleService</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMuscleRepository _muscleRepository;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MuscleService</span>(<span class="hljs-params">IMuscleRepository muscleRepository</span>)</span>
    {
        _muscleRepository = muscleRepository;
    }   

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Create</span>(<span class="hljs-params">Muscle muscle</span>)</span>
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _muscleRepository.Create(muscle);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Delete</span>(<span class="hljs-params">Muscle muscle</span>)</span>
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _muscleRepository.Delete(muscle);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;Muscle&gt;&gt; GetAll()
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _muscleRepository.GetAll();
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;Muscle&gt; <span class="hljs-title">GetById</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _muscleRepository.GetById(id);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">Update</span>(<span class="hljs-params">Muscle muscle</span>)</span>
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _muscleRepository.Update(muscle);
    }
}
</code></pre>
<h2 id="heading-cqrs">CQRS</h2>
<p>I will create feature-wise folders to implement the Commands and Queries using the CQRS Pattern. All CQRS commands, queries, handlers, and validators related to one feature can be grouped under one folder. For example, to create all our commands and queries related to Muscles, we can have a <strong>Muscles</strong> folder, and inside that folder, we can have separate folders for <strong>Commands</strong> and <strong>Queries</strong>.</p>
<h3 id="heading-queries-1">Queries</h3>
<p>All the queries will implement the <strong>IRequest&lt;T&gt;</strong> interface available in the MediatR library, and it is necessary to specify what it will return.</p>
<p>Next, we need to define a handler class that implements the <strong>IRequestHandler</strong> interface. This class can be defined outside the class; I am implementing it as a nested class.</p>
<p>The <code>IMuscleService</code> service is injected into the constructor of <code>GetAllMusclesQuery</code> and <code>GetMuscleByIdQuery</code>.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GetAllMusclesQuery</span> : <span class="hljs-title">IRequest</span>&lt;<span class="hljs-title">IEnumerable</span>&lt;<span class="hljs-title">Domain.Entities.Muscle</span>&gt;&gt;
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GetAllMusclesQueryHandler</span> : <span class="hljs-title">IRequestHandler</span>&lt;<span class="hljs-title">GetAllMusclesQuery</span>, <span class="hljs-title">IEnumerable</span>&lt;<span class="hljs-title">Domain.Entities.Muscle</span>&gt;&gt;
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMuscleService _muscleService;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GetAllMusclesQueryHandler</span>(<span class="hljs-params">IMuscleService muscleService</span>)</span>
        {
            _muscleService = muscleService;
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;Domain.Entities.Muscle&gt;&gt; Handle(GetAllMusclesQuery query, CancellationToken cancellationToken)
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _muscleService.GetAll();
        }
    }
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GetMuscleByIdQuery</span> : <span class="hljs-title">IRequest</span>&lt;<span class="hljs-title">Domain.Entities.Muscle</span>&gt;
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> id;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GetMuscleByIdQuery</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>
    {
        <span class="hljs-keyword">this</span>.id = id;
    }   
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GetMuscleByIdQueryHandler</span> : <span class="hljs-title">IRequestHandler</span>&lt;<span class="hljs-title">GetMuscleByIdQuery</span>, <span class="hljs-title">Domain.Entities.Muscle</span>&gt;
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMuscleService _muscleService;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GetMuscleByIdQueryHandler</span>(<span class="hljs-params">IMuscleService muscleService</span>)</span>
        {
            _muscleService = muscleService;
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;Domain.Entities.Muscle&gt; Handle(GetMuscleByIdQuery query, CancellationToken cancellationToken)
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _muscleService.GetById(query.id);
        }
    }
}
</code></pre>
<h3 id="heading-commands-1">Commands</h3>
<p>The commands will follow the same idea as the queries; the difference is that the commands can change the data.</p>
<p>It was created the CreateMuscleCommand, DeleteMuscleCommand and UpdateMuscleCommand and their respective handlers.</p>
<p>Because of the example's simplicity, the domain entity was used as the query return type and as a parameter for the commands. It is a better practice to use DTOs to hide a domain entity from the public API.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CreateMuscleCommand</span> : <span class="hljs-title">IRequest</span>&lt;<span class="hljs-title">Unit</span>&gt;
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> Domain.Entities.Muscle muscle;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CreateMuscleCommand</span>(<span class="hljs-params">Domain.Entities.Muscle muscle</span>)</span>
    {
        <span class="hljs-keyword">this</span>.muscle = muscle;
    }      

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CreateMuscleCommandHandler</span> : <span class="hljs-title">IRequestHandler</span>&lt;<span class="hljs-title">CreateMuscleCommand</span>, <span class="hljs-title">Unit</span>&gt;
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMuscleService _muscleService;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CreateMuscleCommandHandler</span>(<span class="hljs-params">IMuscleService muscleService</span>)</span>
        {
            _muscleService = muscleService;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;Unit&gt; <span class="hljs-title">Handle</span>(<span class="hljs-params">CreateMuscleCommand command, CancellationToken cancellationToken</span>)</span>
        {
            <span class="hljs-keyword">await</span> _muscleService.Create(command.muscle);

            <span class="hljs-keyword">return</span> Unit.Value;
        }
    }
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">DeleteMuscleCommand</span> : <span class="hljs-title">IRequest</span>&lt;<span class="hljs-title">Unit</span>&gt;
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> id;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DeleteMuscleCommand</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id</span>)</span>
    {
        <span class="hljs-keyword">this</span>.id = id;
    }   

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">DeleteMuscleCommandHandler</span> : <span class="hljs-title">IRequestHandler</span>&lt;<span class="hljs-title">DeleteMuscleCommand</span>, <span class="hljs-title">Unit</span>&gt;
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMuscleService _muscleService;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DeleteMuscleCommandHandler</span>(<span class="hljs-params">IMuscleService muscleService</span>)</span>
        {
            _muscleService = muscleService;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;Unit&gt; <span class="hljs-title">Handle</span>(<span class="hljs-params">DeleteMuscleCommand command, CancellationToken cancellationToken</span>)</span>
        {
            <span class="hljs-keyword">var</span> muscle = <span class="hljs-keyword">await</span> _muscleService.GetById(command.id);
            <span class="hljs-keyword">if</span> (muscle == <span class="hljs-literal">null</span>)
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">default</span>;

            <span class="hljs-keyword">await</span> _muscleService.Delete(muscle);

            <span class="hljs-keyword">return</span> Unit.Value;
        }
    }
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">UpdateMuscleCommand</span> : <span class="hljs-title">IRequest</span>&lt;<span class="hljs-title">Unit</span>&gt;
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> id;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> Domain.Entities.Muscle muscle;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UpdateMuscleCommand</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> id, Domain.Entities.Muscle muscle</span>)</span>
    {
        <span class="hljs-keyword">this</span>.id = id;
        <span class="hljs-keyword">this</span>.muscle = muscle;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">UpdateMuscleCommandHandler</span> : <span class="hljs-title">IRequestHandler</span>&lt;<span class="hljs-title">UpdateMuscleCommand</span>, <span class="hljs-title">Unit</span>&gt;
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMuscleService _muscleService;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UpdateMuscleCommandHandler</span>(<span class="hljs-params">IMuscleService muscleService</span>)</span>
        {
            _muscleService = muscleService;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;Unit&gt; <span class="hljs-title">Handle</span>(<span class="hljs-params">UpdateMuscleCommand command, CancellationToken cancellationToken</span>)</span>
        {
            <span class="hljs-keyword">var</span> muscle = <span class="hljs-keyword">await</span> _muscleService.GetById(command.id);
            <span class="hljs-keyword">if</span> (muscle == <span class="hljs-literal">null</span>)
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">default</span>;

            muscle.Name = command.muscle.Name; 

            <span class="hljs-keyword">await</span> _muscleService.Update(muscle);

            <span class="hljs-keyword">return</span> Unit.Value;
        }
    }
}
</code></pre>
<h2 id="heading-mediatr">MediatR</h2>
<p>The <a target="_blank" href="https://github.com/jbogard/MediatR">MediatR</a> library describes itself as a “Simple, unambitious mediator implementation in .NET.” All communication between the user interface and the data store happens via MediatR; this helps us to build CQRS systems.</p>
<p>We need to install two nugget packages: <a target="_blank" href="https://www.nuget.org/packages/MediatR/">MediatR</a> and <a target="_blank" href="https://www.nuget.org/packages/MediatR.Extensions.Microsoft.DependencyInjection/">MediatR.Extensions.Microsoft.DependencyInjection</a>. After that, we can register the MediatR in our application.</p>
<p>MediatR Requests are straightforward request-response style messages where a single handler synchronously handles a single request.</p>
<h2 id="heading-application">Application</h2>
<p>First, it is necessary to register everything the application will use. The following code registers the MediatR, service, repository and the EF DbContext.</p>
<pre><code class="lang-csharp">builder.Services.AddMediatR(Assembly.GetExecutingAssembly());

builder.Services.AddScoped&lt;IMuscleRepository, MuscleRepository&gt;();
builder.Services.AddScoped&lt;IMuscleService, MuscleService&gt;();

builder.Services.AddDbContext&lt;CoachPlanContext&gt;(options =&gt;
       options.UseSqlServer(builder.Configuration.GetConnectionString(<span class="hljs-string">"DefaultConnection"</span>)));
</code></pre>
<p>All the endpoints receive the <code>IMediator</code> instance, and this one will send the request using the correct command or query.</p>
<pre><code class="lang-csharp">app.MapGet(<span class="hljs-string">"/muscles"</span>, <span class="hljs-keyword">async</span> (IMediator _mediator) =&gt;
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _mediator.Send(<span class="hljs-keyword">new</span> GetAllMusclesQuery());
});

app.MapGet(<span class="hljs-string">"/muscles/{id}"</span>, <span class="hljs-keyword">async</span> (IMediator _mediator, <span class="hljs-keyword">int</span> id) =&gt;
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _mediator.Send(<span class="hljs-keyword">new</span> GetMuscleByIdQuery(id));
});

app.MapPost(<span class="hljs-string">"/muscles"</span>, <span class="hljs-keyword">async</span> (IMediator _mediator, Muscle muscle) =&gt;
{
   <span class="hljs-keyword">await</span> _mediator.Send(<span class="hljs-keyword">new</span> CreateMuscleCommand(muscle));

    <span class="hljs-keyword">return</span> Results.Created(<span class="hljs-string">$"/muscles/<span class="hljs-subst">{muscle.Id}</span>"</span>, muscle);
});

app.MapPut(<span class="hljs-string">"/muscles/{id}"</span>, <span class="hljs-keyword">async</span> (IMediator _mediator, <span class="hljs-keyword">int</span> id, Muscle muscle) =&gt;
{
    <span class="hljs-keyword">await</span> _mediator.Send(<span class="hljs-keyword">new</span> UpdateMuscleCommand(id, muscle));

    <span class="hljs-keyword">return</span> Results.NoContent();
});

app.MapDelete(<span class="hljs-string">"/muscles/{id}"</span>, <span class="hljs-keyword">async</span> (IMediator _mediator, <span class="hljs-keyword">int</span> id) =&gt;
{
    <span class="hljs-keyword">await</span> _mediator.Send(<span class="hljs-keyword">new</span> DeleteMuscleCommand(id));

    <span class="hljs-keyword">return</span> Results.Ok();
});
</code></pre>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>This was a simple example of how to use CQRS and Mediator patterns. More things can be added, like MediatR Behaviors and Notifications. I will keep updating this project.</p>
<p>You can find the complete code on my <a target="_blank" href="https://github.com/jhonatanfernando/coachplan">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Using caching in Asp.Net Core Minimal APIs]]></title><description><![CDATA[Caching provides a better customer experience and makes applications performant and scalable. If the result (query, page, etc.) is cached, the next time…]]></description><link>https://blog.jhonatanoliveira.dev/using-caching-in-aspnet-core-minimal-apis</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/using-caching-in-aspnet-core-minimal-apis</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[caching]]></category><category><![CDATA[C#]]></category><category><![CDATA[minimal-apis]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Tue, 03 Jan 2023 12:18:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/37973fbb18ef4b6d2118c729b255a571.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Caching provides a better customer experience and makes applications performant and scalable. If the result (query, page, etc.) is cached, the next time the same request comes, the cached data can be fetched instead of processing the request again.</p>
<p>This blog post will discuss the caching of data using <code>IMemoryCache</code> and <code>IDistributedCache</code>.</p>
<h1 id="heading-what-is-cache">What is cache?</h1>
<p>Caching is the technique of storing the data which are frequently used. Those data can be returned faster in the future or subsequent requests by eliminating unnecessary requests to external data sources.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672489820360/2dc333b3-1279-4eed-8cbd-72011208478a.webp" alt class="image--center mx-auto" /></p>
<p>Caching will be a good option when the databases take time to respond, when the CPU spikes occur during peak traffic or when server response times become inconsistent depending on the number of concurrent requests.</p>
<h2 id="heading-what-is-in-memory-caching"><strong>What is in-memory caching?</strong></h2>
<p>In-Memory caching refers to caching the computation results in the memory of the machine where the actual application is running. If the machine is restarted, the cache store will be flushed. It might be helpful to use this in the early stages of development or on the development machine.</p>
<h3 id="heading-imemorycache">IMemoryCache</h3>
<p>The interface <code>IMemoryCache</code> can be injected into the endpoints. This injected instance can be used to see if the data is already cached and to add a new one to the cache.</p>
<p>While it requires a key, the cache options, such as the item's expiration, are optional. The expiration can be sliding or absolute.</p>
<p>Absolute expiration means no matter the frequency of accessing cached data, it will be removed after a fixed time.</p>
<p>Sliding expiration provides a way to remove the cached data which are not frequently accessed. If an object's sliding expiration of 30 seconds is enabled, it will expire only if the data was not accessed in the last 30 seconds.</p>
<p>The following code shows the methods and extension methods of this interface.</p>
<pre><code class="lang-csharp"> <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IMemoryCache</span>: <span class="hljs-title">IDisposable</span>
 {
        <span class="hljs-function">ICacheEntry <span class="hljs-title">CreateEntry</span>(<span class="hljs-params"><span class="hljs-keyword">object</span> key</span>)</span>;
        MemoryCacheStatistics? GetCurrentStatistics();
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Remove</span>(<span class="hljs-params"><span class="hljs-keyword">object</span> key</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">TryGetValue</span>(<span class="hljs-params"><span class="hljs-keyword">object</span> key, <span class="hljs-keyword">out</span> <span class="hljs-keyword">object</span>? <span class="hljs-keyword">value</span></span>)</span>;
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CacheExtensions</span>
 {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">object</span>? Get(<span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key);
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> TItem? Get&lt;TItem&gt;(<span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key);
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> TItem? GetOrCreate&lt;TItem&gt;(<span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key, Func&lt;ICacheEntry, TItem&gt; factory);
       <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-title">Task</span>&lt;<span class="hljs-title">TItem</span>?&gt; <span class="hljs-title">GetOrCreateAsync</span>&lt;<span class="hljs-title">TItem</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key, Func&lt;ICacheEntry, Task&lt;TItem&gt;&gt; factory</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> TItem <span class="hljs-title">Set</span>&lt;<span class="hljs-title">TItem</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key, TItem <span class="hljs-keyword">value</span></span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> TItem <span class="hljs-title">Set</span>&lt;<span class="hljs-title">TItem</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key, TItem <span class="hljs-keyword">value</span>, DateTimeOffset absoluteExpiration</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> TItem <span class="hljs-title">Set</span>&lt;<span class="hljs-title">TItem</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key, TItem <span class="hljs-keyword">value</span>, TimeSpan absoluteExpirationRelativeToNow</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> TItem <span class="hljs-title">Set</span>&lt;<span class="hljs-title">TItem</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key, TItem <span class="hljs-keyword">value</span>, IChangeToken expirationToken</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> TItem <span class="hljs-title">Set</span>&lt;<span class="hljs-title">TItem</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key, TItem <span class="hljs-keyword">value</span>, MemoryCacheEntryOptions? options</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">TryGetValue</span>&lt;<span class="hljs-title">TItem</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> IMemoryCache cache, <span class="hljs-keyword">object</span> key, <span class="hljs-keyword">out</span> TItem? <span class="hljs-keyword">value</span></span>)</span>;
  }
</code></pre>
<h2 id="heading-what-is-distributed-cache"><strong>What is Distributed Cache?</strong></h2>
<p>As the name suggests, a distributed cache does not use a web server’s memory as a cache store. Multiple app servers share a distributed cache, typically maintained as an external service to the app servers that access it.</p>
<p>A distributed cache can improve the performance and scalability of an ASP.NET Core app, mainly when a cloud service or a server farm hosts the app. Some examples of Distribute Cache include <code>SQL Server database</code>, <code>Azure Redis Cache</code>, <code>NCache</code>, etc.</p>
<p>In this blog post, we will use the <code>SQL Server database</code>.</p>
<h3 id="heading-idistributedcache"><strong>IDistributedCache</strong></h3>
<p>The <code>IDistributedCache</code> interface includes synchronous and asynchronous methods. The interface allows items to be added, retrieved, and removed from the distributed cache implementation.</p>
<p>The interface provides similar functionality to <code>IMemoryCache</code>, but there are some differences, such as additional async methods, refresh methods and byte-based rather than object-based. The following code shows the methods and the extension methods of the interface.</p>
<pre><code class="lang-csharp"> <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IDistributedCache</span>
    {
        <span class="hljs-keyword">byte</span>[]? Get(<span class="hljs-keyword">string</span> key);
        Task&lt;<span class="hljs-keyword">byte</span>[]?&gt; GetAsync(<span class="hljs-keyword">string</span> key, CancellationToken token = <span class="hljs-keyword">default</span>);
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Refresh</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> key</span>)</span>;
        <span class="hljs-function">Task <span class="hljs-title">RefreshAsync</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> key, CancellationToken token = <span class="hljs-keyword">default</span></span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Remove</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> key</span>)</span>;
        <span class="hljs-function">Task <span class="hljs-title">RemoveAsync</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> key, CancellationToken token = <span class="hljs-keyword">default</span></span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Set</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> key, <span class="hljs-keyword">byte</span>[] <span class="hljs-keyword">value</span>, DistributedCacheEntryOptions options</span>)</span>;
        <span class="hljs-function">Task <span class="hljs-title">SetAsync</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> key, <span class="hljs-keyword">byte</span>[] <span class="hljs-keyword">value</span>, DistributedCacheEntryOptions options, CancellationToken token = <span class="hljs-keyword">default</span></span>)</span>;
    }

<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">DistributedCacheExtensions</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span>? GetString(<span class="hljs-keyword">this</span> IDistributedCache cache, <span class="hljs-keyword">string</span> key);
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Task&lt;<span class="hljs-keyword">string</span>?&gt; GetStringAsync(<span class="hljs-keyword">this</span> IDistributedCache cache, <span class="hljs-keyword">string</span> key, CancellationToken token = <span class="hljs-keyword">default</span>);
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Set</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> IDistributedCache cache, <span class="hljs-keyword">string</span> key, <span class="hljs-keyword">byte</span>[] <span class="hljs-keyword">value</span></span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Task <span class="hljs-title">SetAsync</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> IDistributedCache cache, <span class="hljs-keyword">string</span> key, <span class="hljs-keyword">byte</span>[] <span class="hljs-keyword">value</span>, CancellationToken token = <span class="hljs-keyword">default</span></span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SetString</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> IDistributedCache cache, <span class="hljs-keyword">string</span> key, <span class="hljs-keyword">string</span> <span class="hljs-keyword">value</span></span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SetString</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> IDistributedCache cache, <span class="hljs-keyword">string</span> key, <span class="hljs-keyword">string</span> <span class="hljs-keyword">value</span>, DistributedCacheEntryOptions options</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Task <span class="hljs-title">SetStringAsync</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> IDistributedCache cache, <span class="hljs-keyword">string</span> key, <span class="hljs-keyword">string</span> <span class="hljs-keyword">value</span>, CancellationToken token = <span class="hljs-keyword">default</span></span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Task <span class="hljs-title">SetStringAsync</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> IDistributedCache cache, <span class="hljs-keyword">string</span> key, <span class="hljs-keyword">string</span> <span class="hljs-keyword">value</span>, DistributedCacheEntryOptions options, CancellationToken token = <span class="hljs-keyword">default</span></span>)</span>;
    }
</code></pre>
<h3 id="heading-distributed-sql-server-cache"><strong>Distributed SQL Server Cache</strong></h3>
<p>Distributed SQL server cache uses SQL Server as the backing store to store the cached data. A database and a table can be created in a SQL server instance. The connection string for this database can be provided to the application to connect to this data store.</p>
<p>To create a SQL Server cached item table in a SQL Server instance, we can use the <code>sql-cache</code> tool. The tool creates a table with the name and schema that we specify.</p>
<p>The <code>sql-cache</code> command needs the SQL Server instance (<code>Data Source</code>), database (<code>Initial Catalog</code>), schema (for example, <code>dbo</code>), and table name (for example, <code>TestCache</code>).</p>
<pre><code class="lang-csharp">dotnet sql-cache create <span class="hljs-string">"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;"</span> dbo TestCache
</code></pre>
<h1 id="heading-implementation">Implementation</h1>
<h2 id="heading-in-memory-caching"><strong>In-memory caching</strong></h2>
<p>Before using the <code>IMemoryCache</code> in our code, we must register it in the application.</p>
<pre><code class="lang-csharp">builder.Services.AddMemoryCache();
</code></pre>
<p>For this example, a new service was created that has a method to return all the <code>Todo</code> items. It is possible to inject the <code>IMemoryCache</code> into the constructor.</p>
<p>In the method <code>GetAll,</code> we are using the method <code>GetOrCreateAsync</code> which will return the data if the cache exists or create a new one with the results of the method from the <code>DbContext</code>.</p>
<p>The code uses <code>SlidingExpiration</code>and <code>AbsoluteExpiration</code>. When both are used, a logical OR is used to decide if the data should be marked as expired. The data is removed from the cache if either the sliding expiration interval or the absolute expiration time passes.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoService</span> : <span class="hljs-title">ITodoService</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> key = <span class="hljs-string">"get-todos"</span>;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMemoryCache _memoryCache;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TodoDb _dbContext;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoService</span>(<span class="hljs-params">IMemoryCache memoryCache, TodoDb dbContext</span>)</span>
        {
            _memoryCache = memoryCache;
            _dbContext = dbContext;
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;List&lt;Todo&gt;&gt; GetAll()
        {
            <span class="hljs-keyword">var</span> todos = <span class="hljs-keyword">await</span> _memoryCache.GetOrCreateAsync&lt;List&lt;Todo&gt;&gt;(key, <span class="hljs-keyword">async</span> entry =&gt;
            {
                entry.SetSlidingExpiration(TimeSpan.FromSeconds(<span class="hljs-number">10</span>));
                entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(<span class="hljs-number">20</span>));

                <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _dbContext.Todos.ToListAsync();
            });

            <span class="hljs-keyword">return</span> todos;
        }
    }
</code></pre>
<p>This is the endpoint code using the new service that was created.</p>
<pre><code class="lang-csharp">app.MapGet(<span class="hljs-string">"v{version:apiVersion}/todoitems"</span>, [Authorize] <span class="hljs-keyword">async</span> (ITodoService todoService) =&gt;
{
    logger.LogInformation(<span class="hljs-string">"Getting todoitems"</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> todoService.GetAll();
})
.WithApiVersionSet(versionSet)
.MapToApiVersion(version1);
</code></pre>
<h2 id="heading-distributed-cache"><strong>Distributed Cache</strong></h2>
<p>Before coding, we must prepare the SQL database to store the cache. The two following CLI commands need to be executed. The first command is installing the tool, and the second is creating a table in the local database.</p>
<pre><code class="lang-csharp">dotnet tool install --<span class="hljs-keyword">global</span> dotnet-sql-cache
</code></pre>
<pre><code class="lang-csharp">dotnet sql-cache create <span class="hljs-string">"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;"</span> dbo TestCache
</code></pre>
<p>After executing the CLI command, the table <code>TestCache</code> must have the following structure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672707770137/ebf4ba7f-d717-4b2e-9820-63ada0485554.png" alt class="image--center mx-auto" /></p>
<p>After installing the nugget package <a target="_blank" href="https://www.nuget.org/packages/Microsoft.Extensions.Caching.SqlServer/">Microsoft.Extensions.Caching.SqlServer</a> we can register the cache.</p>
<pre><code class="lang-csharp">builder.Services.AddDistributedSqlServerCache(options =&gt;
{
    options.ConnectionString = builder.Configuration.GetConnectionString(<span class="hljs-string">"DistCacheConnection"</span>);
    options.SchemaName = <span class="hljs-string">"dbo"</span>;
    options.TableName = <span class="hljs-string">"TestCache"</span>;
})
</code></pre>
<p>The connection string was added to the <code>appsettings.json</code> file.</p>
<pre><code class="lang-json">  <span class="hljs-string">"ConnectionStrings"</span>: {
    <span class="hljs-attr">"DistCacheConnection"</span>: <span class="hljs-string">"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;"</span>
  }
</code></pre>
<p>It is necessary to inject <code>IDistributedCache</code> into TodoService's constructor, and then we can use the instance to cache and restore the data from the cache.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoService</span> : <span class="hljs-title">ITodoService</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> key = <span class="hljs-string">"get-todos"</span>;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IMemoryCache _memoryCache;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TodoDb _dbContext;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IDistributedCache _distributedCache;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoService</span>(<span class="hljs-params">IMemoryCache memoryCache, TodoDb dbContext, IDistributedCache distributedCache</span>)</span>
        {
            _memoryCache = memoryCache;
            _dbContext = dbContext;
            _distributedCache = distributedCache;
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;List&lt;Todo&gt;&gt; GetAllWithDistributedCache()
        {
            <span class="hljs-comment">//Get the cached data</span>
            <span class="hljs-keyword">byte</span>[] cachedData = <span class="hljs-keyword">await</span> _distributedCache.GetAsync(key);

            <span class="hljs-comment">//Deserialize the cached response if there are any</span>
            <span class="hljs-keyword">if</span> (cachedData != <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">var</span> jsonData = System.Text.Encoding.UTF8.GetString(cachedData);
                <span class="hljs-keyword">var</span> dataResult = JsonSerializer.Deserialize&lt;List&lt;Todo&gt;&gt;(jsonData);
                <span class="hljs-keyword">if</span> (dataResult != <span class="hljs-literal">null</span>)
                {
                    <span class="hljs-keyword">return</span> dataResult;
                }
            }

            <span class="hljs-keyword">var</span> todos = <span class="hljs-keyword">await</span> _dbContext.Todos.ToListAsync();

            <span class="hljs-comment">// Serialize the response</span>
            <span class="hljs-keyword">byte</span>[] objectToCache = JsonSerializer.SerializeToUtf8Bytes(todos);
            <span class="hljs-keyword">var</span> cacheEntryOptions = <span class="hljs-keyword">new</span> DistributedCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromSeconds(<span class="hljs-number">10</span>))
                .SetAbsoluteExpiration(TimeSpan.FromSeconds(<span class="hljs-number">30</span>));

            <span class="hljs-comment">// Cache it</span>
            <span class="hljs-keyword">await</span> _distributedCache.SetAsync(key, objectToCache, cacheEntryOptions);

            <span class="hljs-keyword">return</span> todos;
        }
    }
</code></pre>
<p>This is the entry that is stored in the database. We can see both expiration dates, the <code>SlidingExpirationInSeconds</code> value and the serialized data.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672710611808/7a73b2b3-b2a2-474b-9e3e-9f333f90b382.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>This example shows the basic ways to introduce caching to an ASP.Net core app. Other solutions using a distributed cache are NCache and Redis, for which I will prepare one exclusive blog post.</p>
<p>You can find the complete code on my <a target="_blank" href="https://github.com/jhonatanfernando/api-fluent-validator/tree/caching">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Using background service in Asp.net Core Minimal APIs]]></title><description><![CDATA[Background tasks are services that aren’t meant to execute during a regular flow of a typical application, such as sending email confirmations or updating…]]></description><link>https://blog.jhonatanoliveira.dev/using-background-service-in-aspnet-core-minimal-apis</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/using-background-service-in-aspnet-core-minimal-apis</guid><category><![CDATA[background services]]></category><category><![CDATA[asp.net core]]></category><category><![CDATA[C#]]></category><category><![CDATA[APIs]]></category><category><![CDATA[minimal-apis]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sat, 24 Dec 2022 18:55:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/41027d9d6336ff436c8a1f73843393b3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Background tasks are services that aren’t meant to execute during a regular flow of a typical application, such as sending email confirmations or updating the database with new data. These tasks are not meant to interact with the customers or process user input. Instead, they run in the background, handling items from a queue or executing a long-running process.</p>
<h1 id="heading-ihostedservice"><strong>IHostedService</strong></h1>
<p>We use the <code>IHostedService</code> interface to run tasks in the background. The hosted service indicates a class that contains background task logic.</p>
<p>When we register an <code>IHostedService</code>, .NET will call the <code>StartAsync()</code> and <code>StopAsync()</code> methods of our <code>IHostedService</code> type during application start and stop, respectively.</p>
<p>We are responsible for handling the stopping action of our services when the hosts trigger the <code>StopAsync()</code>.</p>
<p>The following code shows the structure of the <code>IHostedService</code>.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IHostedService</span>
    {
        <span class="hljs-function">Task <span class="hljs-title">StartAsync</span>(<span class="hljs-params">CancellationToken cancellationToken</span>)</span>;
        <span class="hljs-function">Task <span class="hljs-title">StopAsync</span>(<span class="hljs-params">CancellationToken cancellationToken</span>)</span>;
    }
</code></pre>
<h2 id="heading-backgroundservice"><strong>BackgroundService</strong></h2>
<p>The <code>BackgroundService</code>class is part of .NET Core. It’s an implementation of the <code>IHostedService</code> interface, which is meant to be used for running background jobs in ASP.NET Core.</p>
<p>When deriving from <code>BackgroundService</code>, thanks to that inherited implementation, we need to implement the <code>ExecuteAsync()</code> method in our custom-hosted service class.</p>
<p>The implementation of <code>ExecuteAsync</code> should finish promptly when the cancellation token is fired to stop the service immediately.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BackgroundService</span> : <span class="hljs-title">IHostedService</span>, <span class="hljs-title">IDisposable</span>
    {
        <span class="hljs-keyword">private</span> Task _executeTask;
        <span class="hljs-keyword">private</span> CancellationTokenSource _stoppingCts;

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> Task ExecuteTask =&gt; _executeTask;

        <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> Task <span class="hljs-title">ExecuteAsync</span>(<span class="hljs-params">CancellationToken stoppingToken</span>)</span>;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> Task <span class="hljs-title">StartAsync</span>(<span class="hljs-params">CancellationToken cancellationToken</span>)</span>
        {
            _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            _executeTask = ExecuteAsync(_stoppingCts.Token);
            <span class="hljs-keyword">if</span> (_executeTask.IsCompleted)
            {
                <span class="hljs-keyword">return</span> _executeTask;
            }

            <span class="hljs-keyword">return</span> Task.CompletedTask;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">StopAsync</span>(<span class="hljs-params">CancellationToken cancellationToken</span>)</span>
        {
            <span class="hljs-keyword">if</span> (_executeTask == <span class="hljs-literal">null</span>)
            {
                <span class="hljs-keyword">return</span>;
            }

            <span class="hljs-keyword">try</span>
            {
                _stoppingCts.Cancel();
            }
            <span class="hljs-keyword">finally</span>
            {
                <span class="hljs-keyword">await</span> Task.WhenAny(_executeTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(<span class="hljs-literal">false</span>);
            }

        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Dispose</span>(<span class="hljs-params"></span>)</span>
        {
            _stoppingCts?.Cancel();
        }
    }
</code></pre>
<h2 id="heading-timed-background-tasks"><strong>Timed background tasks</strong></h2>
<p>It is an implementation of <code>IHostedService</code> that uses the <code>Timer</code> class to trigger the function that needs to run.</p>
<h2 id="heading-queued-background-tasks"><strong>Queued background tasks</strong></h2>
<p>Queue background tasks are an excellent example of long-running services where work items can be queued and worked on sequentially as previous work items are completed.</p>
<h1 id="heading-quartznet">Quartz.NET</h1>
<p>Quartz.NET is a free and open source .NET port of its Java Quartz Scheduling framework counterpart. It has been used for a long time and offers good support for dealing with cron expressions. There is also a <code>Quartz.AspNetCore</code> package that builds on the Quartz.Extensions.Hosting. It primarily adds health-check integration, though health checks can also be used with worker services!</p>
<p>Quartz.NET has three main actors:</p>
<ul>
<li><p>A <strong>job</strong>. This is the background task, and it includes the code needed to execute a task or job.</p>
</li>
<li><p>A <strong>trigger</strong>. A trigger controls <em>when</em> and <em>how</em> a job runs.</p>
</li>
<li><p>A <strong>scheduler</strong>. This is responsible for coordinating the jobs and triggers and executing the jobs as required by the triggers.</p>
</li>
</ul>
<h1 id="heading-implementation">Implementation</h1>
<h2 id="heading-backgroundservice-1"><strong>BackgroundService</strong></h2>
<p>Using the <code>BackgroundService</code>, we need to create a class that inherits from it and implement the method <code>ExecuteAsync</code>. The following codes show the implementation of the service and how to register it.</p>
<pre><code class="lang-csharp">builder.Services.AddHostedService&lt;TodoBackgroundService&gt;();
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoBackgroundService</span> : <span class="hljs-title">BackgroundService</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;Todo&gt; _logger;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoBackgroundService</span>(<span class="hljs-params">ILogger&lt;Todo&gt; logger</span>)</span>
    {
        _logger = logger;
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> Task <span class="hljs-title">ExecuteAsync</span>(<span class="hljs-params">CancellationToken stoppingToken</span>)</span>
    {
        <span class="hljs-keyword">if</span> (!stoppingToken.IsCancellationRequested)
        {
            <span class="hljs-keyword">try</span>
            {
                _logger.LogInformation(
                    <span class="hljs-string">$"Executed TodoItemBackgroundService"</span>);

            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                _logger.LogInformation(
                    <span class="hljs-string">$"Failed to execute TodoItemBackgroundService with exception message <span class="hljs-subst">{ex.Message}</span>."</span>);
            }
        }

        <span class="hljs-keyword">return</span> Task.CompletedTask;
    }
}
</code></pre>
<h2 id="heading-timed-background-tasks-1"><strong>Timed background tasks</strong></h2>
<p>The Timed background task can be implemented using <code>BackgroundService</code> or <code>IHostedService</code>. The important thing is to use a class that helps to control the execution of the code in an interval of time. For this example, we will use the <code>PeriodicTimer</code>.</p>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoTimedBackgroundService</span> : <span class="hljs-title">BackgroundService</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> _executionCount = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">private</span> TimeSpan _period;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;Todo&gt; _logger;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoTimedBackgroundService</span>(<span class="hljs-params">ILogger&lt;Todo&gt; logger</span>)</span>
        {
            _logger = logger;
            _period = TimeSpan.FromSeconds(<span class="hljs-number">10</span>);
        }

        <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">ExecuteAsync</span>(<span class="hljs-params">CancellationToken stoppingToken</span>)</span>
        {
            <span class="hljs-keyword">using</span> PeriodicTimer timer = <span class="hljs-keyword">new</span> PeriodicTimer(_period);
            <span class="hljs-keyword">while</span> (
                !stoppingToken.IsCancellationRequested &amp;&amp;
                <span class="hljs-keyword">await</span> timer.WaitForNextTickAsync(stoppingToken))
            {
                <span class="hljs-keyword">try</span>
                {
                    _executionCount++;
                    _logger.LogInformation(
                        <span class="hljs-string">$"<span class="hljs-subst">{DateTime.Now.ToString(<span class="hljs-string">"HH:mm:ss"</span>)}</span> - Executed TodoTimedBackgroundService - Count: <span class="hljs-subst">{_executionCount}</span>"</span>);
                }
                <span class="hljs-keyword">catch</span> (Exception ex)
                {
                    _logger.LogInformation(
                        <span class="hljs-string">$"Failed to execute TodoTimedBackgroundService with exception message <span class="hljs-subst">{ex.Message}</span>."</span>);
                }
            }
        }
    }
</code></pre>
<pre><code class="lang-csharp">info: ApiFluentValidator.Models.Todo[<span class="hljs-number">0</span>]
      <span class="hljs-number">16</span>:<span class="hljs-number">24</span>:<span class="hljs-number">08</span> - Executed TodoTimedBackgroundService - Count: <span class="hljs-number">1</span>
info: ApiFluentValidator.Models.Todo[<span class="hljs-number">0</span>]
      <span class="hljs-number">16</span>:<span class="hljs-number">24</span>:<span class="hljs-number">18</span> - Executed TodoTimedBackgroundService - Count: <span class="hljs-number">2</span>
info: ApiFluentValidator.Models.Todo[<span class="hljs-number">0</span>]
      <span class="hljs-number">16</span>:<span class="hljs-number">24</span>:<span class="hljs-number">28</span> - Executed TodoTimedBackgroundService - Count: <span class="hljs-number">3</span>
info: ApiFluentValidator.Models.Todo[<span class="hljs-number">0</span>]
      <span class="hljs-number">16</span>:<span class="hljs-number">24</span>:<span class="hljs-number">38</span> - Executed TodoTimedBackgroundService - Count: <span class="hljs-number">4</span>
</code></pre>
<h2 id="heading-queued-background-tasks-1"><strong>Queued background tasks</strong></h2>
<p>For this type of background task, first, we will implement a Queue that our worker can use. The generic interface <code>IBackgroundQueue&lt;T&gt;</code> is created to be injected into our application.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IBackgroundQueue</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Enqueue</span>(<span class="hljs-params">T item</span>)</span>;
    <span class="hljs-function">T <span class="hljs-title">Dequeue</span>(<span class="hljs-params"></span>)</span>;
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BackgroundQueue</span>&lt;<span class="hljs-title">T</span>&gt; : <span class="hljs-title">IBackgroundQueue</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-keyword">where</span> <span class="hljs-title">T</span> : <span class="hljs-keyword">class</span>
{
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-title">ConcurrentQueue</span>&lt;<span class="hljs-title">T</span>&gt; _items</span> = <span class="hljs-keyword">new</span> ConcurrentQueue&lt;T&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Enqueue</span>(<span class="hljs-params">T item</span>)</span>
    {
        <span class="hljs-keyword">if</span> (item == <span class="hljs-literal">null</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentNullException(<span class="hljs-keyword">nameof</span>(item));

        _items.Enqueue(item);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">Dequeue</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> success = _items.TryDequeue(<span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> workItem);

        <span class="hljs-keyword">return</span> success
            ? workItem
            : <span class="hljs-literal">null</span>;
    }
}
</code></pre>
<p>Because the queue will be accessed from different threads, the <strong>ConcurrentQueue&lt;T&gt;</strong> provides the code with some thread safety.</p>
<p>The implementation of <code>TodoBackgroundQueueService</code> will use <code>IBackgroundQueue&lt;Todo&gt;</code>, <code>ILogger</code> and <code>IServiceScopeFactory</code>. The reason to use <code>IServiceScopeFactory</code>is because the <code>ITodoService</code>is a <em>Scoped Service</em> while the <code>TodoBackgroundQueueService</code>is a <em>Singleton</em> and the <code>TodoService</code>uses an Entity Framework <code>DbContext</code><em>.</em> In this case, to avoid weird behaviours of <code>DbContext</code> that might occur with other Scoped Services.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoBackgroundQueueService</span> : <span class="hljs-title">BackgroundService</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IBackgroundQueue&lt;Todo&gt; _queue;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IServiceScopeFactory _scopeFactory;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;TodoBackgroundQueueService&gt; _logger;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoBackgroundQueueService</span>(<span class="hljs-params">IBackgroundQueue&lt;Todo&gt; queue, IServiceScopeFactory scopeFactory,
      ILogger&lt;TodoBackgroundQueueService&gt; logger</span>)</span>
    {
        _queue = queue;
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">ExecuteAsync</span>(<span class="hljs-params">CancellationToken stoppingToken</span>)</span>
    {
        _logger.LogInformation(<span class="hljs-string">"{Type} is now running in the background."</span>, <span class="hljs-keyword">nameof</span>(TodoBackgroundQueueService));

        <span class="hljs-keyword">await</span> TodoProcessing(stoppingToken);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> Task <span class="hljs-title">StopAsync</span>(<span class="hljs-params">CancellationToken cancellationToken</span>)</span>
    {
        _logger.LogCritical(
            <span class="hljs-string">"The {Type} is stopping; queued items might not be processed anymore."</span>,
            <span class="hljs-keyword">nameof</span>(TodoBackgroundQueueService)
        );

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">base</span>.StopAsync(cancellationToken);
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">TodoProcessing</span>(<span class="hljs-params">CancellationToken stoppingToken</span>)</span>
    {
        <span class="hljs-keyword">while</span> (!stoppingToken.IsCancellationRequested)
        {
            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">await</span> Task.Delay(<span class="hljs-number">1000</span>, stoppingToken);

                <span class="hljs-keyword">var</span> todo = _queue.Dequeue();

                <span class="hljs-keyword">if</span> (todo == <span class="hljs-literal">null</span>)
                    <span class="hljs-keyword">continue</span>;

                _logger.LogInformation(<span class="hljs-string">"Todo Item found! Completing it .."</span>);

                <span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> scope = _scopeFactory.CreateScope();
                <span class="hljs-keyword">var</span> todoService = scope.ServiceProvider.GetRequiredService&lt;ITodoService&gt;();

                <span class="hljs-keyword">await</span> todoService.CompleteTodo(todo);

                _logger.LogInformation(<span class="hljs-string">"Todo Item is completed."</span>);
            }
            <span class="hljs-keyword">catch</span> (Exception ex)
            {
                _logger.LogCritical(<span class="hljs-string">"An error occurred when completing a todo. Exception: {@Exception}"</span>, ex);
            }
        }
    }
}
</code></pre>
<p>The following code registers all the items that the code needs to work.</p>
<pre><code class="lang-csharp">builder.Services.AddScoped&lt;ITodoService, TodoService&gt;();
builder.Services.AddSingleton&lt;IBackgroundQueue&lt;Todo&gt;, BackgroundQueue&lt;Todo&gt;&gt;();
builder.Services.AddHostedService&lt;TodoBackgroundQueueService&gt;();
</code></pre>
<p>The following code shows the endpoint enqueuing the Todo item.</p>
<pre><code class="lang-csharp">app.MapPut(<span class="hljs-string">"v{version:apiVersion}/complete"</span>, [Authorize] (IBackgroundQueue&lt;Todo&gt; queue, <span class="hljs-keyword">int</span> id, TodoDb db) =&gt;
{
    <span class="hljs-keyword">var</span> todo = db.Todos.SingleOrDefault(c=&gt; c.Id == id);

    <span class="hljs-keyword">if</span>(todo <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span>)
    {
        <span class="hljs-keyword">return</span> Results.NotFound();
    }

    queue.Enqueue(todo);

    <span class="hljs-keyword">return</span> Results.Accepted();
})
.WithApiVersionSet(versionSet)
.MapToApiVersion(version1);
</code></pre>
<pre><code class="lang-csharp">info: ApiFluentValidator.BackgroundServices.TodoBackgroundQueueService[<span class="hljs-number">0</span>]
      Todo Item found! Completing it ...
info: ApiFluentValidator.BackgroundServices.TodoBackgroundQueueService[<span class="hljs-number">0</span>]
      Todo Item <span class="hljs-keyword">is</span> completed.
</code></pre>
<h2 id="heading-quartznet-1">Quartz.NET</h2>
<p>First, it is necessary to install the nugget package <a target="_blank" href="https://www.nuget.org/packages/Quartz.AspNetCore">Quartz.AspNetCore</a>. For the background work, we will get all the Todos not completed and complete them. We need to create a class that implements the <code>IJob</code> interface that contains the asynchronous <code>Execute()</code> method. The <code>[DisallowConcurrentExecution]</code> attribute prevents <code>Quartz.NET</code> from trying to run the same job concurrently.</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">DisallowConcurrentExecution</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CompleteTodoItemJob</span> : <span class="hljs-title">IJob</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ILogger&lt;CompleteTodoItemJob&gt; _logger;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ITodoService _todoService;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CompleteTodoItemJob</span>(<span class="hljs-params">ILogger&lt;CompleteTodoItemJob&gt; logger, ITodoService todoService</span>)</span>
    {
        _logger = logger;
        _todoService = todoService;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Execute</span>(<span class="hljs-params">IJobExecutionContext context</span>)</span>
    {
        _logger.LogInformation(<span class="hljs-string">"Getting all not completed Todos!"</span>);
        <span class="hljs-keyword">var</span> todos = <span class="hljs-keyword">await</span> _todoService.GetAllNotCompleted();

        <span class="hljs-keyword">if</span>(todos.Count == <span class="hljs-number">0</span>)
            _logger.LogInformation(<span class="hljs-string">"There is no Todo to be completed!"</span>);

        <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">var</span> todo <span class="hljs-keyword">in</span> todos)
        {
            _logger.LogInformation(<span class="hljs-string">$"Completing the Todo: <span class="hljs-subst">{todo.Name}</span>"</span>);

            <span class="hljs-keyword">await</span> _todoService.CompleteTodo(todo);
        }
    }
}
</code></pre>
<p><code>Quartz.NET</code> has some simple schedules for running jobs, but one of the most common approaches is using a Cron expression that allows complex timer scheduling. For more information about Cron expression, check out this <a target="_blank" href="https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/crontriggers.html">link</a>.</p>
<p>We need to define a Jobkey, which links the job and its trigger. After that, we need to add the job that will run and finally, we define the trigger; in this example, it will run every 10 seconds. The <code>UseMicrosoftDependencyInjectionJobFactory</code> method allows jobs to receive services through the DI.</p>
<pre><code class="lang-csharp">builder.Services.AddQuartz(q =&gt;
{
    <span class="hljs-comment">// Create a "key" for the job</span>
    <span class="hljs-keyword">var</span> jobKey = <span class="hljs-keyword">new</span> JobKey(<span class="hljs-string">"CompleteTodoItemJob"</span>);

    q.UseMicrosoftDependencyInjectionJobFactory();

    <span class="hljs-comment">// Register the job with the DI container</span>
    q.AddJob&lt;CompleteTodoItemJob&gt;(opts =&gt; opts.WithIdentity(jobKey));

    <span class="hljs-comment">// Create a trigger for the job</span>
    q.AddTrigger(opts =&gt; opts
        .ForJob(jobKey) <span class="hljs-comment">// link to the CompleteTodoItemJob</span>
        .WithIdentity(<span class="hljs-string">"CompleteTodoItemJob-trigger"</span>) 
        .WithCronSchedule(<span class="hljs-string">"0/10 * * * * ?"</span>)); <span class="hljs-comment">// run every 10 seconds</span>

});
builder.Services.AddQuartzHostedService(q =&gt; q.WaitForJobsToComplete = <span class="hljs-literal">true</span>);
</code></pre>
<pre><code class="lang-csharp">info: ApiFluentValidator.BackgroundServices.Quartz.CompleteTodoItemJob[<span class="hljs-number">0</span>]
      Getting all not completed Todos!
info: ApiFluentValidator.BackgroundServices.Quartz.CompleteTodoItemJob[<span class="hljs-number">0</span>]
      There <span class="hljs-keyword">is</span> no Todo to be completed!
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">1.1</span> POST https:<span class="hljs-comment">//localhost:7063/v1/todoitems application/json 52</span>
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[<span class="hljs-number">0</span>]
      Executing endpoint <span class="hljs-string">'HTTP: POST v{version:apiVersion}/todoitems'</span>
info: Program[<span class="hljs-number">0</span>]
      Saving todoitem
info: Microsoft.EntityFrameworkCore.Update[<span class="hljs-number">30100</span>]
      Saved <span class="hljs-number">1</span> entities to <span class="hljs-keyword">in</span>-memory store.
info: Program[<span class="hljs-number">0</span>]
      TodoItem was saved
info: Microsoft.AspNetCore.Http.Result.CreatedResult[<span class="hljs-number">1</span>]
      Writing <span class="hljs-keyword">value</span> of type <span class="hljs-string">'ApiFluentValidator.Models.Todo'</span> with status code <span class="hljs-string">'201'</span>.
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[<span class="hljs-number">1</span>]
      Executed endpoint <span class="hljs-string">'HTTP: POST v{version:apiVersion}/todoitems'</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">1.1</span> POST https:<span class="hljs-comment">//localhost:7063/v1/todoitems application/json 52 - 201 - application/json;+charset=utf-8 131.6760ms</span>
info: ApiFluentValidator.BackgroundServices.Quartz.CompleteTodoItemJob[<span class="hljs-number">0</span>]
      Getting all not completed Todos!
info: ApiFluentValidator.BackgroundServices.Quartz.CompleteTodoItemJob[<span class="hljs-number">0</span>]
      Completing the Todo: Read a book
info: Microsoft.EntityFrameworkCore.Update[<span class="hljs-number">30100</span>]
      Saved <span class="hljs-number">1</span> entities to <span class="hljs-keyword">in</span>-memory store.
info: ApiFluentValidator.BackgroundServices.Quartz.CompleteTodoItemJob[<span class="hljs-number">0</span>]
      Getting all not completed Todos!
info: ApiFluentValidator.BackgroundServices.Quartz.CompleteTodoItemJob[<span class="hljs-number">0</span>]
      There <span class="hljs-keyword">is</span> no Todo to be completed!
</code></pre>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>You can find the complete code on my <a target="_blank" href="https://github.com/jhonatanfernando/api-fluent-validator/tree/bacckground-service">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Using Serilog  for logging in Asp.Net Core Minimal APIs]]></title><description><![CDATA[With Debug, File and ElasticSearch sinks.]]></description><link>https://blog.jhonatanoliveira.dev/using-serilog-for-logging-in-aspnet-core-minimal-apis</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/using-serilog-for-logging-in-aspnet-core-minimal-apis</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[serilog]]></category><category><![CDATA[logging]]></category><category><![CDATA[C#]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Mon, 12 Dec 2022 22:09:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670877482628/ARRjtdW0K.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the previous <a target="_blank" href="https://blog.jhonatanoliveira.dev/logging-in-aspnet-core-minimal-apis">blog post</a>, we talked about logging and we used a logging provider from Microsoft. In this blog post, we will use Serilog.</p>
<h1 id="heading-serilog">Serilog</h1>
<p>Like many other libraries for .NET, Serilog provides diagnostic logging to files, the console, and elsewhere. It can be used in classic .NET Framework applications, in Xamarin.Forms applications and applications running on the latest and greatest .NET 6.</p>
<h2 id="heading-sinks">Sinks</h2>
<p>Sinks are the way how and where the logs can be sent. Structured log events are written to sinks; each sink is responsible for writing it to its backend, database, store, etc. Serilog has a vast range of <a target="_blank" href="https://github.com/serilog/serilog/wiki/Provided-Sinks">sinks</a> that can be used. Each one of them is a nugget package that can be installed in the application. In this blog post, we will use three of them.</p>
<h3 id="heading-debug">Debug</h3>
<p>A Serilog sink that writes log events to the debug output window. For more details access the <a target="_blank" href="https://github.com/serilog/serilog-sinks-debug">GitHub</a> repository.</p>
<h3 id="heading-file">File</h3>
<p>A Serilog sink that writes events to one or more text files. With this sink is possible to define the following settings, for more details access the <a target="_blank" href="https://github.com/serilog/serilog-sinks-file">GitHub</a> repository.</p>
<ul>
<li><p><code>formatter</code>: log as JSON</p>
</li>
<li><p><code>path</code>: the log file path</p>
</li>
<li><p><code>fileSizeLimitBytes</code> : default: 1 GB, use <code>null</code> for unlimited</p>
</li>
<li><p><code>rollingInterval</code> : Specifies the frequency at which the log file should roll. default: “Day”</p>
</li>
<li><p><code>rollOnFileSizeLimit</code> : a new file will be created when the file size limit is reached default: <code>true</code></p>
</li>
<li><p><code>retainedFileCountLimit</code> : The maximum number of log files that will be retained including the current log file. default: 31 days.</p>
</li>
<li><p><code>shared</code>: to enable multi-process shared log files, default: <code>false</code></p>
</li>
</ul>
<h3 id="heading-elasticsearch">Elasticsearch</h3>
<p>The Serilog Elasticsearch sink project is a writer for the Serilog logging framework. This sink delivers the data to Elasticsearch, a NoSQL search engine. It has a lot of settings, for more details access the <a target="_blank" href="https://github.com/serilog-contrib/serilog-sinks-elasticsearch">GitHub</a> repository.</p>
<h1 id="heading-implementation">Implementation</h1>
<p>To use the sinks it is necessary to install the correct nugget package. The configuration for the logger can be done by code, XML <code>&lt;appSettings&gt;</code> configuration or JSON <code>appsettings.json</code> configuration.</p>
<p>For XML <code>&lt;appSettings&gt;</code> configuration is necessary to install the package <a target="_blank" href="https://www.nuget.org/packages/Serilog.Settings.AppSettings/">Serilog.Settings.AppSettings</a>.</p>
<p>For JSON <code>appsettings.json</code> configuration is necessary to install the package <a target="_blank" href="https://www.nuget.org/packages/Serilog.Settings.Configuration/">Serilog.Settings.Configuration</a>.</p>
<p>Another package that is recommended to install is <a target="_blank" href="https://www.nuget.org/packages/Serilog.AspNetCore/">Serilog.AspNetCore</a>. This package routes <a target="_blank" href="http://ASP.NET">ASP.NET</a> Core log messages through Serilog, so we can get information about <a target="_blank" href="http://ASP.NET">ASP.NET</a>'s internal operations written to the same Serilog sinks as our application events.</p>
<h2 id="heading-debug-1">Debug</h2>
<p>To use the Debug sink, install the package <a target="_blank" href="https://www.nuget.org/packages/Serilog.Sinks.Debug/">Serilog.Sinks.Debug</a>. After that, the output template can be configured if needed.</p>
<pre><code class="lang-csharp">builder.Logging.ClearProviders();
builder.Host.UseSerilog((hostContext, services, configuration) =&gt; {
    configuration
    .WriteTo.Debug(outputTemplate: <span class="hljs-string">"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"</span>);
});
</code></pre>
<p>The ILogger interface can be injected into the endpoints.</p>
<pre><code class="lang-csharp">app.MapGet(<span class="hljs-string">"/"</span>, (ILogger logger) =&gt;
{
    logger.Information(<span class="hljs-string">"Logging information."</span>);
    logger.Error(<span class="hljs-string">"Logging critical information."</span>);
    logger.Debug(<span class="hljs-string">"Logging debug information."</span>);
    logger.Error(<span class="hljs-string">"Logging error information."</span>);
    logger.Warning(<span class="hljs-string">"Logging warning."</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello World!"</span>;
});
</code></pre>
<p>This is an example of the output after running the app and calling the endpoint.</p>
<pre><code class="lang-plaintext">[10:48:35 INF] Now listening on: https://localhost:7063
[10:48:35 INF] Now listening on: http://localhost:5063
[10:48:35 INF] Application started. Press Ctrl+C to shut down.
[10:48:35 INF] Hosting environment: Development
[10:48:36 INF] Request starting HTTP/2 GET https://localhost:7063/_framework/aspnetcore-browser-refresh.js - -
[10:48:36 INF] Request starting HTTP/2 GET https://localhost:7063/_vs/browserLink - -
[10:48:37 INF] Request finished HTTP/2 GET https://localhost:7063/swagger/index.html - - - 200 - text/html;charset=utf-8 657.4176ms
[10:48:37 INF] Request finished HTTP/2 GET https://localhost:7063/_framework/aspnetcore-browser-refresh.js - - - 200 12006 application/javascript;+charset=utf-8 17.0781ms
'ApiFluentValidator.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.11\System.Net.WebSockets.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
[10:48:37 INF] Request finished HTTP/2 GET https://localhost:7063/_vs/browserLink - - - 200 - text/javascript;+charset=UTF-8 47.4439ms
[10:48:37 INF] Request finished HTTP/2 GET https://localhost:7063/swagger/v1/swagger.json - - - 200 - application/json;charset=utf-8 243.7456ms
[10:48:49 INF] BasicAuthentication was not authenticated. Failure message: Header Not Found.
[10:48:49 INF] Executing endpoint 'HTTP: GET /'
[10:48:49 INF] Logging information.
[10:48:49 ERR] Logging critical information.
[10:48:49 ERR] Logging error information.
[10:48:49 WRN] Logging warning.
[10:48:49 INF] Executed endpoint 'HTTP: GET /'
[10:48:49 INF] Request finished HTTP/2 GET https://localhost:7063/ - - - 200 - text/plain;+charset=utf-8 223.9726ms
</code></pre>
<p>Instead of writing the configuration by code, we can use the <code>appsettings</code> file to define the configuration.</p>
<pre><code class="lang-json">  <span class="hljs-string">"Serilog"</span>: {
    <span class="hljs-attr">"WriteTo"</span>: [
      {
        <span class="hljs-attr">"Name"</span>: <span class="hljs-string">"Debug"</span>,
        <span class="hljs-attr">"Args"</span>: {
          <span class="hljs-attr">"outputTemplate"</span>: <span class="hljs-string">"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} &lt;s:{SourceContext}&gt;{NewLine}{Exception}"</span>
        }
      }
    ]
  }
</code></pre>
<p>We also need to change the way to configure the Logger, it is necessary to inform the app that the configuration needs to be read.</p>
<pre><code class="lang-csharp">builder.Host.UseSerilog((context, services, configuration) =&gt; configuration
    .ReadFrom.Configuration(context.Configuration));
</code></pre>
<h2 id="heading-file-1">File</h2>
<p>The steps to use this sink is pretty much the same as Debug. First, it is necessary to install the nugget package <a target="_blank" href="https://www.nuget.org/packages/Serilog.Sinks.File/">Serilog.Sinks.File</a> after that is necessary to define the settings for the logger. A file will be created and will contain the app's log.</p>
<pre><code class="lang-csharp">builder.Logging.ClearProviders();
builder.Host.UseSerilog((hostContext, services, configuration) =&gt; {
    configuration
    .WriteTo.File(
      <span class="hljs-string">"diagnostics.txt"</span>,
       rollingInterval: RollingInterval.Day,
       fileSizeLimitBytes: <span class="hljs-number">10</span> * <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>,
       retainedFileCountLimit: <span class="hljs-number">2</span>,
       rollOnFileSizeLimit: <span class="hljs-literal">true</span>,
       shared: <span class="hljs-literal">true</span>,
       flushToDiskInterval: TimeSpan.FromSeconds(<span class="hljs-number">1</span>));
});
</code></pre>
<p>The same configuration can be done through the <code>appsettings</code> file. To load the configuration is the same code that was used for Debug.</p>
<pre><code class="lang-json">  <span class="hljs-string">"Serilog"</span>: {
    <span class="hljs-attr">"MinimumLevel"</span>: <span class="hljs-string">"Information"</span>,
    <span class="hljs-attr">"WriteTo"</span>: [
      {
        <span class="hljs-attr">"Name"</span>: <span class="hljs-string">"File"</span>,
        <span class="hljs-attr">"Args"</span>: {
          <span class="hljs-attr">"path"</span>: <span class="hljs-string">"diagnostics.txt"</span>,
          <span class="hljs-attr">"outputTemplate"</span>: <span class="hljs-string">"[{Timestamp:HH:mm:ss} {SourceContext} [{Level}] {Message}{NewLine}{Exception}"</span>,
          <span class="hljs-attr">"rollingInterval"</span>: <span class="hljs-string">"Day"</span>,
          <span class="hljs-attr">"fileSizeLimitBytes"</span>: <span class="hljs-number">4194304</span>,
          <span class="hljs-attr">"retainedFileCountLimit"</span>: <span class="hljs-number">2</span>,
          <span class="hljs-attr">"rollOnFileSizeLimit"</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">"shared"</span>: <span class="hljs-literal">true</span>
        }
      }
    ]
  }
</code></pre>
<h2 id="heading-elasticsearch-1">Elasticsearch</h2>
<p>First, we need to configure the environment to have ElasticSearch and Kibana running. I will not get into details about it because I think it deserves a blog post exclusive to it. You can access this <a target="_blank" href="https://www.elastic.co/guide/en/kibana/current/docker.html">link</a> to know how to configure ElasticSearch and Kibana with Docker.</p>
<p>To use the sink, it is necessary to install the nugget package <a target="_blank" href="https://www.nuget.org/packages/Serilog.Sinks.Elasticsearch">Serilog.Sinks.Elasticsearch</a> and then define the configuration for this sink.</p>
<pre><code class="lang-csharp">builder.Logging.ClearProviders();
builder.Host.UseSerilog((hostContext, services, configuration) =&gt;
{
    configuration
    .WriteTo.Elasticsearch(<span class="hljs-keyword">new</span> ElasticsearchSinkOptions(<span class="hljs-keyword">new</span> Uri(<span class="hljs-string">"http://localhost:9200"</span>))
    {
        FailureCallback = e =&gt; Console.WriteLine(<span class="hljs-string">"Unable to submit event "</span> + e.MessageTemplate),
        EmitEventFailure = EmitEventFailureHandling.WriteToSelfLog | EmitEventFailureHandling.WriteToFailureSink | EmitEventFailureHandling.RaiseCallback,
        QueueSizeLimit = <span class="hljs-number">100000</span>,
        BatchPostingLimit = <span class="hljs-number">50</span>,
        IndexFormat = <span class="hljs-string">"custom-index-{0:yyyy.MM}"</span>
    });
});
</code></pre>
<p>The configuration can be defined in the <code>appsettings</code> too.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"Serilog"</span>: {
    <span class="hljs-attr">"WriteTo"</span>: [{
        <span class="hljs-attr">"Name"</span>: <span class="hljs-string">"Elasticsearch"</span>,
        <span class="hljs-attr">"Args"</span>: {
          <span class="hljs-attr">"nodeUris"</span>: <span class="hljs-string">"http://localhost:9200;"</span>,
          <span class="hljs-attr">"indexFormat"</span>: <span class="hljs-string">"custom-index-{0:yyyy.MM}"</span>,
          <span class="hljs-attr">"templateName"</span>: <span class="hljs-string">"myCustomTemplate"</span>,
          <span class="hljs-attr">"typeName"</span>: <span class="hljs-string">"myCustomLogEventType"</span>,
          <span class="hljs-attr">"pipelineName"</span>: <span class="hljs-string">"myCustomPipelineName"</span>,
          <span class="hljs-attr">"batchPostingLimit"</span>: <span class="hljs-number">50</span>,
          <span class="hljs-attr">"batchAction"</span>: <span class="hljs-string">"Create"</span>,
          <span class="hljs-attr">"period"</span>: <span class="hljs-number">2</span>,
          <span class="hljs-attr">"inlineFields"</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">"restrictedToMinimumLevel"</span>: <span class="hljs-string">"Warning"</span>,
          <span class="hljs-attr">"bufferFileSizeLimitBytes"</span>: <span class="hljs-number">5242880</span>,
          <span class="hljs-attr">"bufferLogShippingInterval"</span>: <span class="hljs-number">5000</span>,
          <span class="hljs-attr">"bufferRetainedInvalidPayloadsLimitBytes"</span>: <span class="hljs-number">5000</span>,
          <span class="hljs-attr">"bufferFileCountLimit"</span>: <span class="hljs-number">31</span>,
          <span class="hljs-attr">"connectionTimeout"</span>: <span class="hljs-number">5</span>,
          <span class="hljs-attr">"emitEventFailure"</span>: <span class="hljs-string">"WriteToSelfLog"</span>,
          <span class="hljs-attr">"queueSizeLimit"</span>: <span class="hljs-string">"100000"</span>,
          <span class="hljs-attr">"autoRegisterTemplate"</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">"overwriteTemplate"</span>: <span class="hljs-literal">false</span>,
          <span class="hljs-attr">"registerTemplateFailure"</span>: <span class="hljs-string">"IndexAnyway"</span>,
          <span class="hljs-attr">"numberOfShards"</span>: <span class="hljs-number">20</span>,
          <span class="hljs-attr">"numberOfReplicas"</span>: <span class="hljs-number">10</span>
        }
    }]
  }
}
</code></pre>
<p>The ElasticSearch sink configuration has two important parameters, the ElasticSearch URL and the “IndexFormat”.</p>
<p>Kibana won’t show anything unless we create an index, so to do it, we need to access <a target="_blank" href="http://localhost:5601">http://localhost:5601</a>, go to <em>Discover</em> and then <em>Create Index Pattern</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670873185775/wSsanfxvY.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670873211470/nkQg18Gmn.png" alt class="image--center mx-auto" /></p>
<p>The pattern that was defined in the property <code>IndexFormat</code> will be used to create a new index. We will use the following pattern: <strong><em>custom-index-*</em></strong>, this will match all the indexes generated by the app.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670874691012/uRA0xYzsj.png" alt class="image--center mx-auto" /></p>
<p>To view the logs generated by the app we need to access the Discover link again. We also can search for specific logs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670875737261/6uvOmE0CS.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670876029406/pePEWpm5z.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-wrapping-up"><strong>Wrapping Up</strong></h1>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/api-fluent-validator/tree/logging-with-serilog">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Logging in Asp.Net Core Minimal APIs]]></title><description><![CDATA[This article describes logging in Asp.Net Core Minimal APIs. Logging is a means of tracking events that happen when some software runs. Logging is…]]></description><link>https://blog.jhonatanoliveira.dev/logging-in-aspnet-core-minimal-apis</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/logging-in-aspnet-core-minimal-apis</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[logging]]></category><category><![CDATA[minimal-apis]]></category><category><![CDATA[C#]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sat, 03 Dec 2022 17:25:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/660dcf8b9a06246e615e732b1c16f333.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article describes logging in Asp.Net Core Minimal APIs.</p>
<h1 id="heading-logging">Logging</h1>
<p>Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running.</p>
<p>.NET supports a logging API that works with a variety of built-in and third-party logging providers.</p>
<h2 id="heading-logging-api">Logging API</h2>
<p>Microsoft.Extensions.Logging is an extensible logging mechanism with plug-in providers for many common logging systems. That means it's easy to aggregate the logs from the entire app, including the framework and the code, into one place.</p>
<p>This logging mechanism makes writing logs easy. All of the first-party libraries that make up ASP.NET Core and EF Core use this abstraction.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669997639457/c319ac85-c868-44ad-97d6-8718270709a1.png" alt="logging-api.png" /></p>
<h3 id="heading-iloggerfactory">ILoggerFactory</h3>
<p>Represents a type used to configure the logging system and create instances of ILogger from the registered ILoggerProviders.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Microsoft.Extensions.Logging</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ILoggerFactory</span> : <span class="hljs-title">IDisposable</span>
    {
        <span class="hljs-function">ILogger <span class="hljs-title">CreateLogger</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> categoryName</span>)</span>;

        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddProvider</span>(<span class="hljs-params">ILoggerProvider provider</span>)</span>;
    }
}
</code></pre>
<h3 id="heading-iloggerprovider">ILoggerProvider</h3>
<p>The ILoggerProvider manages and creates an appropriate logger, specified by the logging category.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Microsoft.Extensions.Logging</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ILoggerProvider</span> : <span class="hljs-title">IDisposable</span>
    {
        <span class="hljs-function">ILogger <span class="hljs-title">CreateLogger</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> categoryName</span>)</span>;
    }
}
</code></pre>
<h3 id="heading-iloger">ILoger</h3>
<p>ILogger is responsible for writing a log message of a given log level and creating logging scopes. The interface only exposes some generic log methods which are used by extension methods making the logging easy.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Microsoft.Extensions.Logging</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ILogger</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Log</span>&lt;<span class="hljs-title">TState</span>&gt;(<span class="hljs-params">LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func&lt;TState, Exception?, <span class="hljs-keyword">string</span>&gt; formatter</span>)</span>;

        <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">IsEnabled</span>(<span class="hljs-params">LogLevel logLevel</span>)</span>;

        IDisposable? BeginScope&lt;TState&gt;(TState state) <span class="hljs-keyword">where</span> TState : notnull;
    }
}
</code></pre>
<h2 id="heading-logging-providers">Logging Providers</h2>
<p>The responsibility of the Logging providers is to persist logs, except for the Console provider, which only displays logs as standard output. For example, the Azure Application Insights provider stores logs in Azure Application Insights. Multiple providers can be enabled. Microsoft provides various logging providers as NuGet packages such as:</p>
<p><a target="_blank" href="https://www.nuget.org/packages/Microsoft.Extensions.Logging.Console/">Microsoft.Extensions.Logging.Console</a></p>
<p><a target="_blank" href="https://www.nuget.org/packages/Microsoft.Extensions.Logging.Debug/">Microsoft.Extensions.Logging.Debug</a></p>
<p><a target="_blank" href="https://www.nuget.org/packages/Microsoft.Extensions.Logging.AzureAppServices/">Microsoft.Extensions.Logging.AzureAppServices</a></p>
<p><a target="_blank" href="https://www.nuget.org/packages/Microsoft.Extensions.Logging.EventLog/">Microsoft.Extensions.Logging.EventLog</a></p>
<p><a target="_blank" href="https://www.nuget.org/packages/Microsoft.Extensions.Logging.EventSource/">Microsoft.Extensions.Logging.EventSource</a></p>
<p><a target="_blank" href="https://www.nuget.org/packages/Microsoft.Extensions.Logging.TraceSource/">Microsoft.Extensions.Logging.TraceSource</a></p>
<h3 id="heading-third-party-providers">Third-party providers</h3>
<p>They use the same logging abstraction, after installing the nugget package it is necessary to call an ILoggerFactory or ILoggingBuilder extension method provided by the logging framework.</p>
<p>These are just some third-party logging frameworks: <a target="_blank" href="https://github.com/elmahio/Elmah.Io.Extensions.Logging">elmah.io</a>, <a target="_blank" href="https://github.com/serilog/serilog-sinks-console">Serilog</a>, <a target="_blank" href="https://github.com/NLog/NLog.Extensions.Logging">Log4Net</a> and <a target="_blank" href="https://github.com/NLog/NLog.Extensions.Logging">NLog</a>.</p>
<h2 id="heading-log-levels">Log Levels</h2>
<p>The LogLevel specifies the minimum level to log for selected categories. They are a way of filtering important information about the system’s state and reducing information noise or alert fatigue. LogLevel indicates the severity of the log and ranges from 0 to 6:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670026231396/16860b88-58eb-47b8-b733-bebb3c8511a8.png" alt="Screenshot 2022-12-02 191020.png" /></p>
<h2 id="heading-log-scopes">Log Scopes</h2>
<p>Log Scopes are used when it is necessary to add the same values to every log message. For example, adding a database transaction id to every log message until that transaction is committed.</p>
<h1 id="heading-implementation">Implementation</h1>
<p>For this implementation the we will use the Microsoft.Extensions.Logging.Console package, so the first step is to install the package.</p>
<h2 id="heading-configuration">Configuration</h2>
<p>The first change in the code is to override the default set of logging providers.</p>
<pre><code class="lang-csharp">builder.Logging.ClearProviders();
builder.Logging.AddConsole();
</code></pre>
<p>Logging configuration is commonly provided by the Logging section of appsettings.json files. The following appsettings.Development.json file is what the app is using:</p>
<pre><code class="lang-csharp">{
  <span class="hljs-string">"Logging"</span>: {
    <span class="hljs-string">"LogLevel"</span>: {
      <span class="hljs-string">"Default"</span>: <span class="hljs-string">"Information"</span>,
      <span class="hljs-string">"Microsoft.AspNetCore"</span>: <span class="hljs-string">"Information"</span>,
      <span class="hljs-string">"Microsoft.Hosting.Lifetime"</span>: <span class="hljs-string">"Information"</span>,
      <span class="hljs-string">"Microsoft.EntityFrameworkCore"</span>: <span class="hljs-string">"Information"</span>
    },
    <span class="hljs-string">"Console"</span>: {
      <span class="hljs-string">"IncludeScopes"</span>: <span class="hljs-literal">false</span>,
      <span class="hljs-string">"LogLevel"</span>: {
        <span class="hljs-string">"Microsoft.EntityFrameworkCore"</span>: <span class="hljs-string">"Information"</span>,
        <span class="hljs-string">"Default"</span>: <span class="hljs-string">"Information"</span>
      }
    }
  },

  <span class="hljs-string">"AllowedHosts"</span>: <span class="hljs-string">"*"</span>,

  <span class="hljs-string">"TodoApiKey"</span>: <span class="hljs-string">"6298ce01e3a143ac9ddb1e9e37664a2b"</span>
}
</code></pre>
<p>This is the log when the app starts.</p>
<pre><code class="lang-csharp">info: Microsoft.Hosting.Lifetime[<span class="hljs-number">14</span>]
      Now listening <span class="hljs-keyword">on</span>: https:<span class="hljs-comment">//localhost:7063</span>
info: Microsoft.Hosting.Lifetime[<span class="hljs-number">14</span>]
      Now listening <span class="hljs-keyword">on</span>: http:<span class="hljs-comment">//localhost:5063</span>
info: Microsoft.Hosting.Lifetime[<span class="hljs-number">0</span>]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[<span class="hljs-number">0</span>]
      Hosting environment: Development
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/swagger/index.html - -</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/swagger/index.html - - - 200 - text/html;charset=utf-8 423.9127ms</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/_vs/browserLink - -</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/_framework/aspnetcore-browser-refresh.js - -</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/_framework/aspnetcore-browser-refresh.js - - - 200 12006 application/javascript;+charset=utf-8 9.2800ms</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/_vs/browserLink - - - 200 - text/javascript;+charset=UTF-8 20.1397ms</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/swagger/v1/swagger.json - -</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/swagger/v1/swagger.json - - - 200 - application/json;charset=utf-8 149.7433ms</span>
</code></pre>
<h2 id="heading-logging-1">Logging</h2>
<h3 id="heading-default-logger">Default Logger</h3>
<p>To create the logger that will be used in the app, the following code can be used. After that we can use the object logger to log the information.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> logger = LoggerFactory.Create(config =&gt;
{
    config.AddConsole();
}).CreateLogger(<span class="hljs-string">"Program"</span>);
</code></pre>
<pre><code class="lang-csharp">app.MapPost(<span class="hljs-string">"v{version:apiVersion}/todoitems"</span>, [Authorize] <span class="hljs-keyword">async</span> (IValidator&lt;Todo&gt; validator, Todo todo, TodoDb db) =&gt;
{
    <span class="hljs-keyword">try</span>
    {
        logger.LogInformation(<span class="hljs-string">"Saving todoitem"</span>);

        ValidationResult validationResult = <span class="hljs-keyword">await</span> validator.ValidateAsync(todo);

        <span class="hljs-keyword">if</span> (!validationResult.IsValid)
        {
            <span class="hljs-keyword">return</span> Results.ValidationProblem(validationResult.ToDictionary());
        }

        db.Todos.Add(todo);
        <span class="hljs-keyword">await</span> db.SaveChangesAsync();

        logger.LogInformation(<span class="hljs-string">"TodoItem was saved"</span>);

        <span class="hljs-keyword">return</span> Results.Created(<span class="hljs-string">$"/todoitems/<span class="hljs-subst">{todo.Id}</span>"</span>, todo);
    }
    <span class="hljs-keyword">catch</span>(Exception ex)
    {
        logger.LogError(ex, <span class="hljs-string">"An unexpected exception occured"</span>);
        <span class="hljs-keyword">return</span> Results.Problem();
    }
})
.WithApiVersionSet(versionSet)
.MapToApiVersion(version1);
</code></pre>
<pre><code class="lang-csharp">info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[<span class="hljs-number">63</span>]
      User profile <span class="hljs-keyword">is</span> available. Using <span class="hljs-string">'C:\Users\Jhonathan.oliveira\AppData\Local\ASP.NET\DataProtection-Keys'</span> <span class="hljs-keyword">as</span> key repository and Windows DPAPI to encrypt keys at rest.
info: Microsoft.Hosting.Lifetime[<span class="hljs-number">14</span>]
      Now listening <span class="hljs-keyword">on</span>: https:<span class="hljs-comment">//localhost:7063</span>
info: Microsoft.Hosting.Lifetime[<span class="hljs-number">14</span>]
      Now listening <span class="hljs-keyword">on</span>: http:<span class="hljs-comment">//localhost:5063</span>
info: Microsoft.Hosting.Lifetime[<span class="hljs-number">0</span>]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[<span class="hljs-number">0</span>]
      Hosting environment: Development
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/swagger/index.html - -</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/swagger/index.html - - - 200 - text/html;charset=utf-8 364.3598ms</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/_framework/aspnetcore-browser-refresh.js - -</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/_vs/browserLink - -</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/_framework/aspnetcore-browser-refresh.js - - - 200 12006 application/javascript;+charset=utf-8 11.4441ms</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/_vs/browserLink - - - 200 - text/javascript;+charset=UTF-8 20.3106ms</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/swagger/v1/swagger.json - -</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">2</span> GET https:<span class="hljs-comment">//localhost:7063/swagger/v1/swagger.json - - - 200 - application/json;charset=utf-8 131.3444ms</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">1.1</span> POST https:<span class="hljs-comment">//localhost:7063/user application/json 100</span>
info: ApiFluentValidator.Security.CustomBasicAuthenticationHandler[<span class="hljs-number">7</span>]
      BasicAuthentication was not authenticated. Failure message: Header Not Found.
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[<span class="hljs-number">0</span>]
      Executing endpoint <span class="hljs-string">'HTTP: POST /user'</span>
info: Microsoft.EntityFrameworkCore.Update[<span class="hljs-number">30100</span>]
      Saved <span class="hljs-number">1</span> entities to <span class="hljs-keyword">in</span>-memory store.
info: Microsoft.AspNetCore.Http.Result.CreatedResult[<span class="hljs-number">1</span>]
      Writing <span class="hljs-keyword">value</span> of type <span class="hljs-string">'ApiFluentValidator.Models.User'</span> with status code <span class="hljs-string">'201'</span>.
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[<span class="hljs-number">1</span>]
      Executed endpoint <span class="hljs-string">'HTTP: POST /user'</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">1.1</span> POST https:<span class="hljs-comment">//localhost:7063/user application/json 100 - 201 - application/json;+charset=utf-8 698.5075ms</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">1</span>]
      Request starting HTTP/<span class="hljs-number">1.1</span> POST https:<span class="hljs-comment">//localhost:7063/v1/todoitems application/json 51</span>
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[<span class="hljs-number">0</span>]
      Executing endpoint <span class="hljs-string">'HTTP: POST v{version:apiVersion}/todoitems'</span>
info: Program[<span class="hljs-number">0</span>]
      Saving todoitem
info: Microsoft.EntityFrameworkCore.Update[<span class="hljs-number">30100</span>]
      Saved <span class="hljs-number">1</span> entities to <span class="hljs-keyword">in</span>-memory store.
info: Program[<span class="hljs-number">0</span>]
      TodoItem was saved
info: Microsoft.AspNetCore.Http.Result.CreatedResult[<span class="hljs-number">1</span>]
      Writing <span class="hljs-keyword">value</span> of type <span class="hljs-string">'ApiFluentValidator.Models.Todo'</span> with status code <span class="hljs-string">'201'</span>.
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[<span class="hljs-number">1</span>]
      Executed endpoint <span class="hljs-string">'HTTP: POST v{version:apiVersion}/todoitems'</span>
info: Microsoft.AspNetCore.Hosting.Diagnostics[<span class="hljs-number">2</span>]
      Request finished HTTP/<span class="hljs-number">1.1</span> POST https:<span class="hljs-comment">//localhost:7063/v1/todoitems application/json 51 - 201 - application/json;+charset=utf-8 417.9473ms</span>
</code></pre>
<h3 id="heading-log-levels-1">Log Levels</h3>
<p>To log different levels in the app just need to use different methods, the following code shows which method can be used.</p>
<pre><code class="lang-csharp">app.MapGet(<span class="hljs-string">"/"</span>, () =&gt;
{
    logger.LogInformation(<span class="hljs-string">"Logging information."</span>);
    logger.LogCritical(<span class="hljs-string">"Logging critical information."</span>);
    logger.LogDebug(<span class="hljs-string">"Logging debug information."</span>);
    logger.LogError(<span class="hljs-string">"Logging error information."</span>);
    logger.LogTrace(<span class="hljs-string">"Logging trace"</span>);
    logger.LogWarning(<span class="hljs-string">"Logging warning."</span>);

    <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello World!"</span>;
});
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670085240309/f98406f0-3378-406a-879d-65ad3e83b535.png" alt="Screenshot 2022-12-03 113351.png" /></p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>The next article is also going to be about logging but using Serilog and Elastic Search. Stay tuned :)</p>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/api-fluent-validator">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[API Versioning with Asp.Net Core Minimal APIs]]></title><description><![CDATA[API versioning is the practice of managing changes to an API without breaking the client’s applications when new versions are developed. Versioning is an…]]></description><link>https://blog.jhonatanoliveira.dev/api-versioning-with-aspnet-core-minimal-apis</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/api-versioning-with-aspnet-core-minimal-apis</guid><category><![CDATA[versioning]]></category><category><![CDATA[api]]></category><category><![CDATA[dotnetcore]]></category><category><![CDATA[minimal-apis]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sun, 27 Nov 2022 16:31:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/npxXWgQ33ZQ/upload/v1669566890870/YFTHOzN1o.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-api-versioning">API Versioning</h1>
<p>API versioning is the practice of managing changes to an API without breaking the client’s applications when new versions are developed. Versioning is an integral part of the API design. A good API versioning strategy communicates the changes made and allows clients using an existing REST API and only migrate or update their applications to the recent versions when they are ready.</p>
<h2 id="heading-types-of-api-versioning">Types of API Versioning</h2>
<p>There are many ways to version an API, each approach has its own set of strengths and weaknesses in addressing changes based on their scope. This article will cover the three following ways.</p>
<h3 id="heading-uri">URI</h3>
<p>This is the most natural and straightforward approach. It includes the version number in the URL path and is often done with the prefix "v".</p>
<pre><code class="lang-csharp">http:<span class="hljs-comment">//www.example.com/api/v1/todos</span>
http:<span class="hljs-comment">//api.example.com/v1/todos</span>
</code></pre>
<h3 id="heading-query-parameter">Query Parameter</h3>
<p>In this approach the version number is added as a query param making it easier to switch to the newest version in case a query parameter is not specified.</p>
<pre><code class="lang-csharp">http:<span class="hljs-comment">//www.example.com/api/todos?version=1</span>
</code></pre>
<h3 id="heading-custom-headers">Custom Headers</h3>
<p>This technique adds custom headers with version numbers as an attribute. This approach differs from query and URI versioning because it doesn’t add filler content to the URI.</p>
<pre><code class="lang-csharp">Accept-version: v1
Accept-version: v2
</code></pre>
<h1 id="heading-implementation">Implementation</h1>
<p>To start the implementation first it is necessary to add the nugget package <a target="_blank" href="https://www.nuget.org/packages/Asp.Versioning.Http/">Asp.Versioning.Http</a>. Once it is added we will be able to use the extension methods *AddApiVersioning * to define the strategy, <em>WithApiVersionSet</em> to define the version of the endpoint and <em>HasApiVersion</em> to define with versions are supported by the endpoint.</p>
<h2 id="heading-configuration">Configuration</h2>
<p>The following code is creating the version numbers that will be used in the version set system.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> version1 = <span class="hljs-keyword">new</span> ApiVersion(<span class="hljs-number">1</span>);
<span class="hljs-keyword">var</span> version2 = <span class="hljs-keyword">new</span> ApiVersion(<span class="hljs-number">2</span>);
</code></pre>
<p>The version set tells the API versioning which versions are available to be used by the endpoints.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> versionSet = app.NewApiVersionSet()
                     .HasApiVersion(version1)
                     .HasApiVersion(version2)
                     .Build();
</code></pre>
<h2 id="heading-uri-1">URI</h2>
<p>For this approach it is necessary to modify the route adding a new parameter to MapGet, MapPost or MapPut methods. It will be added a new segment to the URL called version that is limited to the type apiVersion. This is a validation created by the versioning system to ensure that correct values are passed.</p>
<pre><code class="lang-csharp">app.MapGet(<span class="hljs-string">"v{version:apiVersion}/todoitems"</span>, [Authorize] <span class="hljs-keyword">async</span> (TodoDb db) =&gt;
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> db.Todos.ToListAsync();
})
.WithApiVersionSet(versionSet)
.HasApiVersions(<span class="hljs-keyword">new</span>[] { version1, version2 });
</code></pre>
<p>It is also necessary to configure the type of versioning that API will use. The following code shows how.</p>
<pre><code class="lang-csharp">builder.Services.AddApiVersioning(opt =&gt;
{
    opt.ApiVersionReader = <span class="hljs-keyword">new</span> UrlSegmentApiVersionReader();
});
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669560356825/_1_PFkXW_.png" alt="Screenshot 2022-11-27 094540.png" /></p>
<h2 id="heading-query-parameter-1">Query Parameter</h2>
<p>For this approach It is not necessary to change the route of the endpoint, it only adds the versioning type that will be used.</p>
<pre><code class="lang-csharp">builder.Services.AddApiVersioning(opt =&gt;
{
    opt.ApiVersionReader = <span class="hljs-keyword">new</span> QueryStringApiVersionReader(<span class="hljs-string">"version"</span>);
});
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669561044160/6pPdOqwdw.png" alt="Screenshot 2022-11-27 095651.png" /></p>
<h2 id="heading-custom-headers-1">Custom Headers</h2>
<p>This approach also does not require changing the route and it offers two ways to accomplish the versioning, using an extension to the Accept header or using a custom header.</p>
<h3 id="heading-media-type">Media Type</h3>
<pre><code class="lang-csharp">builder.Services.AddApiVersioning(opt =&gt;
{
    opt.ApiVersionReader = <span class="hljs-keyword">new</span> MediaTypeApiVersionReader(<span class="hljs-string">"version"</span>);
});
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669561682582/MyO3DlI13.png" alt="Screenshot 2022-11-27 100751.png" /></p>
<h3 id="heading-custom-header">Custom Header</h3>
<pre><code class="lang-csharp">builder.Services.AddApiVersioning(opt =&gt;
{
    opt.ApiVersionReader = <span class="hljs-keyword">new</span> HeaderApiVersionReader(<span class="hljs-string">"Api-Version"</span>);
});
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669562307096/d-3PwQkHI.png" alt="Screenshot 2022-11-27 101818.png" /></p>
<h2 id="heading-testing">Testing</h2>
<p>So now we can have two different versions of the same endpoint with different behaviors. In the following example the endpoint <em>todoitems</em> has version 1 with the old implementation and version 2 that changes the property <em>CompletedTimestamp</em>.</p>
<pre><code class="lang-csharp">app.MapPost(<span class="hljs-string">"v{version:apiVersion}/todoitems"</span>, [Authorize] <span class="hljs-keyword">async</span> (IValidator&lt;Todo&gt; validator, Todo todo, TodoDb db) =&gt;
{
    ValidationResult validationResult = <span class="hljs-keyword">await</span> validator.ValidateAsync(todo);

    <span class="hljs-keyword">if</span> (!validationResult.IsValid)
    {
        <span class="hljs-keyword">return</span> Results.ValidationProblem(validationResult.ToDictionary());
    }

    db.Todos.Add(todo);
    <span class="hljs-keyword">await</span> db.SaveChangesAsync();

    <span class="hljs-keyword">return</span> Results.Created(<span class="hljs-string">$"/todoitems/<span class="hljs-subst">{todo.Id}</span>"</span>, todo);
})
.WithApiVersionSet(versionSet)
.HasApiVersion(version1);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669586001099/xgXWZcjnX.png" alt="Screenshot 2022-11-27 165312.png" /></p>
<pre><code class="lang-csharp">app.MapPost(<span class="hljs-string">"v{version:apiVersion}/todoitems"</span>, [Authorize] <span class="hljs-keyword">async</span> (IValidator&lt;Todo&gt; validator, Todo todo, TodoDb db) =&gt;
{
    ValidationResult validationResult = <span class="hljs-keyword">await</span> validator.ValidateAsync(todo);

    <span class="hljs-keyword">if</span> (!validationResult.IsValid)
    {
        <span class="hljs-keyword">return</span> Results.ValidationProblem(validationResult.ToDictionary());
    }

    todo.CompletedTimestamp = DateTime.Now;
    db.Todos.Add(todo);
    <span class="hljs-keyword">await</span> db.SaveChangesAsync();

    <span class="hljs-keyword">return</span> Results.Created(<span class="hljs-string">$"/todoitems/<span class="hljs-subst">{todo.Id}</span>"</span>, todo);
})
.WithName(<span class="hljs-string">"newtodoitems"</span>)
.WithApiVersionSet(versionSet)
.HasApiVersion(version2);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669586049692/WY59sVBpj.png" alt="Screenshot 2022-11-27 165359.png" /></p>
<h2 id="heading-errors">Errors</h2>
<p>The API will return an error when a version is required and was not specified or when the endpoint does not support the version used.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669562578246/A7iYn0xma.png" alt="Screenshot 2022-11-27 102239.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669562585856/bTZPuSBhl.png" alt="Screenshot 2022-11-27 102215.png" /></p>
<p>When the API version is not specified, it can be defined a default version that will be used.</p>
<pre><code class="lang-csharp">builder.Services.AddApiVersioning(opt =&gt;
{
    opt.ApiVersionReader = <span class="hljs-keyword">new</span> HeaderApiVersionReader(<span class="hljs-string">"Api-Version"</span>);
    opt.DefaultApiVersion = version1;
    opt.AssumeDefaultVersionWhenUnspecified = <span class="hljs-literal">true</span>;
});
</code></pre>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/api-fluent-validator">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Creating a custom authentication handler with Asp.Net Core Minimal APIs]]></title><description><![CDATA[In this article I created a custom middleware for securing an Api. For this one let's change the implementation using a custom authentication handler…]]></description><link>https://blog.jhonatanoliveira.dev/creating-a-custom-authentication-handler-with-aspnet-core-minimal-apis</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/creating-a-custom-authentication-handler-with-aspnet-core-minimal-apis</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[authentication]]></category><category><![CDATA[minimal-apis]]></category><category><![CDATA[APIs]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Wed, 16 Nov 2022 16:45:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/6pflEeSzGUo/upload/v1668534607674/hjaiQiGZF.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this <a target="_blank" href="https://blog.jhonatanoliveira.dev/securing-aspnet-core-minimal-apis-with-a-custom-middleware">article</a> I created a custom middleware for securing an Api. For this one let's change the implementation using a custom authentication handler.</p>
<h2 id="heading-authentication">Authentication</h2>
<p>Authentication is the process that helps identify who are the users. The API authentication process validates the identity of the client attempting to make a connection by using an authentication protocol.</p>
<p>After the user is authenticated the authorization process starts. It is necessary user’s identity to identify the role of a user and act accordingly.</p>
<h3 id="heading-authentication-scheme">Authentication scheme</h3>
<p>Authentication schemes provide a way to collect credentials and determine the identity of a user and is useful as a mechanism for referring to the authentication, challenge, and forbid behaviors of the associated handler.</p>
<p>During authentication, Web Agents communicate with the Policy Server to determine the proper credentials that must be retrieved from a user who is requesting resources.</p>
<p>Authentication schemes are registered inside of the ConfigureServices method. It happens by calling the AddAuthentication method on the IServiceCollection instance passed to the method. It can register multiple authentication schemes, whereas only one of them will be a default scheme</p>
<h3 id="heading-authentication-handler">Authentication handler</h3>
<p>Authentication handlers can be created implementing the interface IAuthenticationHandler or deriving from AuthenticationHandler. Its primary responsibility is to authenticate users based on the authentication scheme's configuration and the incoming request context.</p>
<p>It is common to have a custom logic for authenticating a user inside of the handler.</p>
<p>It should return:</p>
<ul>
<li><p>'no result' or 'failure' if authentication is unsuccessful.</p>
</li>
<li><p>'success' if authentication is successful</p>
</li>
</ul>
<h1 id="heading-implementation">Implementation</h1>
<p>This implementation will be based in Basic Authentication, having a user model and a service to help in the authentication process.</p>
<h2 id="heading-context-and-userservice">Context and UserService</h2>
<p>The model is to represent the user.  A new property was added to the Context allowing user's data to be saved and retrieved  from the database through the UserService.  The service will be used in the endpoint and in the AuthenticationHandler.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
{   
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> FirstName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> LastName { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Username { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Password { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoDb</span> : <span class="hljs-title">DbContext</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoDb</span>(<span class="hljs-params">DbContextOptions&lt;TodoDb&gt; options</span>)
        : <span class="hljs-title">base</span>(<span class="hljs-params">options</span>)</span> { }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DbSet</span>&lt;<span class="hljs-title">Todo</span>&gt; Todos</span> =&gt; Set&lt;Todo&gt;();
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DbSet</span>&lt;<span class="hljs-title">User</span>&gt; Users</span> =&gt; Set&lt;User&gt;();
}
</code></pre>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IUserService</span>
    {
        <span class="hljs-function">Task&lt;User&gt; <span class="hljs-title">Authenticate</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> username, <span class="hljs-keyword">string</span> password</span>)</span>;
        Task&lt;IEnumerable&lt;User&gt;&gt; GetAll();
        <span class="hljs-function">Task <span class="hljs-title">Save</span>(<span class="hljs-params">User user</span>)</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">UserService</span> : <span class="hljs-title">IUserService</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TodoDb _dbContext;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UserService</span>(<span class="hljs-params">TodoDb todoDb</span>)</span>
        {
            <span class="hljs-keyword">this</span>._dbContext = todoDb;
        }   

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;User&gt; <span class="hljs-title">Authenticate</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> username, <span class="hljs-keyword">string</span> password</span>)</span>
        {
            <span class="hljs-keyword">var</span> user = <span class="hljs-keyword">await</span> Task.Run(() =&gt; _dbContext.Users.SingleOrDefault(x =&gt; x.Username == username &amp;&amp; x.Password == password));

            <span class="hljs-keyword">return</span> user;
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;IEnumerable&lt;User&gt;&gt; GetAll()
        {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> _dbContext.Users.ToListAsync();
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Save</span>(<span class="hljs-params">User user</span>)</span>
        {
            _dbContext.Users.Add(user);
            <span class="hljs-keyword">await</span> _dbContext.SaveChangesAsync();
        }
    }
</code></pre>
<h2 id="heading-custom-authentication-scheme">Custom Authentication Scheme</h2>
<p>Creating a custom authentication handler requires an AuthenticationSchemeOptions implementation. So this custom authentication scheme is to specify the scheme that will be used, for now it just derives from AuthenticationSchemeOptions.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CustomBasicAuthenticationSchemeOptions</span> : <span class="hljs-title">AuthenticationSchemeOptions</span>
{
}
</code></pre>
<h2 id="heading-custom-authentication-handler">Custom Authentication Handler</h2>
<p>The validations will be inside of the method <em>HandleAuthenticateAsync</em>. The first validation is to check if it contains the <em>Authorization</em> header. After that, the header value will be parsed and the username and password will be obtained from it. The UserService class will be used to authenticate the user.</p>
<p>At the end the claims will be created and then passed over an AuthenticationTicket so the middleware can continue with the execution of the pipeline.</p>
<pre><code class="lang-csharp"> <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CustomBasicAuthenticationHandler</span> : <span class="hljs-title">AuthenticationHandler</span>&lt;<span class="hljs-title">CustomBasicAuthenticationSchemeOptions</span>&gt;
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> IUserService _userService;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CustomBasicAuthenticationHandler</span>(<span class="hljs-params">IUserService userService, 
                                                IOptionsMonitor&lt;CustomBasicAuthenticationSchemeOptions&gt; options, 
                                                ILoggerFactory logger, 
                                                UrlEncoder encoder, 
                                                ISystemClock clock</span>) : <span class="hljs-title">base</span>(<span class="hljs-params">options, logger, encoder, clock</span>)</span>
        {
            _userService = userService;
        }

        <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">async</span> Task&lt;AuthenticateResult&gt; <span class="hljs-title">HandleAuthenticateAsync</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">if</span> (!Request.Headers.ContainsKey(Constants.AuthorizationHeaderName))
            {
                <span class="hljs-keyword">return</span> AuthenticateResult.Fail(<span class="hljs-string">"Header Not Found."</span>);
            }

            <span class="hljs-keyword">var</span> headerValue = Request.Headers[Constants.AuthorizationHeaderName];

            User? user = <span class="hljs-literal">null</span>;
            <span class="hljs-keyword">try</span>
            {
                <span class="hljs-keyword">var</span> authHeader = AuthenticationHeaderValue.Parse(headerValue);
                <span class="hljs-keyword">var</span> credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                <span class="hljs-keyword">var</span> credentials = Encoding.UTF8.GetString(credentialBytes).Split(<span class="hljs-keyword">new</span>[] { <span class="hljs-string">':'</span> }, <span class="hljs-number">2</span>);
                <span class="hljs-keyword">var</span> username = credentials[<span class="hljs-number">0</span>];
                <span class="hljs-keyword">var</span> password = credentials[<span class="hljs-number">1</span>];
                user = <span class="hljs-keyword">await</span> _userService.Authenticate(username, password);
            }
            <span class="hljs-keyword">catch</span>
            {
                <span class="hljs-keyword">return</span> AuthenticateResult.Fail(<span class="hljs-string">"Invalid Authorization Header"</span>);
            }

            <span class="hljs-keyword">if</span> (user == <span class="hljs-literal">null</span>)
                <span class="hljs-keyword">return</span> AuthenticateResult.Fail(<span class="hljs-string">"Invalid Username or Password"</span>);

            <span class="hljs-keyword">var</span> claims = <span class="hljs-keyword">new</span>[] {
                <span class="hljs-keyword">new</span> Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                <span class="hljs-keyword">new</span> Claim(ClaimTypes.Name, user.Username),
            };
            <span class="hljs-keyword">var</span> identity = <span class="hljs-keyword">new</span> ClaimsIdentity(claims, Scheme.Name);
            <span class="hljs-keyword">var</span> principal = <span class="hljs-keyword">new</span> ClaimsPrincipal(identity);
            <span class="hljs-keyword">var</span> ticket = <span class="hljs-keyword">new</span> AuthenticationTicket(principal, Scheme.Name);

            <span class="hljs-keyword">return</span> AuthenticateResult.Success(ticket);
        }
    }
</code></pre>
<h1 id="heading-registering">Registering</h1>
<p>The following code registers the custom authentication handler and the custom authentication scheme.</p>
<pre><code class="lang-csharp">builder.Services.AddAuthentication(<span class="hljs-string">"BasicAuthentication"</span>)
    .AddScheme&lt;CustomBasicAuthenticationSchemeOptions, CustomBasicAuthenticationHandler&gt;(<span class="hljs-string">"BasicAuthentication"</span>,<span class="hljs-literal">null</span>);
builder.Services.AddAuthorization();
</code></pre>
<p>And also needs to be added before app.UseHttpsRedirection();</p>
<pre><code class="lang-csharp">app.UseAuthentication();
app.UseAuthorization();
</code></pre>
<h1 id="heading-endpoints">Endpoints</h1>
<p>It was added a new endpoint to add new users.</p>
<pre><code class="lang-csharp">app.MapPost(<span class="hljs-string">"/user"</span>, <span class="hljs-keyword">async</span> (IUserService userService, User user) =&gt;
{
    <span class="hljs-keyword">await</span> userService.Save(user);

    <span class="hljs-keyword">return</span> Results.Created(<span class="hljs-string">$"/users/<span class="hljs-subst">{user.Id}</span>"</span>, user);
});
</code></pre>
<p>To add authorize requirements to the endpoints is necessary to decorate them using the <code>[Authorize]</code> attribute.</p>
<pre><code class="lang-csharp">app.MapPost(<span class="hljs-string">"/todoitems"</span>, [Authorize]  <span class="hljs-keyword">async</span> (IValidator&lt;Todo&gt; validator, Todo todo, TodoDb db) =&gt;
{
    ValidationResult validationResult = <span class="hljs-keyword">await</span> validator.ValidateAsync(todo);

    <span class="hljs-keyword">if</span> (!validationResult.IsValid)
    {
        <span class="hljs-keyword">return</span> Results.ValidationProblem(validationResult.ToDictionary());
    }

    db.Todos.Add(todo);
    <span class="hljs-keyword">await</span> db.SaveChangesAsync();

    <span class="hljs-keyword">return</span> Results.Created(<span class="hljs-string">$"/todoitems/<span class="hljs-subst">{todo.Id}</span>"</span>, todo);
});
</code></pre>
<h1 id="heading-testing">Testing</h1>
<p>The following images are showing the user being created, the basic authentication being added to the endpoint and the todoitem being created successfully.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668540055278/VwHecF7Ex.png" alt="AddUser.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668539981293/VfxXkvwx9.png" alt="AddAuthorization.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668540124190/E8EjDZZBu.png" alt="TodoCreated.png" /></p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>This is just a simple example of how to customize the authentication handler and authentication scheme.</p>
<p>There are things that could be improved such as: username and password being encrypted and using a better solution for authenticating the user.</p>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/api-fluent-validator">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Securing Asp.Net Core Minimal APIs with a custom Middleware]]></title><description><![CDATA[In this post we will create a custom middleware to secure a minimal API. To ensure that client requests access data securely, APIs use authorization. If…]]></description><link>https://blog.jhonatanoliveira.dev/securing-aspnet-core-minimal-apis-with-a-custom-middleware</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/securing-aspnet-core-minimal-apis-with-a-custom-middleware</guid><category><![CDATA[asp.net core]]></category><category><![CDATA[Middleware]]></category><category><![CDATA[APIs]]></category><category><![CDATA[authorization]]></category><category><![CDATA[apikey]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sat, 12 Nov 2022 17:59:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/eBRTYyjwpRY/upload/v1668206005793/nfwem8bD_.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this post we will create a custom middleware to secure a minimal API.</p>
<h1 id="heading-authorization">Authorization</h1>
<p>To ensure that client requests access data securely, APIs use authorization. If authentication refers to proving correct identity, authorization refers to allowing a certain action.</p>
<p>The authorization process can involve authenticating the sender of a request and confirming that they have permission to access or manipulate the relevant data.</p>
<p>There are a variety of authorization models such as: API key, Bearer token, Basic auth, OAuth and others.</p>
<h2 id="heading-api-key">Api Key</h2>
<p>The API is a key-value pair that you usually include either in the request headers or query parameters. The API key mainly functions as a way to identify the person making the API call (authenticating you to use the API).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668204192134/OSQA78eOm.png" alt="001_Client_API-1.png" /></p>
<h1 id="heading-middleware">Middleware</h1>
<p>Middleware is a component (class) in an application pipeline used to handle requests and responses. Each component:</p>
<ul>
<li><p>Chooses whether to pass the request to the next component in the pipeline.</p>
</li>
<li><p>Can perform work before and after the next component in the pipeline.</p>
</li>
</ul>
<p>The following diagram demonstrates how a middleware pipeline works, each middleware can perform operations before and after the next one.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668204770165/MqMAFXWvk.png" alt="request-delegate-pipeline.png" /></p>
<p>When an ASP.Net Core Web API is created it uses some default middlewares. The following diagram shows the complete request processing pipeline. It shows how the existing middlewares are ordered and where custom middlewares can be added.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668205933446/-RV4LWT96.png" alt="middleware-pipeline.png" /></p>
<h2 id="heading-creating-a-custom-middleware">Creating a custom middleware</h2>
<p>Middleware is generally encapsulated in a class and exposed with an extension method and must include:</p>
<ul>
<li><p>A public constructor with a parameter of type RequestDelegate.</p>
</li>
<li><p>A public method named Invoke or InvokeAsync. This method must:</p>
<ul>
<li><p>Return a Task.</p>
</li>
<li><p>Accept the first parameter of type HttpContext.</p>
</li>
</ul>
</li>
</ul>
<p>For this custom middleware a list of apiKeys values will be passed as a parameter also.</p>
<p>In the method InvokeAsync, the code will check if the header contains the ApiKey, otherwise the next middleware will not be called and an error 401 will be raised.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CustomApiKeyMiddleware</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> RequestDelegate _next;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> List&lt;<span class="hljs-keyword">string</span>&gt; _apiKeys;


    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CustomApiKeyMiddleware</span>(<span class="hljs-params">RequestDelegate next, <span class="hljs-keyword">string</span> apiKey</span>)
        : <span class="hljs-title">this</span>(<span class="hljs-params">next, new List&lt;<span class="hljs-keyword">string</span>&gt; { apiKey }</span>)</span>
    {
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CustomApiKeyMiddleware</span>(<span class="hljs-params">RequestDelegate next, List&lt;<span class="hljs-keyword">string</span>&gt; apiKeys</span>)</span>
    {
        _next = next;
        _apiKeys = apiKeys;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">InvokeAsync</span>(<span class="hljs-params">HttpContext context</span>)</span>
    {
        <span class="hljs-keyword">string</span> header = context.Request.Headers[Constants.ApiKeyHeaderName].ToString();

        <span class="hljs-keyword">if</span> ((context.Features.Get&lt;IEndpointFeature&gt;()?.Endpoint?.Metadata.Any((m) =&gt; m <span class="hljs-keyword">is</span> AllowAnonymousAttribute)).GetValueOrDefault() || 
            !<span class="hljs-keyword">string</span>.IsNullOrWhiteSpace(header) &amp;&amp; _apiKeys.Any((k) =&gt; k == header))
        {
            <span class="hljs-keyword">await</span> _next(context);
            <span class="hljs-keyword">return</span>;
        }

        context.Response.StatusCode = <span class="hljs-number">401</span>;
        context.Response.ContentType = <span class="hljs-string">"text/plain"</span>;
        <span class="hljs-keyword">await</span> context.Response.WriteAsync(<span class="hljs-string">"ApiKey is invalid."</span>);
    }
}
</code></pre>
<h1 id="heading-configuration">Configuration</h1>
<p>Now it is time to add the custom middleware in the pipeline. This is a middleware used to validate an Api key defined in the appsettings then should be called after all other middlewares and before UseEndpoints middleware.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Configure the HTTP request pipeline.</span>
<span class="hljs-keyword">if</span> (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseMiddleware&lt;CustomApiKeyMiddleware&gt;(app.Configuration.GetValue&lt;<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"TodoApiKey"</span>));

app.UseHttpsRedirection();

app.Run();
</code></pre>
<p>The following code adds the security definition for swagger, this way the authorize button will be visible and it allows users to add the ApiKey before executing the endpoints.</p>
<pre><code class="lang-csharp">builder.Services.AddSwaggerGen(c =&gt;
{
    c.SwaggerDoc(<span class="hljs-string">"v1"</span>, <span class="hljs-keyword">new</span> OpenApiInfo { Title = <span class="hljs-string">"TodoServiceApi"</span>, Version = <span class="hljs-string">"v1"</span> });

    c.AddSecurityDefinition(Constants.ApiKeyHeaderName, <span class="hljs-keyword">new</span> OpenApiSecurityScheme
    {
        Description = <span class="hljs-string">"Api key needed to access the endpoints. ApiKey: ApiKey"</span>,
        In = ParameterLocation.Header,
        Name = Constants.ApiKeyHeaderName,
        Type = SecuritySchemeType.ApiKey
    });

    c.AddSecurityRequirement(<span class="hljs-keyword">new</span> OpenApiSecurityRequirement
    {
        {
            <span class="hljs-keyword">new</span> OpenApiSecurityScheme
            {
                Name = Constants.ApiKeyHeaderName,
                Type = SecuritySchemeType.ApiKey,
                In = ParameterLocation.Header,
                Reference = <span class="hljs-keyword">new</span> OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = Constants.ApiKeyHeaderName,
                },
                },
                <span class="hljs-keyword">new</span> <span class="hljs-keyword">string</span>[] {}
            }
    });
});
</code></pre>
<h1 id="heading-testing-with-postman">Testing with Postman</h1>
<p>Executing the endpoint without providing an ApiKey will result in unauthorized error as can be seen in the following image.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668267893089/riXTZuQB4.png" alt="erroApikeyPostman.png" /></p>
<p>The ApiKey can be added in the Authorization tab, selecting API Key from the Type list and adding the values with the same key and value defined in the Api settings.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668268705990/PBIZKGI6G.png" alt="PostManConfig.png" /></p>
<h1 id="heading-testing-with-swagger">Testing with Swagger</h1>
<p>The same error will happen with swagger if the API Key is not provided.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668269002600/TZX2Chz6t.png" alt="SwaggerError.png" /></p>
<p>Because a security definition was added in swagger settings through the code, now the authorization page is available. The page can be displayed through the button Authorize at the top of the page or through the lock icon at the header of each endpoint.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668269323815/IkT6tNEJq.png" alt="swaggersecure.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668269678644/4FAWjxAqj.png" alt="swaggerAuth.png" /></p>
<p>After providing the ApiKey value, the page will be authorized to execute all the endpoints.</p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/api-fluent-validator">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Customize controls with .NET MAUI using PlatformViewFactory]]></title><description><![CDATA[In this post we will use PlatformViewFactory to customize a control without creating a new handler. When I wrote this article about customize controls with…]]></description><link>https://blog.jhonatanoliveira.dev/customize-controls-with-net-maui-using-platformviewfactory</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/customize-controls-with-net-maui-using-platformviewfactory</guid><category><![CDATA[#PlatformViewFactory]]></category><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[handler]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Fri, 11 Nov 2022 20:38:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/cckf4TsHAuw/upload/v1668012314775/tCh-_Cq-L.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this post we will use PlatformViewFactory to customize a control without creating a new handler.</p>
<h1 id="heading-contextualizing">Contextualizing</h1>
<p>When I wrote this <a target="_blank" href="https://blog.jhonatanoliveira.dev/customize-controls-with-handlers-with-net-maui">article</a> about customize controls with handlers, <a target="_blank" href="https://mobile.twitter.com/pj_souz">Pedro Jesus</a> replied to my <a target="_blank" href="https://twitter.com/pj_souz/status/1588711656020144128">tweet</a> suggesting to reimplement the control using PlatformViewFactory.</p>
<h1 id="heading-platformviewfactory">PlatformViewFactory</h1>
<p>It is a static property of ViewHandler that allows to return any implementation of ViewHandler or even the native control itself.</p>
<p>To register it should be added in MauiProgram.cs (or anywhere before Entry handlers will be created in the app).</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MauiProgram</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiApp <span class="hljs-title">CreateMauiApp</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp&lt;App&gt;()
            .ConfigureFonts(fonts =&gt;
            {
                fonts.AddFont(<span class="hljs-string">"OpenSans-Regular.ttf"</span>, <span class="hljs-string">"OpenSansRegular"</span>);
                fonts.AddFont(<span class="hljs-string">"OpenSans-Semibold.ttf"</span>, <span class="hljs-string">"OpenSansSemibold"</span>);
            });

        EntryImageHandler.Register();

        <span class="hljs-keyword">return</span> builder.Build();
    }
}
</code></pre>
<h1 id="heading-implementation">Implementation</h1>
<p>The difference using PlatformViewFactory is instead of creating a custom handler, the function receives the default EntryHandler allowing us to customize the native control as needed.</p>
<h2 id="heading-android-implementation">Android implementation</h2>
<pre><code class="lang-csharp">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EntryImageHandler</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Register</span>(<span class="hljs-params"></span>)</span>
        {
            EntryHandler.PlatformViewFactory = (handler) =&gt;
            {
                <span class="hljs-keyword">var</span> editText = <span class="hljs-keyword">new</span> AppCompatEditText(handler.Context);

                <span class="hljs-keyword">if</span> (handler.VirtualView <span class="hljs-keyword">is</span> not ImageEntry)
                    <span class="hljs-keyword">return</span> editText;

                <span class="hljs-keyword">var</span> element = handler.VirtualView <span class="hljs-keyword">as</span> ImageEntry;

                <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(element.Image))
                {
                    <span class="hljs-keyword">switch</span> (element.ImageAlignment)
                    {
                        <span class="hljs-keyword">case</span> ImageAlignment.Left:
                            editText.SetCompoundDrawablesWithIntrinsicBounds(GetDrawable(element.Image, handler.Context, element), <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>);
                            <span class="hljs-keyword">break</span>;
                        <span class="hljs-keyword">case</span> ImageAlignment.Right:
                            editText.SetCompoundDrawablesWithIntrinsicBounds(<span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, GetDrawable(element.Image, handler.Context, element), <span class="hljs-literal">null</span>);
                            <span class="hljs-keyword">break</span>;
                    }
                }

                editText.CompoundDrawablePadding = <span class="hljs-number">25</span>;
                editText.Background.SetColorFilter(Colors.White.ToAndroid(), PorterDuff.Mode.SrcAtop);

                <span class="hljs-keyword">return</span> editText;
            };
        }
    }
</code></pre>
<h2 id="heading-ios-implementation">iOS implementation</h2>
<pre><code class="lang-csharp"> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EntryImageHandler</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Register</span>(<span class="hljs-params"></span>)</span>
        {
            EntryHandler.PlatformViewFactory = (handler) =&gt;
            {
                <span class="hljs-keyword">var</span> textField = <span class="hljs-keyword">new</span> MauiTextField();

                <span class="hljs-keyword">if</span> (handler.VirtualView <span class="hljs-keyword">is</span> not ImageEntry)
                    <span class="hljs-keyword">return</span> textField;

                <span class="hljs-keyword">var</span> element = handler.VirtualView <span class="hljs-keyword">as</span> ImageEntry;

                <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(element.Image))
                {
                    <span class="hljs-keyword">switch</span> (element.ImageAlignment)
                    {
                        <span class="hljs-keyword">case</span> ImageAlignment.Left:
                            textField.LeftViewMode = UITextFieldViewMode.Always;
                            textField.LeftView = GetImageView(element.Image, element.ImageHeight, element.ImageWidth);
                            <span class="hljs-keyword">break</span>;
                        <span class="hljs-keyword">case</span> ImageAlignment.Right:
                            textField.RightViewMode = UITextFieldViewMode.Always;
                            textField.RightView = GetImageView(element.Image, element.ImageHeight, element.ImageWidth);
                            <span class="hljs-keyword">break</span>;
                    }
                }
                textField.BorderStyle = UITextBorderStyle.Line;
                textField.Layer.MasksToBounds = <span class="hljs-literal">true</span>;

                <span class="hljs-keyword">return</span> textField;
            };
        }
    }
</code></pre>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/custom-handlers-maui/tree/master/Article_002">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Asp.Net Core Minimal APIs with FluentValidation]]></title><description><![CDATA[In this post we will use how the model can be validated in minimal APIs and how FluentValidation can help us in this process. Minimal APIs are a new…]]></description><link>https://blog.jhonatanoliveira.dev/aspnet-core-minimal-apis-with-fluentvalidation</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/aspnet-core-minimal-apis-with-fluentvalidation</guid><category><![CDATA[minimal-apis]]></category><category><![CDATA[asp.net core]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Validation]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Wed, 09 Nov 2022 20:41:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/ehyV_XOZ4iA/upload/v1668002585045/I16M2qSFG.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this post we will use how the model can be validated in minimal APIs and how FluentValidation can help us in this process.</p>
<h1 id="heading-what-is-aspnet-core-minimal-apis">What is Asp.Net Core Minimal APIs</h1>
<p>Minimal APIs are a new feature in .NET 6 that helps the developers to create APIs with minimal dependencies in ASP.NET Core. Minimal APIs simplify API development through the use of a more compact code syntax.</p>
<h1 id="heading-validation">Validation</h1>
<p>In Web API development it is very important to validate the request before processing it. A lot of validations can be done and one of these validations is the Model.</p>
<p>Model Validation is a technique used to validate the model state before continuing with the request, checking if the data meets all the defined rules.</p>
<p>Minimal APIs do not come with any built-in support for validation, like <a target="_blank" href="https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0#validation-attributes">Data Annotations</a>, however we are free to create our own validation or use libraries like <a target="_blank" href="https://github.com/DamianEdwards/MiniValidation">MinimalValidation</a> and <a target="_blank" href="https://docs.fluentvalidation.net/en/latest/">FluentValidation</a>.</p>
<h2 id="heading-fluentvalidation">FluentValidation</h2>
<p>FluentValidation is a .NET library for building strongly-typed validation rules. It is an open source and uses a fluent interface and lambda expressions for creating validation rules.</p>
<p>FluentValidation has several built-in validators. The error message for each validator can contain special placeholders that will be filled in when the error message is constructed.</p>
<p>Some examples of validators:</p>
<pre><code class="lang-csharp">RuleFor(customer =&gt; customer.Surname).NotNull();

RuleFor(customer =&gt; customer.Surname).NotEmpty();

<span class="hljs-comment">//Not equal to a particular value</span>
RuleFor(customer =&gt; customer.Surname).NotEqual(<span class="hljs-string">"Foo"</span>);

<span class="hljs-comment">//Equal to a particular value</span>
RuleFor(customer =&gt; customer.Surname).Equal(<span class="hljs-string">"Foo"</span>);

<span class="hljs-comment">//Equal to another property</span>
RuleFor(customer =&gt; customer.Password).Equal(customer =&gt; customer.PasswordConfirmation);

<span class="hljs-comment">//must be between 1 and 250 chars (inclusive)</span>
RuleFor(customer =&gt; customer.Surname).Length(<span class="hljs-number">1</span>, <span class="hljs-number">250</span>); 

<span class="hljs-comment">//must be 10 chars or more</span>
RuleFor(customer =&gt; customer.Surname).MinimumLength(<span class="hljs-number">10</span>); 

<span class="hljs-comment">//Less than a particular value</span>
RuleFor(customer =&gt; customer.CreditLimit).LessThan(<span class="hljs-number">100</span>);

<span class="hljs-comment">//Less than another property</span>
RuleFor(customer =&gt; customer.CreditLimit).LessThan(customer =&gt; customer.MaxCreditLimit);
</code></pre>
<p>The complete list of validators can be found in <a target="_blank" href="https://docs.fluentvalidation.net/en/latest/built-in-validators.html">here</a>.</p>
<h1 id="heading-lets-code">Let's code</h1>
<p>First we will create our ASP.NET Core Web API. For Minimal API's we need to uncheck the option <em>Use controllers</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667914917370/v62mUo-Z3.png" alt="MinimalAPIs.png" /></p>
<p>The default code shows an implementation of one endpoint, <em>weatherforecast</em>, in the <em>Program.cs</em> file but we will create different endpoints using a different model.</p>
<h3 id="heading-model">Model</h3>
<p>This model will be used to create the context service, validator and the endpoints.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Todo</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> IsComplete { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> DateTimeOffset? CompletedTimestamp { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<h3 id="heading-context">Context</h3>
<p>To persist the data a DbContext implementation will be created and for this the nuget package <a target="_blank" href="https://www.nuget.org/packages/Microsoft.EntityFrameworkCore">Microsoft.EntityFrameworkCore</a> needs to be installed.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoDb</span> : <span class="hljs-title">DbContext</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoDb</span>(<span class="hljs-params">DbContextOptions&lt;TodoDb&gt; options</span>)
        : <span class="hljs-title">base</span>(<span class="hljs-params">options</span>)</span> { }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DbSet</span>&lt;<span class="hljs-title">Todo</span>&gt; Todos</span> =&gt; Set&lt;Todo&gt;();
}
</code></pre>
<h3 id="heading-validator">Validator</h3>
<p>To create the validator is necessary to install the nuget package <a target="_blank" href="https://www.nuget.org/packages/FluentValidation.AspNetCore/11.2.2">FluentValidation.AspNetCore</a>.</p>
<p>With this library is possible to define the rules for each property of the class used in the request of the endpoint, can be the model or a <a target="_blank" href="https://en.wikipedia.org/wiki/Data_transfer_object">DTO</a>, for this post it will be created for the model.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TodoValidator</span> : <span class="hljs-title">AbstractValidator</span>&lt;<span class="hljs-title">Todo</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TodoValidator</span>(<span class="hljs-params"></span>)</span>
    {
        RuleFor(m =&gt; m.Name).NotEmpty().WithMessage(<span class="hljs-string">"The field 'Name' is required."</span>);
        RuleFor(m =&gt; m.IsComplete).NotEmpty();
        RuleFor(m =&gt; m.CompletedTimestamp).LessThanOrEqualTo(DateTime.Now);
    }
}
</code></pre>
<p>The validator has rules for three properties: Name, IsComplete and CompletedTimestamp. Name and IsComplete are required and the Name has a custom message. For the property CompletedTimestamp should be less than or equal to the current date.</p>
<h3 id="heading-settings">Settings</h3>
<p>Before using the validator and the dbContext it is necessary to add them in the services of the services collection of the API.</p>
<pre><code class="lang-csharp">builder.Services.AddDbContext&lt;TodoDb&gt;(opt =&gt; opt.UseInMemoryDatabase(<span class="hljs-string">"TodoList"</span>));
builder.Services.AddScoped&lt;IValidator&lt;Todo&gt;, TodoValidator&gt;();
</code></pre>
<h3 id="heading-endpoints">Endpoints</h3>
<p>The validator and the dbContext will be injected to the endpoint and the model can be validated before being persisted.</p>
<pre><code class="lang-csharp">app.MapPost(<span class="hljs-string">"/todoitems"</span>, <span class="hljs-keyword">async</span> (IValidator&lt;Todo&gt; validator, Todo todo, TodoDb db) =&gt;
{
    ValidationResult validationResult = <span class="hljs-keyword">await</span> validator.ValidateAsync(todo);

    <span class="hljs-keyword">if</span> (!validationResult.IsValid)
    {
        <span class="hljs-keyword">return</span> Results.ValidationProblem(validationResult.ToDictionary());
    }

    db.Todos.Add(todo);
    <span class="hljs-keyword">await</span> db.SaveChangesAsync();

    <span class="hljs-keyword">return</span> Results.Created(<span class="hljs-string">$"/todoitems/<span class="hljs-subst">{todo.Id}</span>"</span>, todo);
});
</code></pre>
<h3 id="heading-results">Results</h3>
<p>The property CompletedTimestamp is not required so it will be validated only when it has a value.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668002307740/Geqfs9mz1.png" alt="Validation00.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668002505113/bVwn5N54i.png" alt="validation001.png" /></p>
<p>The properties Name and IsComplete are required, so they need to have value to continue. For the property Name the message was customized.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668002748635/U4TR9JyHx.png" alt="Validation01.png" /></p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/api-fluent-validator">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Customize controls with handlers with .NET MAUI]]></title><description><![CDATA[maui,android,ios,handlers,.net,dotnet]]></description><link>https://blog.jhonatanoliveira.dev/customize-controls-with-handlers-with-net-maui</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/customize-controls-with-handlers-with-net-maui</guid><category><![CDATA[handler]]></category><category><![CDATA[#maui]]></category><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sat, 05 Nov 2022 00:58:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/DIp71kvwXhU/upload/v1667606751382/jzuiIKOlnP.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It is very common during the development of mobile applications to create or customize controls. In this post we will see how we can do this with handlers in .NET MAUI.</p>
<h1 id="heading-ways-to-create-and-customize-net-maui-controls">Ways to create and customize .NET MAUI Controls</h1>
<p>There is more than one way to create and customize controls with .NET MAUI. The following list shows five different ways to acomplish it.</p>
<ol>
<li><p>Using Custom Renderers (Xamarin.Forms Architecture).</p>
</li>
<li><p>Using Custom Handlers.</p>
</li>
<li><p>Using ContentView.</p>
</li>
<li><p>Using TemplatedView (Templated Controls).</p>
</li>
<li><p>Using GraphicsView (Drawn controls)</p>
</li>
</ol>
<h1 id="heading-handlers">Handlers</h1>
<p>A key concept of .NET MAUI handlers is mappers. Each handler typically provides a property mapper, and sometimes a command mapper, that maps the cross-platform control's API to the native view's API. For example, on iOS a handler maps a .NET MAUI Button to an iOS UIButton. On Android, the Button is mapped to an AppCompatButton:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667503127532/S8EtyKio4.png" alt="button-handler.png" /></p>
<p>Handlers can be customized to augment the appearance and behavior of a cross-platform control beyond the customization that's possible through the control's API.</p>
<p>Handlers can be accessed through a control-specific interface provided derived from IView interface, it means that we can use handlers in any control that implements the interface IView.</p>
<h1 id="heading-creating-an-imageentry-control">Creating an ImageEntry control</h1>
<p>The .NET MAUI Entry is a single-line text input control that implements the IEntry interface. On iOS, the EntryHandler maps the Entry to an iOS UITextField. On Android, the Entry is mapped to an AppCompatEditText, and on Windows the Entry is mapped to a TextBox.</p>
<p>Depending on the control that we are creating, we can use the interface <code>IView</code> to be more generic or something more specific such as Entry or Button classes. The same idea applies for the handlers, we can create a custom handler that inherits from ViewHandler or just use a specific handler like EntryHandler.</p>
<p>The ImageEntry control that we will create is an Entry that has some properties that a common Entry does not have such as Image. The idea is to allow the developers to define an image to be displayed inside of the control and some other properties.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Article_002.Controls</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ImageEntry</span> : <span class="hljs-title">Entry</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ImageEntry</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">this</span>.HeightRequest = <span class="hljs-number">50</span>;
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> BindableProperty ImageProperty =
            BindableProperty.Create(<span class="hljs-keyword">nameof</span>(Image), <span class="hljs-keyword">typeof</span>(<span class="hljs-keyword">string</span>), <span class="hljs-keyword">typeof</span>(ImageEntry), <span class="hljs-keyword">string</span>.Empty);

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> BindableProperty ImageHeightProperty =
             BindableProperty.Create(<span class="hljs-keyword">nameof</span>(ImageHeight), <span class="hljs-keyword">typeof</span>(<span class="hljs-keyword">int</span>), <span class="hljs-keyword">typeof</span>(ImageEntry), <span class="hljs-number">40</span>);

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> BindableProperty ImageWidthProperty =
            BindableProperty.Create(<span class="hljs-keyword">nameof</span>(ImageWidth), <span class="hljs-keyword">typeof</span>(<span class="hljs-keyword">int</span>), <span class="hljs-keyword">typeof</span>(ImageEntry), <span class="hljs-number">40</span>);

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> BindableProperty ImageAlignmentProperty =
            BindableProperty.Create(<span class="hljs-keyword">nameof</span>(ImageAlignment), <span class="hljs-keyword">typeof</span>(ImageAlignment), <span class="hljs-keyword">typeof</span>(ImageEntry), ImageAlignment.Left);


        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> ImageWidth
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> (<span class="hljs-keyword">int</span>)GetValue(ImageWidthProperty); }
            <span class="hljs-keyword">set</span> { SetValue(ImageWidthProperty, <span class="hljs-keyword">value</span>); }
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> ImageHeight
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> (<span class="hljs-keyword">int</span>)GetValue(ImageHeightProperty); }
            <span class="hljs-keyword">set</span> { SetValue(ImageHeightProperty, <span class="hljs-keyword">value</span>); }
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Image
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> (<span class="hljs-keyword">string</span>)GetValue(ImageProperty); }
            <span class="hljs-keyword">set</span> { SetValue(ImageProperty, <span class="hljs-keyword">value</span>); }
        }

        <span class="hljs-keyword">public</span> ImageAlignment ImageAlignment
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> (ImageAlignment)GetValue(ImageAlignmentProperty); }
            <span class="hljs-keyword">set</span> { SetValue(ImageAlignmentProperty, <span class="hljs-keyword">value</span>); }
        }
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> ImageAlignment
    {
        Left,
        Right
    }
}
</code></pre>
<h1 id="heading-creating-the-custom-handlers">Creating the Custom Handlers</h1>
<p>The next step is to create the handlers, for this post only the handlers for Android and iOS will be created. Different from Xamarin.Forms that was necessary to use the ExportRenderer attribute for registering the Renderer, in .NET MAUI the handler registration is slightly different, we need to use AppHostBuilder and the AddHandler method to register the Handler.</p>
<p>The following codes are the implementation of the handler for Android and iOS.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Android.Content;
<span class="hljs-keyword">using</span> Android.Content.Res;
<span class="hljs-keyword">using</span> Android.Graphics;
<span class="hljs-keyword">using</span> Android.Graphics.Drawables;
<span class="hljs-keyword">using</span> Android.Widget;
<span class="hljs-keyword">using</span> AndroidX.AppCompat.Widget;
<span class="hljs-keyword">using</span> AndroidX.Core.Content;
<span class="hljs-keyword">using</span> AndroidX.Core.Graphics;
<span class="hljs-keyword">using</span> Article_002.Controls;
<span class="hljs-keyword">using</span> Microsoft.Maui.Controls.Compatibility.Platform.Android;
<span class="hljs-keyword">using</span> Microsoft.Maui.Controls.Platform;
<span class="hljs-keyword">using</span> Microsoft.Maui.Handlers;
<span class="hljs-keyword">using</span> Microsoft.Maui.Platform;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Article_002.Platforms.Android.Renderes</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ImageEntryRenderer</span> : <span class="hljs-title">EntryHandler</span>
    {
        <span class="hljs-keyword">private</span> ImageEntry element;

        <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> AppCompatEditText <span class="hljs-title">CreatePlatformView</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">var</span> editText = <span class="hljs-keyword">new</span> AppCompatEditText(Context);
            element = VirtualView <span class="hljs-keyword">as</span> ImageEntry;

            <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(element.Image))
            {
                <span class="hljs-keyword">switch</span> (element.ImageAlignment)
                {
                    <span class="hljs-keyword">case</span> ImageAlignment.Left:
                        editText.SetCompoundDrawablesWithIntrinsicBounds(GetDrawable(element.Image), <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>);
                        <span class="hljs-keyword">break</span>;
                    <span class="hljs-keyword">case</span> ImageAlignment.Right:
                        editText.SetCompoundDrawablesWithIntrinsicBounds(<span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, GetDrawable(element.Image), <span class="hljs-literal">null</span>);
                        <span class="hljs-keyword">break</span>;
                }
            }

            editText.CompoundDrawablePadding = <span class="hljs-number">25</span>;
            editText.Background.SetColorFilter(Colors.White.ToAndroid(), PorterDuff.Mode.SrcAtop);

            <span class="hljs-keyword">return</span> editText;
        }

        <span class="hljs-function"><span class="hljs-keyword">private</span> BitmapDrawable <span class="hljs-title">GetDrawable</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> imageEntryImage</span>)</span>
        {
            <span class="hljs-keyword">int</span> resID = Context.Resources.GetIdentifier(imageEntryImage, <span class="hljs-string">"drawable"</span>, <span class="hljs-keyword">this</span>.Context.PackageName);
            <span class="hljs-keyword">var</span> drawable = ContextCompat.GetDrawable(Context, resID);
            <span class="hljs-keyword">var</span> bitmap = drawableToBitmap(drawable);

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> BitmapDrawable(Bitmap.CreateScaledBitmap(bitmap, element.ImageWidth * <span class="hljs-number">2</span>, element.ImageHeight * <span class="hljs-number">2</span>, <span class="hljs-literal">true</span>));
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> Bitmap <span class="hljs-title">drawableToBitmap</span>(<span class="hljs-params">Drawable drawable</span>)</span>
        {
            <span class="hljs-keyword">if</span> (drawable <span class="hljs-keyword">is</span> BitmapDrawable) {
                <span class="hljs-keyword">return</span> ((BitmapDrawable)drawable).Bitmap;
            }

            <span class="hljs-keyword">int</span> width = drawable.IntrinsicWidth;
            width = width &gt; <span class="hljs-number">0</span> ? width : <span class="hljs-number">1</span>;
            <span class="hljs-keyword">int</span> height = drawable.IntrinsicHeight;
            height = height &gt; <span class="hljs-number">0</span> ? height : <span class="hljs-number">1</span>;

            Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
            Canvas canvas = <span class="hljs-keyword">new</span> Canvas(bitmap);
            drawable.SetBounds(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, canvas.Width, canvas.Height);
            drawable.Draw(canvas);

            <span class="hljs-keyword">return</span> bitmap;
        }
    }
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Article_002.Controls;
<span class="hljs-keyword">using</span> Microsoft.Maui.Handlers;
<span class="hljs-keyword">using</span> Microsoft.Maui.Platform;
<span class="hljs-keyword">using</span> System.Drawing;
<span class="hljs-keyword">using</span> UIKit;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Article_002.Platforms.iOS.Renderes</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ImageEntryRenderer</span> : <span class="hljs-title">EntryHandler</span>
    {
        <span class="hljs-keyword">private</span> ImageEntry element;

        <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> MauiTextField <span class="hljs-title">CreatePlatformView</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">var</span> textField = <span class="hljs-keyword">new</span> MauiTextField();
            element = VirtualView <span class="hljs-keyword">as</span> ImageEntry;

            <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(element.Image))
            {
                <span class="hljs-keyword">switch</span> (element.ImageAlignment)
                {
                    <span class="hljs-keyword">case</span> ImageAlignment.Left:
                        textField.LeftViewMode = UITextFieldViewMode.Always;
                        textField.LeftView = GetImageView(element.Image, element.ImageHeight, element.ImageWidth);
                        <span class="hljs-keyword">break</span>;
                    <span class="hljs-keyword">case</span> ImageAlignment.Right:
                        textField.RightViewMode = UITextFieldViewMode.Always;
                        textField.RightView = GetImageView(element.Image, element.ImageHeight, element.ImageWidth);
                        <span class="hljs-keyword">break</span>;
                }
            }

            textField.BorderStyle = UITextBorderStyle.Line;
            textField.Layer.MasksToBounds = <span class="hljs-literal">true</span>;

            <span class="hljs-keyword">return</span> textField;
        }

        <span class="hljs-function"><span class="hljs-keyword">private</span> UIView <span class="hljs-title">GetImageView</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> imagePath, <span class="hljs-keyword">int</span> height, <span class="hljs-keyword">int</span> width</span>)</span>
        {
            <span class="hljs-keyword">var</span> uiImageView = <span class="hljs-keyword">new</span> UIImageView(UIImage.FromFile(imagePath))
            {
                Frame = <span class="hljs-keyword">new</span> RectangleF(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, width, height)
            };
            UIView objLeftView = <span class="hljs-keyword">new</span> UIView(<span class="hljs-keyword">new</span> System.Drawing.Rectangle(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, width + <span class="hljs-number">10</span>, height));
            objLeftView.AddSubview(uiImageView);

            <span class="hljs-keyword">return</span> objLeftView;
        }
    }
}
</code></pre>
<p>In .NET MAUI to have access to the native implementation of the control we need to override the method <code>CreatePlatformView</code>, so this way we can instantiate the native control and change the properties that we need/want.</p>
<p>In summary, we are defining the image alignment and loading the image by name using the property that was created.</p>
<p>Something that is also different in .NET MAUI is the way that we work with images. It is not necessary to have the images in the platform projects, everything is located in the Resources folder.</p>
<h1 id="heading-registering-the-handlers">Registering the Handlers</h1>
<p>Now it is time to register the handlers. We can use the method ConfigureMauiHandlers from the class MauiAppBuilder to add the handlers.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Article_002.Controls;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Article_002</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MauiProgram</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> MauiApp <span class="hljs-title">CreateMauiApp</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp&lt;App&gt;()
            .ConfigureFonts(fonts =&gt;
            {
                fonts.AddFont(<span class="hljs-string">"OpenSans-Regular.ttf"</span>, <span class="hljs-string">"OpenSansRegular"</span>);
                fonts.AddFont(<span class="hljs-string">"OpenSans-Semibold.ttf"</span>, <span class="hljs-string">"OpenSansSemibold"</span>);
            })
                    .ConfigureMauiHandlers((handlers) =&gt; {
<span class="hljs-meta">#<span class="hljs-meta-keyword">if</span> ANDROID</span>
                        handlers.AddHandler(<span class="hljs-keyword">typeof</span>(ImageEntry), <span class="hljs-keyword">typeof</span>(Platforms.Android.Renderes.ImageEntryRenderer));

<span class="hljs-meta">#<span class="hljs-meta-keyword">elif</span> IOS                    </span>
                        handlers.AddHandler(<span class="hljs-keyword">typeof</span>(ImageEntry), <span class="hljs-keyword">typeof</span>(Platforms.iOS.Renderes.ImageEntryRenderer));
<span class="hljs-meta">#<span class="hljs-meta-keyword">endif</span></span>
                    });

        <span class="hljs-keyword">return</span> builder.Build();
    }
}
</code></pre>
<p>With the compile directives will help to apply the correct handler to the specific platform.</p>
<h1 id="heading-using-the-imageentry">Using the ImageEntry</h1>
<p>With everything in place we can use the control in our application, for this we just need to add the namespace in the XAML of the page so the control can be recognized.</p>
<pre><code class="lang-csharp">&lt;?xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"utf-8"</span> ?&gt;
&lt;ContentPage xmlns=<span class="hljs-string">"http://schemas.microsoft.com/dotnet/2021/maui"</span>
             xmlns:x=<span class="hljs-string">"http://schemas.microsoft.com/winfx/2009/xaml"</span>
             xmlns:local=<span class="hljs-string">"clr-namespace:Article_002.Controls"</span>
             BackgroundColor=<span class="hljs-string">"{StaticResource Primary}"</span>
             x:Class=<span class="hljs-string">"Article_002.MainPage"</span>&gt;

    &lt;ScrollView&gt;
        &lt;VerticalStackLayout Spacing=<span class="hljs-string">"10"</span>&gt;


            &lt;local:ImageEntry TextColor=<span class="hljs-string">"{StaticResource Black}"</span> 
                        PlaceholderColor=<span class="hljs-string">"{StaticResource White}"</span> 
                        Image=<span class="hljs-string">"user"</span> 
                        Placeholder=<span class="hljs-string">"Email"</span> 
                        HorizontalOptions=<span class="hljs-string">"FillAndExpand"</span>/&gt;

            &lt;local:ImageEntry TextColor=<span class="hljs-string">"{StaticResource Black}"</span> 
                    PlaceholderColor=<span class="hljs-string">"{StaticResource White}"</span>  
                    Image=<span class="hljs-string">"password"</span> 
                    Placeholder=<span class="hljs-string">"Password"</span> 
                    HorizontalOptions=<span class="hljs-string">"FillAndExpand"</span>/&gt;

            &lt;Button HeightRequest=<span class="hljs-string">"50"</span> 
                         TextColor=<span class="hljs-string">"{StaticResource White}"</span> 
                         Text=<span class="hljs-string">"Login"</span>  
                         BackgroundColor=<span class="hljs-string">"{StaticResource primary}"</span>
                         HorizontalOptions=<span class="hljs-string">"FillAndExpand"</span>/&gt;

            &lt;Label  Text=<span class="hljs-string">"Forgot password"</span> 
                        HorizontalOptions=<span class="hljs-string">"Center"</span> 
                        TextColor=<span class="hljs-string">"{StaticResource White}"</span>/&gt;

            &lt;Label Margin=<span class="hljs-string">"0,0,0,20"</span> Text=<span class="hljs-string">"I don't have an account"</span> VerticalOptions=<span class="hljs-string">"EndAndExpand"</span>
                        HorizontalOptions=<span class="hljs-string">"Center"</span> 
                        TextColor=<span class="hljs-string">"{StaticResource White}"</span>&gt;
            &lt;/Label&gt;
        &lt;/VerticalStackLayout&gt;
    &lt;/ScrollView&gt;

&lt;/ContentPage&gt;
</code></pre>
<p>We should see the results like this for Android and iOS.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667608866235/2wwWSw9JG.png" alt="Screen Shot 2022-11-04 at 8.39.49 PM.png" /></p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>This is how we can create or customize a control in .NET MAUI using custom handlers. You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/custom-handlers-maui">GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Angular Dependency Injection — One Service, Multiple Implementations]]></title><description><![CDATA[angular, service, dependecy injection, oop]]></description><link>https://blog.jhonatanoliveira.dev/angular-dependency-injection-one-service-multiple-implementations</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/angular-dependency-injection-one-service-multiple-implementations</guid><category><![CDATA[Angular]]></category><category><![CDATA[dependency injection]]></category><category><![CDATA[services]]></category><category><![CDATA[oop]]></category><category><![CDATA[dependency inversion]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Wed, 02 Nov 2022 01:22:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/xG8IQMqMITM/upload/v1667361831182/MDDwK2IdJ.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this post we will learn what is dependecy injection and how to inject multiple implementations of one service into a component.</p>
<h1 id="heading-what-is-dependency-injection">What Is Dependency Injection?</h1>
<p>By Wikipedia, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.</p>
<p>The practice of dependency injection is made possible by following the dependency inversion principle. Dependency inversion is a key part of building loosely coupled applications, since implementation details can be written to depend on and implement higher-level abstractions, rather than the other way around. The resulting applications are more testable, modular, and maintainable as a result.</p>
<p>In Angular, dependencies are typically services, but they also can be values, such as strings or functions. An injector for an application instantiates dependencies when needed, using a configured provider of the service or value.</p>
<h1 id="heading-creating-an-injectable-service">Creating an injectable service</h1>
<p>Creating services in Angular can be done using Angular CLI or just adding a new file in the project. The advantage of using Angular CLI is having everything done and ready to be used.</p>
<p>This is the Angular CLI command to generate a new service.</p>
<pre><code class="lang-csharp">ng generate service products/product
</code></pre>
<p>After the command you sould have your ProductService like this:</p>
<pre><code class="lang-csharp">import { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

@Injectable({
  providedIn: <span class="hljs-string">'root'</span>
})
export <span class="hljs-keyword">class</span> <span class="hljs-title">ProductService</span> {

  constructor() { }
}
</code></pre>
<p>The <code>@Injectable()</code> decorator specifies that Angular can use this class in the DI system. The metadata, providedIn: 'root', means that the ProductService is visible throughout the application.</p>
<p>If you decide to not use Angular CLI command to create your services, remember that you will need to add the decorator <code>@Injectable()</code>.</p>
<h1 id="heading-injecting-services">Injecting services</h1>
<p>To inject a service as a dependency into a component or into an other service is very easy, you just need to add a constructor argument with the type of the service that you want to use.</p>
<p>First of all, let's create a new component using Angular CLI.</p>
<pre><code class="lang-csharp">ng generate component products
</code></pre>
<p>After creating the component we will add the ProductService to it. The following code is the Product component after the dependecy to the service was added.</p>
<pre><code class="lang-csharp">import { Component, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
import { ProductService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./product.service'</span>;

@Component({
  selector: <span class="hljs-string">'app-products'</span>,
  templateUrl: <span class="hljs-string">'./products.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./products.component.css'</span>]
})
export <span class="hljs-keyword">class</span> <span class="hljs-title">ProductsComponent</span> <span class="hljs-title">implements</span> <span class="hljs-title">OnInit</span> {

  constructor(<span class="hljs-keyword">private</span> productService: ProductService) { }

  ngOnInit(): <span class="hljs-keyword">void</span> {
  }

}
</code></pre>
<p>In runtime the component will receive the instance of productService ready to be used.</p>
<h1 id="heading-the-example">The example</h1>
<p>Let's picture the situation when we need a different implementation of ProductService running in dev and another running in production.</p>
<p>So the idea is to have an Interface of the service and different implementations of it. The Class Diagram represents the idea of what we want to implement.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667276692514/5QkzIytKT.png" alt="Screen Shot 2022-11-01 at 12.24.37 AM.png" /></p>
<p>To have this solution in place we need to use the dependency injection differently than we've used it before.</p>
<h1 id="heading-injecting-multiple-services">Injecting multiple services</h1>
<p>Angular has dependency providers that allow dependency injection not only for classes but also for other values such as boolean, string, date, and objects.</p>
<p>We could have chosen <code>useFactory</code> for this implementation. The <code>useFactory</code> provider key lets us create a dependency object by calling a factory function. With this approach we would be responsible to create the instance of the service that needs to be injected.</p>
<p>Using <code>InjectionToken</code> will allow us to inject an interface, callable type, array of parameterized type. Our component will receive an array of the <em>IProductService</em>, that in runtime will contain the instance of the services <em>ProductProdService</em> and <em>ProductDevService</em>.</p>
<p>The <code>useClass</code> provider key lets us create and return a new instance of the specified class, so we will use it with <code>InjectionToken</code>. We can use this type of provider to substitute an alternative implementation, for example, implement a different strategy or extend the default class.</p>
<h1 id="heading-lets-code">Let’s code</h1>
<p>First we will create the interface <em>IProductService</em> and the services <em>ProductProdService</em> and <em>ProductDevService</em>.</p>
<pre><code class="lang-csharp">import { Injectable, InjectionToken } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

export <span class="hljs-keyword">const</span> productServiceToken = <span class="hljs-keyword">new</span> InjectionToken&lt;ProductService&gt;(<span class="hljs-string">"ProductService"</span>);

export <span class="hljs-keyword">interface</span> <span class="hljs-title">ProductService</span> {

  isProduction: boolean;

  getAllProducts(): <span class="hljs-keyword">void</span>;

}
</code></pre>
<p>The responsibility of <code>InjectionToken</code> class here is to ensure that the token is unique, this way another developer won’t be able to create another token with the same value.</p>
<pre><code class="lang-csharp">import { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
import { ProductService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./product.service'</span>;

@Injectable({
  providedIn: <span class="hljs-string">'root'</span>
})
export <span class="hljs-keyword">class</span> <span class="hljs-title">ProductProdService</span> <span class="hljs-title">implements</span> <span class="hljs-title">ProductService</span> {

  constructor() { }

  isProduction = <span class="hljs-literal">true</span>;

  getAllProducts(): <span class="hljs-keyword">void</span> {
    console.log(<span class="hljs-string">'getting data from Prod'</span>);
  }
}
</code></pre>
<pre><code class="lang-csharp">import { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
import { ProductService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./product.service'</span>;

@Injectable({
  providedIn: <span class="hljs-string">'root'</span>
})
export <span class="hljs-keyword">class</span> <span class="hljs-title">ProductDevService</span> <span class="hljs-title">implements</span> <span class="hljs-title">ProductService</span> {

  constructor() { }
  isProduction = <span class="hljs-literal">false</span>;

  getAllProducts(): <span class="hljs-keyword">void</span> {
    console.log(<span class="hljs-string">'getting data from Dev'</span>);
  }
}
</code></pre>
<p>The next step is to configure the dependency providers so this way both implementations of our service can be injected into our component. The following code is from <code>app.module.ts</code> . You can see that was used <code>productServiceToken</code> to inform Angular which service is being registered, <code>useClass</code> is to register which classes will be used and <code>multi</code> is because we have multiple dependencies for a inject token.</p>
<pre><code class="lang-csharp">import { NgModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
import { BrowserModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;

import { AppRoutingModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app-routing.module'</span>;
import { AppComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.component'</span>;
import { ProductProdService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./products/product-prod.service'</span>;
import { productServiceToken } <span class="hljs-keyword">from</span> <span class="hljs-string">'./products/product.service'</span>;
import { ProductDevService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./products/product-dev.service'</span>;
import { ProductsComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./products/products.component'</span>;

@NgModule({
  declarations: [
    AppComponent,
    ProductsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {
      provide: productServiceToken,
      useClass: ProductDevService,
      multi: <span class="hljs-literal">true</span>,
    },
    {
      provide: productServiceToken,
      useClass: ProductProdService,
      multi: <span class="hljs-literal">true</span>,
    }
  ],
  bootstrap: [AppComponent]
})
export <span class="hljs-keyword">class</span> <span class="hljs-title">AppModule</span> { }
</code></pre>
<p>Now our component is ready to receive an array of <code>IProductService</code> in the constructor and we can define which service it will use. For this example, one service will be used in <code>Dev</code> and the other in <code>Prod</code>.</p>
<pre><code class="lang-csharp">import { Component, Inject, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
import { ProductService, productServiceToken } <span class="hljs-keyword">from</span> <span class="hljs-string">'./product.service'</span>;
import { environment } <span class="hljs-keyword">from</span> <span class="hljs-string">'src/environments/environment'</span>;

@Component({
  selector: <span class="hljs-string">'app-products'</span>,
  templateUrl: <span class="hljs-string">'./products.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./products.component.css'</span>]
})
export <span class="hljs-keyword">class</span> <span class="hljs-title">ProductsComponent</span> <span class="hljs-title">implements</span> <span class="hljs-title">OnInit</span> {
  <span class="hljs-keyword">private</span> productService: ProductService;
  constructor(@Inject(productServiceToken) <span class="hljs-keyword">private</span> productServices: ProductService[]) { 

      <span class="hljs-keyword">this</span>.productService = <span class="hljs-keyword">this</span>.getService();
  }

  ngOnInit(): <span class="hljs-keyword">void</span> {
    <span class="hljs-keyword">this</span>.productService.getAllProducts();
  }

  getService(): ProductService {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.productServices.find(p=&gt; p.isProduction == environment.production)!;
  } 

}
</code></pre>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/angular-multi-impl-services">GitHub</a></p>
]]></content:encoded></item><item><title><![CDATA[Google Login Integration with .NET MAUI]]></title><description><![CDATA[Social login uses information from social networking sites to facilitate logins on third-party applications and platforms. The goal is to make the login…]]></description><link>https://blog.jhonatanoliveira.dev/google-login-integration-with-net-maui</link><guid isPermaLink="true">https://blog.jhonatanoliveira.dev/google-login-integration-with-net-maui</guid><category><![CDATA[.NET]]></category><category><![CDATA[#dotnet-maui]]></category><category><![CDATA[Google]]></category><category><![CDATA[authentication]]></category><category><![CDATA[Android]]></category><dc:creator><![CDATA[Jhonatan Oliveira]]></dc:creator><pubDate>Sat, 29 Oct 2022 17:03:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/A6qNzfJXRGQ/upload/v1667062686152/eaHWHH1kg.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Social login uses information from social networking sites to facilitate logins on third-party applications and platforms. The goal is to make the login process easier for users. The process is designed to simplify sign-in and registration experiences, providing a convenient alternative to mandatory account creation, allowing users to skip the registration procedures.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667054100438/QCuHJ3I3l.png" alt="Y_M2nOfCM2FQ4TyZOTid3x7ZZ1l2goWcfWZek42BiF6G3IoRoQ6570OrW3uoAJBI54uK9K1fW57ZuQndhJVM4qJ4dls-Sdd6m3KfPYvUIrVmcWvT_k1n5j3XY_8xbzXDknpQ1_Uh.png" /></p>
<p>In summary, social sign-on it helps users and developers. In this post, we are going to learn what is necessary to implement a Google authentication with .Net MAUI.</p>
<h1 id="heading-how-does-social-login-work">How does social login work?</h1>
<p>Social login can be done in three steps:</p>
<ol>
<li><p>The user enters an app and selects their chosen social network.</p>
</li>
<li><p>The social network provider receives a login request and authenticates the user. At this stage, users need to accept the access permissions of the app.</p>
</li>
<li><p>The user will get access to the app once the social provider has confirmed their identity.</p>
</li>
</ol>
<p>The Google OAuth 2.0 endpoint supports applications that are installed on devices such as computers, mobile devices, and tablets.</p>
<p>The authorization sequence begins when your application redirects a browser to a Google URL; the URL includes query parameters that indicate the type of access being requested. Google handles the user authentication, session selection, and user consent. The result is an authorization code, which the application can exchange for an access token and a refresh token.</p>
<p>The diagram shows the process described above.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667054890109/oAtJYfLs2.png" alt="authorization-code.png" /></p>
<h1 id="heading-google-project-creation">Google project creation</h1>
<p>Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server.</p>
<p>The first step is to create a new <a target="_blank" href="https://console.cloud.google.com/projectcreate">project</a> in Google Cloud. Accessing the link you should see something like the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667055519216/ep35I4L25.png" alt="Screen Shot 2022-10-29 at 10.58.14 AM.png" /></p>
<p>The next step is to create the Credentials. Using this <a target="_blank" href="https://console.developers.google.com/apis/credentials">link</a>, we need to click on Create Credentials and then OAuth Client ID.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667056105216/WzsuFmqU_.png" alt="Screen Shot 2022-10-29 at 11.05.52 AM.png" /></p>
<p>The Consent and App Information pages should be fill in with information that is necessary for your mobile application.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667056519755/pl7C70nxO.png" alt="Screen Shot 2022-10-29 at 11.09.45 AM.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667056525802/WA6PK5Xok.png" alt="Screen Shot 2022-10-29 at 11.10.54 AM.png" class="image--right mx-auto mr-0" /></p>
<p>After defining the information of our application, we can finalize the creation of the Client Id, choosing Android in the application type field.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667056678341/v6ikxkHiw.png" alt="Screen Shot 2022-10-29 at 11.17.23 AM.png" /></p>
<p>In the following page we need to provide the package name of the application that can be found in the Manifest.xml file and the SHA-1 fingerprint.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667057252141/W8sg6O0QX.png" alt="Screen Shot 2022-10-29 at 11.23.40 AM.png" /></p>
<p>Regarding the SHA-1 fingerprint, you can get the fingerprint code using the steps in the following link.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/xamarin/android/deploy-test/signing/keystore-signature?tabs=macos">https://learn.microsoft.com/en-us/xamarin/android/deploy-test/signing/keystore-signature?tabs=macos</a></div>
<p> </p>
<p>After the process, a json file will be generated with some information that we will use to authenticate. Below there is a sample of the json file.</p>
<pre><code class="lang-csharp">{<span class="hljs-string">"installed"</span>:{<span class="hljs-string">"client_id"</span>:<span class="hljs-string">"1076424481260-0tkbph8l6l0gebqcbahnkk4v4oio589f.apps.googleusercontent.com"</span>,<span class="hljs-string">"project_id"</span>:<span class="hljs-string">"lofty-tokenizer-367014"</span>,<span class="hljs-string">"auth_uri"</span>:<span class="hljs-string">"https://accounts.google.com/o/oauth2/auth"</span>,<span class="hljs-string">"token_uri"</span>:<span class="hljs-string">"https://oauth2.googleapis.com/token"</span>,<span class="hljs-string">"auth_provider_x509_cert_url"</span>:<span class="hljs-string">"https://www.googleapis.com/oauth2/v1/certs"</span>}}
</code></pre>
<h1 id="heading-lets-code">Let's code</h1>
<p>For this post, we will use <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/communication/authentication?tabs=android">WebAuthenticator</a>. The WebAuthenticator API takes care of launching the url in the browser and waiting until the callback is received. If the user cancels the flow at any point, a TaskCanceledException is thrown.</p>
<p>First, we will define the URL's necessary for the authentication process. Most of the values will be found in the clientId json file. The callback URL can have any value, here I chose to use the same value of the android package name.</p>
<p>The scopes can be defined during the App Registration process in Google Cloud, for this example I am using only one.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> authUrl = <span class="hljs-string">$"<span class="hljs-subst">{Constants.Google.auth_uri}</span>?response_type=code"</span> +
                    <span class="hljs-string">$"&amp;redirect_uri=com.maui.login://"</span> +
                    <span class="hljs-string">$"&amp;client_id=<span class="hljs-subst">{Constants.Google.client_id}</span>"</span> +
                    <span class="hljs-string">$"&amp;scope=https://www.googleapis.com/auth/userinfo.email"</span> +
                    <span class="hljs-string">$"&amp;include_granted_scopes=true"</span> +
                    <span class="hljs-string">$"&amp;state=state_parameter_passthrough_value"</span>;


<span class="hljs-keyword">var</span> callbackUrl = <span class="hljs-string">"com.maui.login://"</span>;
</code></pre>
<p>The following code will open the browser, starting the authentication process.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> WebAuthenticator.AuthenticateAsync(<span class="hljs-keyword">new</span> WebAuthenticatorOptions()
                        {
                            Url = <span class="hljs-keyword">new</span> Uri(authUrl),
                            CallbackUrl = <span class="hljs-keyword">new</span> Uri(callbackUrl)
                        });
</code></pre>
<p>Like we saw in the beginning of the post, after the user authenticates and consents, the app will get the Authorization Token that will be used to request the Access Token using the Token URL that can be found in the clientId json file.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> codeToken = response.Properties[<span class="hljs-string">"code"</span>];

<span class="hljs-keyword">var</span> parameters = <span class="hljs-keyword">new</span> FormUrlEncodedContent(<span class="hljs-keyword">new</span>[]
{
        <span class="hljs-keyword">new</span> KeyValuePair&lt;<span class="hljs-keyword">string</span>,<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"grant_type"</span>,<span class="hljs-string">"authorization_code"</span>),
        <span class="hljs-keyword">new</span> KeyValuePair&lt;<span class="hljs-keyword">string</span>,<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"client_id"</span>,Constants.Google.client_id),
        <span class="hljs-keyword">new</span> KeyValuePair&lt;<span class="hljs-keyword">string</span>,<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"redirect_uri"</span>,callbackUrl),
        <span class="hljs-keyword">new</span> KeyValuePair&lt;<span class="hljs-keyword">string</span>,<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"code"</span>,codeToken),
});

HttpClient client = <span class="hljs-keyword">new</span> HttpClient();
<span class="hljs-keyword">var</span> accessTokenResponse = <span class="hljs-keyword">await</span> client.PostAsync(Constants.Google.token_ur, parameters);

LoginResponse loginResponse;

<span class="hljs-keyword">if</span> (accessTokenResponse.IsSuccessStatusCode)
{
     <span class="hljs-keyword">var</span> data = <span class="hljs-keyword">await</span> accessTokenResponse.Content.ReadAsStringAsync();
     loginResponse = JsonConvert.DeserializeObject&lt;LoginResponse&gt;(data);
}
</code></pre>
<p>The full code of the authentication is displayed below.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Android.App;
<span class="hljs-keyword">using</span> Article_001.Models;
<span class="hljs-keyword">using</span> Newtonsoft.Json;
<span class="hljs-keyword">using</span> System;
<span class="hljs-keyword">using</span> System.Collections.Generic;
<span class="hljs-keyword">using</span> System.Linq;
<span class="hljs-keyword">using</span> System.Text;
<span class="hljs-keyword">using</span> System.Threading.Tasks;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Article_001.ViewModels</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MainPageViewModel</span>
    {
        <span class="hljs-keyword">public</span> Command LoginCommand
                =&gt; <span class="hljs-keyword">new</span> Command(<span class="hljs-keyword">async</span> () =&gt;
                {
                    <span class="hljs-keyword">var</span> authUrl = <span class="hljs-string">$"<span class="hljs-subst">{Constants.Google.auth_uri}</span>?response_type=code"</span> +
                    <span class="hljs-string">$"&amp;redirect_uri=com.maui.login://"</span> +
                    <span class="hljs-string">$"&amp;client_id=<span class="hljs-subst">{Constants.Google.client_id}</span>"</span> +
                    <span class="hljs-string">$"&amp;scope=https://www.googleapis.com/auth/userinfo.email"</span> +
                    <span class="hljs-string">$"&amp;include_granted_scopes=true"</span> +
                    <span class="hljs-string">$"&amp;state=state_parameter_passthrough_value"</span>;


                    <span class="hljs-keyword">var</span> callbackUrl = <span class="hljs-string">"com.maui.login://"</span>;

                    <span class="hljs-keyword">try</span>
                    {
                        <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> WebAuthenticator.AuthenticateAsync(<span class="hljs-keyword">new</span> WebAuthenticatorOptions()
                        {
                            Url = <span class="hljs-keyword">new</span> Uri(authUrl),
                            CallbackUrl = <span class="hljs-keyword">new</span> Uri(callbackUrl)
                        });

                        <span class="hljs-keyword">var</span> codeToken = response.Properties[<span class="hljs-string">"code"</span>];

                        <span class="hljs-keyword">var</span> parameters = <span class="hljs-keyword">new</span> FormUrlEncodedContent(<span class="hljs-keyword">new</span>[]
                        {
                        <span class="hljs-keyword">new</span> KeyValuePair&lt;<span class="hljs-keyword">string</span>,<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"grant_type"</span>,<span class="hljs-string">"authorization_code"</span>),
                        <span class="hljs-keyword">new</span> KeyValuePair&lt;<span class="hljs-keyword">string</span>,<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"client_id"</span>,Constants.Google.client_id),
                        <span class="hljs-keyword">new</span> KeyValuePair&lt;<span class="hljs-keyword">string</span>,<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"redirect_uri"</span>,callbackUrl),
                        <span class="hljs-keyword">new</span> KeyValuePair&lt;<span class="hljs-keyword">string</span>,<span class="hljs-keyword">string</span>&gt;(<span class="hljs-string">"code"</span>,codeToken),
                    });


                        HttpClient client = <span class="hljs-keyword">new</span> HttpClient();
                        <span class="hljs-keyword">var</span> accessTokenResponse = <span class="hljs-keyword">await</span> client.PostAsync(Constants.Google.token_ur, parameters);

                        LoginResponse loginResponse;

                        <span class="hljs-keyword">if</span> (accessTokenResponse.IsSuccessStatusCode)
                        {
                            <span class="hljs-keyword">var</span> data = <span class="hljs-keyword">await</span> accessTokenResponse.Content.ReadAsStringAsync();

                            loginResponse = JsonConvert.DeserializeObject&lt;LoginResponse&gt;(data);
                        }
                    }
                    <span class="hljs-keyword">catch</span> (TaskCanceledException e)
                    {
                        <span class="hljs-comment">// Use stopped auth</span>
                    }


                });

    }
}
</code></pre>
<p>For Android application it is necessary to create an Activity that inherits from WebAuthenticatorCallbackActivity and it needs to have in its IntentFilter DataScheme the same value as callback url.</p>
<pre><code class="lang-csharp">    [<span class="hljs-meta">Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop, Exported = true)</span>]
    [<span class="hljs-meta">IntentFilter(new[</span>] { Android.Content.Intent.ActionView },
     Categories = <span class="hljs-keyword">new</span>[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable },
      DataScheme = <span class="hljs-string">"com.maui.login"</span>)]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">WebAuthenticatorActivity</span> : <span class="hljs-title">WebAuthenticatorCallbackActivity</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OnCreate</span>(<span class="hljs-params">Bundle savedInstanceState</span>)</span>
        {
            <span class="hljs-keyword">base</span>.OnCreate(savedInstanceState);
        }
    }
</code></pre>
<p>Another setting for Android application is adding the <em>query</em> tag for CustomTabsService in Manifest.xml file.</p>
<pre><code class="lang-csharp">&lt;?xml version=<span class="hljs-string">"1.0"</span> encoding=<span class="hljs-string">"utf-8"</span>?&gt;
&lt;manifest xmlns:android=<span class="hljs-string">"http://schemas.android.com/apk/res/android"</span>&gt;
    &lt;application android:allowBackup=<span class="hljs-string">"true"</span> android:icon=<span class="hljs-string">"@mipmap/appicon"</span> package=<span class="hljs-string">"com.maui.login"</span> android:roundIcon=<span class="hljs-string">"@mipmap/appicon_round"</span> android:supportsRtl=<span class="hljs-string">"true"</span>&gt;&lt;/application&gt;
    &lt;uses-permission android:name=<span class="hljs-string">"android.permission.ACCESS_NETWORK_STATE"</span> /&gt;
    &lt;uses-permission android:name=<span class="hljs-string">"android.permission.INTERNET"</span> /&gt;

    &lt;queries&gt;
        &lt;intent&gt;
            &lt;action android:name=<span class="hljs-string">"android.support.customtabs.action.CustomTabsService"</span> /&gt;
        &lt;/intent&gt;
    &lt;/queries&gt;

&lt;/manifest&gt;
</code></pre>
<p>You can find the full code on my <a target="_blank" href="https://github.com/jhonatanfernando/maui-google-authentication">GitHub</a>.</p>
]]></content:encoded></item></channel></rss>