<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by fatih on Medium]]></title>
        <description><![CDATA[Stories by fatih on Medium]]></description>
        <link>https://medium.com/@_fatih?source=rss-15565c94f10e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by fatih on Medium</title>
            <link>https://medium.com/@_fatih?source=rss-15565c94f10e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:20:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_fatih/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using gRPC in ASP.NET]]></title>
            <link>https://medium.com/@_fatih/using-grpc-in-asp-net-704368c6aff8?source=rss-15565c94f10e------2</link>
            <guid isPermaLink="false">https://medium.com/p/704368c6aff8</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[aspnet]]></category>
            <dc:creator><![CDATA[fatih]]></dc:creator>
            <pubDate>Fri, 12 May 2023 15:04:34 GMT</pubDate>
            <atom:updated>2023-05-14T12:27:56.736Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is about how to implement and use gRPC (which is an application-level communication protocol such as REST, GraphQL, or SOAP ) in the .NET ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*bh_u1lX3mX4hur-54wIOFg.png" /></figure><p><em>Topics like what is gRPC or core concepts of it are not mentioned, here are some links if you want to learn more about gRPC fundamentals.</em></p><ul><li><a href="https://developers.google.com/protocol-buffers">Protocol Buffers</a></li><li><a href="https://www.digitalocean.com/community/tutorials/http-1-1-vs-http-2-what-s-the-difference">HTTP/1.1 vs HTTP/2: What&#39;s the Difference? | DigitalOcean</a></li><li><a href="https://grpc.io/docs/">Documentation</a></li></ul><h3><strong>Show me the code</strong></h3><p>This is the final version that includes all of the things mentioned in the article.</p><p><a href="https://github.com/faaydemir/GrpcSample">GitHub - faaydemir/GrpcSample: sample gRPC app</a></p><p>The app has four iterations, each of them represented by a commit, You can see what changed between iterations by traversing commits.</p><h4><a href="https://github.com/faaydemir/GrpcSample/commit/9e19be43f2b67f755965bff28981c9d673c56f41"><strong>v0 monolith</strong></a></h4><p>The base app. Contains three services, these are merchant stock and price. As your guest, the stock service is responsible for the stock operation, and the price service is responsible for price management. Merchant service handles user requests by using these two services.</p><h4><a href="https://github.com/faaydemir/GrpcSample/commit/352a972c85691adc5c6e504d0168aa7b7d02f235"><strong>v1 simple microservice</strong></a></h4><p>In V1, the product and the stock service moved to separate REST APIs. Merchant service communicates with them via HTTP calls.</p><h4><a href="https://github.com/faaydemir/GrpcSample/commit/7c082cd6744d0828e30fbd7eac44feff5c15826d">V2.0 Code-First gRPC</a></h4><p>Stock Service Rest API was replaced with gRPC service that was implemented with code first approach.</p><h4><a href="https://github.com/faaydemir/GrpcSample/commit/c0da32e5e43793c9ae36eb486bd144f0920c9ab0">V2.1 gRPC via proto files</a></h4><p>Price Service Rest API was replaced with gRPC service that was implemented using proto files.</p><h3>gRPC in .NET</h3><p>There are two ways to implement gRPC in the .NET ecosystem. You can create a gRPC service using proto files or you can go with the code-first approach.</p><p>Although these two approaches have some implementation differences, they have the same logical iteration. At first, we are defining services, then Related NuGet packages do some magic and turn our definition into an implementation that is responsible for sending and receiving requests. At last, we integrate generated implementation into the code base.</p><h3><strong>Code First gRPC implementation</strong></h3><p>In the Code First gRPC, C# classes are used to define service instead of using proto files. This is a little different from the classical gRPC implementation style, but it will seem more familiar for dotnet developers.</p><p>To create code first gRPC service;</p><p>On Server:</p><ul><li>Add required NuGet packages.</li><li>Define gRPC service as C# code.</li><li>Implement Service.</li></ul><p>On Client:</p><ul><li>Add required NuGet packages.</li><li>Add service definition to the client app.</li><li>Implement Client.</li></ul><h4>Implementing Server</h4><p><strong>Step 1 — Add NuGet Packages.</strong></p><p>Add <strong>protobuf-net.Grpc.AspNetCore</strong> NuGet package to project, that&#39;s all.</p><p><a href="https://www.nuget.org/packages/protobuf-net.Grpc.AspNetCore">protobuf-net.Grpc.AspNetCore 1.0.177</a></p><p><strong>Step 2 - Defining gRPC service</strong></p><p>Defining service is done with attribute classes in System.ServiceModel namespace. First, we need to create a service interface and request-response classes. Then we need to add a proper attribute class to them. Here is a service definition used in the sample app.</p><pre>using System.ServiceModel;<br>using System.Runtime.Serialization;<br>using ProtoBuf.Grpc;<br><br>[ServiceContract]<br>public interface IStockServiceGrpc<br>{<br>    [OperationContract]<br>    Task&lt;GetStockResponse&gt; GetStock(GetStockRequest request, CallContext context = default);<br><br>    [OperationContract]<br>    Task&lt;GetStockResponse&gt; AddStock(AddStockRequest request, CallContext context = default);<br>}<br><br>[DataContract]<br>public class GetStockRequest<br>{<br>    [DataMember(Order = 1)]<br>    public int ProductId { get; set; }<br>}<br><br>[DataContract]<br>public class GetStockResponse<br>{<br>    [DataMember(Order = 1)]<br>    public int ProductId { get; set; }<br><br>    [DataMember(Order = 2)]<br>    public int Stock { get; set; }<br>}<br><br><br>[DataContract]<br>public class AddStockRequest<br>{<br>    [DataMember(Order = 1)]<br>    public int ProductId { get; set; }<br><br>    [DataMember(Order = 2)]<br>    public int Count { get; set; }<br>}</pre><p><strong>Step 3 - Implementing gRPC service</strong></p><p>The service that we implement in this step is equivalent to the controller on Web API. This service will handle requests, process domain logic, and then return a response.</p><p>Service just is the implementation of the interface defined in the previous step.</p><pre>using ProtoBuf.Grpc;<br><br>public class StockServiceGrpc : IStockServiceGrpc<br>{<br>    private readonly IStockManager stockManager;<br><br>    public StockServiceGrpc(IStockManager stockManager)<br>    {<br>        this.stockManager = stockManager;<br>    }<br><br>    public async Task&lt;GetStockResponse&gt; AddStock(AddStockRequest request, CallContext context = default)<br>    {<br>        var productStock = await stockManager.AddStock(request.ProductId, request.Count);<br>        return new GetStockResponse()<br>        {<br>            ProductId = productStock.ProductId,<br>            Stock = productStock.Stock,<br>        };<br>    }<br><br>    public async Task&lt;GetStockResponse&gt; GetStock(GetStockRequest request, CallContext context = default)<br>    {<br>        var productStock = await stockManager.GetStock(request.ProductId);<br>        return new GetStockResponse()<br>        {<br>            ProductId = productStock.ProductId,<br>            Stock = productStock.Stock,<br>        };<br>    }<br>}</pre><p>After creating service, we need to register it the by using `MapGrpcService` extension method. Then, the service is ready to handle requests.</p><pre>using ProtoBuf.Grpc.Server;<br><br>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddSingleton&lt;IStockManager, StockManager&gt;();<br>builder.Services.AddCodeFirstGrpc();<br><br>var app = builder.Build();<br>app.MapGrpcService&lt;StockServiceGrpc&gt;();<br>app.Run();</pre><h4><strong>Implement Client</strong></h4><p><strong>Step 1 - Add NuGet Packages</strong></p><p>Add the following NuGet packages: Grpc.Net.Client, protobuf-net.Grpc.</p><ul><li><a href="https://www.nuget.org/packages/Grpc.Net.Client">Grpc.Net.Client 2.49.0</a></li><li><a href="https://www.nuget.org/packages/protobuf-net.Grpc">protobuf-net.Grpc 1.0.177</a></li></ul><p><strong>Step 2 - Client Implementation</strong><br>On the client side, the service definition is the same as the server. To create a client instance, first, we need to add the service definition, then we can create an instance by calling `channel.CreateGrpcService&lt;TService&gt;` method.</p><p>Making gRPC call is simple as calling a method.</p><pre>using Grpc.Net.Client;<br>using ProtoBuf.Grpc.Client;<br><br>public class StockClient : IStockManager<br>{<br>    private IStockServiceGrpc client;<br>    private readonly string STOCK_SERVICE_URL = &quot;https://localhost:5004&quot;;<br>    public StockClient()<br>    {<br>        var channel = GrpcChannel.ForAddress(STOCK_SERVICE_URL);<br>        client = channel.CreateGrpcService&lt;IStockServiceGrpc&gt;();<br>    }<br><br>    public async Task&lt;ProductStock&gt; AddStock(int productId, int count)<br>    {<br>        var currentStock = await client.AddStock(new AddStockRequestGrpc() { ProductId = productId, Count = count });<br>        return new ProductStock(currentStock.ProductId, currentStock.Stock);<br>    }<br><br>    public async Task&lt;ProductStock&gt; GetStock(int productId)<br>    {<br>        var stock = await client.GetStock(new GetStockRequest() { ProductId = productId });<br>        return new ProductStock(stock.ProductId, stock.Stock);<br>    }<br>}</pre><h3>gRPC implementation with Proto Files</h3><p>This approach includes the following steps</p><p>On server:</p><ul><li>Add Required Nuget packages</li><li>Create ProtoBuf files and add them to the project</li><li>Generate server code from ProtoBuf</li><li>Implement Service.</li></ul><p>On Client:</p><ul><li>Add Required Nuget packages</li><li>Add ProtoBuf files to the project</li><li>Implement Client</li></ul><h4>Implementing Server</h4><p><strong>Step 1 - Creating proto (Protocol Buffer) files</strong></p><p>In gRPC, services are defined with Protocol Buffer.</p><p>Protocol Buffer (aka Protobuf) is an Interface Definition Language(IDL) to define service with request and response messages. (Also it is the name of the data format used in gRPC communication) In Rest, the close equivalent of Protocol Buffer is OpenApi (IDL ) + Json(DataFormat).</p><p>With ProtoBuf we could define service in detail including method names request and response messages, and property types.</p><p>This is the proto file that defines our PricingService. It includes service details and request-response message format and parameter types. We need to add this proto file both for client and server apps.</p><pre>syntax = &quot;proto3&quot;;<br>package Pricing;<br>service PricingService{<br>// get price<br>rpc GetPrice(GetPriceRequest) returns (GetPriceResponse) {}<br>// set price<br>rpc SetPrice(SetPriceRequest) returns (SetPriceResponse) {}<br>}<br>message GetPriceRequest {<br>int32 productId = 1;<br>}<br>message GetPriceResponse{<br>int32 productId= 1;<br>int32 price= 2;<br>}<br>message SetPriceRequest {<br>int32 productId= 1;<br>int32 price= 2;<br>}<br>message SetPriceResponse{<br>}</pre><p>If you want to compare, here is the (swagger-generated) OpenApi equivalent of PricingService.</p><pre>openapi: 3.0.1<br>info:<br>  title: PricingService<br>  version: &#39;1.0&#39;<br>paths:<br>  &quot;/{productId}/price&quot;:<br>    get:<br>      tags:<br>      - PricingService<br>      parameters:<br>      - name: productId<br>        in: path<br>        required: true<br>        schema:<br>          type: integer<br>          format: int32<br>      responses:<br>        &#39;200&#39;:<br>          description: Success<br>          content:<br>            application/json:<br>              schema:<br>                &quot;$ref&quot;: &quot;#/components/schemas/ProductPrice&quot;<br>    post:<br>      tags:<br>      - PricingService<br>      parameters:<br>      - name: productId<br>        in: path<br>        required: true<br>        schema:<br>          type: integer<br>          format: int32<br>      requestBody:<br>        content:<br>          application/json:<br>            schema:<br>              &quot;$ref&quot;: &quot;#/components/schemas/UpdatePriceRequest&quot;<br>        required: true<br>      responses:<br>        &#39;200&#39;:<br>          description: Success<br>components:<br>  schemas:<br>    ProductPrice:<br>      type: object<br>      properties:<br>        productId:<br>          type: integer<br>          format: int32<br>        price:<br>          type: integer<br>          format: int32<br>      additionalProperties: false<br>    UpdatePriceRequest:<br>      type: object<br>      properties:<br>        price:<br>          type: integer<br>          format: int32<br>      additionalProperties: false</pre><p>ProtoBuf has an equivalent for most types in c#. You could visit the following link to see more detail about type matching.</p><p><a href="https://learn.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/protobuf-data-types">Protobuf scalar data types - gRPC for WCF developers</a></p><p>For more detail about ProtoBuf see;</p><ul><li><a href="https://docs.microsoft.com/en-us/aspnet/core/grpc/protobuf?view=aspnetcore-6.0">Create Protobuf messages for .NET apps</a></li><li><a href="https://developers.google.com/protocol-buffers/docs/proto3#scalar">Language Guide (proto3) | Protocol Buffers | Google Developers</a></li></ul><p><strong>Step 2 - Code generation from proto’s</strong></p><p>When you add proto files to the project, MSBuild automatically generates service implementation for proto files. The only thing you need do is specify the proto files in csproj file as following.</p><pre>&lt;ItemGroup&gt;<br>  &lt;Protobuf Include=&quot;**/*.proto&quot; GrpcServices=&quot;Server&quot; ProtoRoot=&quot;Grpc\Proto&quot; OutputDir=&quot;Grpc\Generated&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p>Here is more detail about adding proto files to csproj.</p><p><a href="https://github.com/grpc/grpc/blob/master/src/csharp/BUILD-INTEGRATION.md">grpc/BUILD-INTEGRATION.md at master · grpc/grpc</a></p><p>MSBuild uses Protoc (Proto Buffer Compiler) for code generation. You could also download Protoc and do generation manually but it&#39;s not simple as MSBuild.</p><p>If you want to use protoc, you could install it for Linux or macOS by following the instructions in here,</p><p><a href="https://grpc.io/docs/protoc-installation/">Protocol Buffer Compiler Installation</a></p><p>For Windows, you should download binaries, then follow the same steps in the previous link.</p><p><a href="https://github.com/protocolbuffers/protobuf/releases/download/v3.20.0/protoc-3.20.0-win64.zip">https://github.com/protocolbuffers/protobuf/releases/download/v3.20.0/protoc-3.20.0-win64.zip</a></p><p><strong>Step 3 - Create gRPC Service</strong></p><p>Protoc generates C# files for Request/Response types and a Service Base Class. Service Base Class is responsible for handling gRPC requests. It has equivalent methods for each service method in proto files. gRPC service is implemented as a class that implements the auto-generated ServiceBaseClass. When a gRPC request is received, it is handled based on the logic inside the overridden methods in ServiceBaseClass implementation.</p><pre>using Grpc.Core;<br>using Pricing;<br><br>public class PricingServiceGrpc : PricingService.PricingServiceBase<br>{<br>    private readonly IPricingManager pricingManager;<br><br>    public PricingServiceGrpc(IPricingManager pricingManager)<br>    {<br>        this.pricingManager = pricingManager;<br>    }<br><br>    public override async Task&lt;GetPriceResponse&gt; GetPrice(GetPriceRequest request, ServerCallContext context)<br>    {<br>        var productPrice = await pricingManager.GetPrice(request.ProductId);<br>        return new GetPriceResponse()<br>        {<br>            Price = productPrice.Price,<br>            ProductId = request.ProductId,<br>        };<br>    }<br><br>    public override async Task&lt;SetPriceResponse&gt; SetPrice(SetPriceRequest request, ServerCallContext context)<br>    {<br>        await pricingManager.SetPrice(request.ProductId, request.Price);<br>        return new SetPriceResponse();<br>    }<br>}</pre><p>Then we need to add gRPC to the builder by calling MapGrpcService method.</p><pre>// AddGrpc<br>builder.Services.AddGrpc();<br>//<br>app.MapGrpcService&lt;PricingServiceGrpc&gt;();</pre><h4><strong>Client Implementation</strong></h4><p><strong>Step 1 — Add nuget packages.</strong></p><p>The only required package is <a href="https://www.nuget.org/packages/Grpc.AspNetCore"><strong>Grpc.AspNetCore</strong></a><strong>.</strong></p><p><a href="https://www.nuget.org/packages/Grpc.AspNetCore">Grpc.AspNetCore 2.53.0</a></p><p><strong>Step 2 — Add proto files to csproj.</strong></p><p>In the client, the same proto file as the server is used. First, you should add a proto file in csproj file then register the gRPC service client that is also auto-generated.</p><pre>&lt;ItemGroup&gt;<br>  &lt;Protobuf Include=&quot;**/*.proto&quot; GrpcServices=&quot;Client&quot; ProtoRoot=&quot;Grpc\Proto&quot; OutputDir=&quot;Grpc\Generated&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><pre>builder.Services.AddGrpcClient&lt;Pricing.PricingService.PricingServiceClient&gt;(o =&gt;<br>{<br>    o.Address = new Uri(&quot;https://localhost:5002&quot;);<br>});</pre><p><strong>Step 3 — Implementing Client</strong><br>After registering PricingServiceClient in a startup, you can use it anywhere you want by passing it as a parameter in the constructor.</p><pre>using Pricing;<br>using static Pricing.PricingService;<br>public class PricingClient : IPricingManager<br>{<br>    private readonly PricingServiceClient pricingClient;<br><br>    public PricingClient(PricingServiceClient pricingClient)<br>    {<br>        this.pricingClient = pricingClient;<br>    }<br><br>    public async Task&lt;ProductPrice&gt; GetPrice(int productId)<br>    {<br>        var productPrice = await pricingClient.GetPriceAsync(new GetPriceRequest() { ProductId = productId });<br>        return new ProductPrice(productPrice.ProductId, productPrice.Price);<br>    }<br><br>    public async Task SetPrice(int productId, int price)<br>    {<br>        await pricingClient.SetPriceAsync(new SetPriceRequest() { ProductId = productId, Price = price });<br>    }<br>}</pre><p>That’s all. This was the last step of gRPC implementation.</p><p>Here is some resources if you learn more about gRPC.</p><p><a href="https://docs.microsoft.com/en-us/aspnet/core/grpc/basics?view=aspnetcore-6.0">gRPC services with C#</a></p><p>Testing gRPC service,</p><p><a href="https://docs.microsoft.com/tr-tr/aspnet/core/grpc/test-tools?view=aspnetcore-6.0">https://docs.microsoft.com/tr-tr/aspnet/core/grpc/test-tools?view=aspnetcore-6.0</a></p><p><a href="https://blog.postman.com/postman-now-supports-grpc/">Postman Now Supports gRPC | Postman Blog</a></p><p><a href="https://martinbjorkstrom.com/posts/2020-07-08-grpc-reflection-in-net">https://martinbjorkstrom.com/posts/2020-07-08-grpc-reflection-in-net</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=704368c6aff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring C# async/await with samples]]></title>
            <link>https://medium.com/@_fatih/c-async-await-common-use-cases-382f1a09dc11?source=rss-15565c94f10e------2</link>
            <guid isPermaLink="false">https://medium.com/p/382f1a09dc11</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[await]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[fatih]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 22:26:51 GMT</pubDate>
            <atom:updated>2023-06-15T22:09:03.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qphartY5WDk16-OP" /><figcaption>Photo by <a href="https://unsplash.com/@redviking509?utm_source=medium&amp;utm_medium=referral">John Anvik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The async/await keywords are a way to manage synchronization. With these keywords, code-blocks working on separate threads can be written linearly and seems almost the same as synchronous code. No need for any continue/wait and callback management logic. Thanks to these, async-await keywords drastically increase writability and readability.</p><p>They added C# has been added C#5, also adopted with many other languages.</p><p>In this article, we examine the most common async/await usage scenarios.</p><h3>syntax</h3><p><strong>async </strong>keyword can be added to any method that returns <strong>void</strong>(is a bad choice), <strong>Task </strong>or <strong>Task-like</strong> types. <strong>await </strong>can be only used in async methods.</p><p><strong>await </strong>is commonly used for <strong>Task </strong>type. But it can be also used for any type that has a method named as GetAwaiter()and returns a type that,<br>- be derived type from INotifyCompletion interface,<br>- having int GetResult()method and bool IsCompleted {get} property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6df8bceb680700c57373888f4a065bc6/href">https://medium.com/media/6df8bceb680700c57373888f4a065bc6/href</a></iframe><h3><strong>async-await at simplest</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11e973ae4bcc27eef6baa57176f266df/href">https://medium.com/media/11e973ae4bcc27eef6baa57176f266df/href</a></iframe><p><em>This is a logging class that will be used in the samples.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58180941630faa7036b938ede050db99/href">https://medium.com/media/58180941630faa7036b938ede050db99/href</a></iframe><p><em>output:</em></p><pre>thread |    elapsed | message<br>    T1 |         23 | Main A<br>    T1 |       6203 | DoWork A<br>    T8 |    1034509 | DoWork B<br>    T8 |    1038225 | Main B</pre><p>This is the most common async/await usage. In the sample, execution starts with T1 and continues with it until Task.Delay() called which is the only asynchronous operation, from this point T8 was created then execution was completed with it.</p><p>Even if DoWork()is an async function, this does not mean DoWork is executed in a separate thread. As we see until the first real async operation execution continues at the same thread.</p><p>Async keyword does not create asynchronous by itself. Initial intuition about the async keyword, may be that it is a mechanism to create asynchronous as an alternative of Task.Runmethod, but it isn&#39;t. If there is no Task creation, execution continues in the same thread.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07f09ca2ff495df7b48263201b868913/href">https://medium.com/media/07f09ca2ff495df7b48263201b868913/href</a></iframe><pre>thread |    elapsed | message<br>    T1 |         23 | Main A<br>    T1 |      12298 | DoWork A<br>    T1 |      15093 | DoWork B<br>    T1 |      15473 | Main B</pre><h4><strong>Task.Yield</strong></h4><p>If you want to force execution to run asynchronously in another thread Task.Yield can be used. After the point Task.Yield called execution switch to another thread.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2e567ba8c1f271affdbcc46c310b69c/href">https://medium.com/media/d2e567ba8c1f271affdbcc46c310b69c/href</a></iframe><pre>thread |    elapsed | message<br>    T1 |         17 | Main A<br>    T1 |      13936 | DoWork A<br>    T6 |      24069 | DoWork B<br>    T6 |      24755 | DoWork C<br>    T6 |      27387 | Main B</pre><h4><strong>Task.Result/Task.Wait() vs await Task</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/224456d334b8f0960c0aa87b360578ed/href">https://medium.com/media/224456d334b8f0960c0aa87b360578ed/href</a></iframe><p>Task.Result and await Taskare creates the same output in different ways. Both of them wait DoWorkAsync() to complete and get the result of it. The only difference is Task.Result and Task.Wait() blocks caller thread until execution is complete, await is not. Blocking threads is a not good thing and has some drawbacks.</p><p>One of the drawbacks is related to SynchronizationContext. A small subset of modern .net has SynchronizationContext one of them is WPF. So the sample is from .NET 5 WPF desktop app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b436c05b87c665566257e97f7de5264/href">https://medium.com/media/2b436c05b87c665566257e97f7de5264/href</a></iframe><p><strong>RunAwait()</strong> output</p><pre>thread |    elapsed | message<br>    T1 |        189 | Main A<br>    T1 |      22039 | DoWork A<br>    T1 |      59241 | Main.Action A<br>    T1 |    3191175 | Main.Action B<br>    T1 |    3248209 | Main.Action C<br>    T4 |    4229930 | DoWork B<br>    T1 |    4703114 | Main B</pre><p><strong>RunResult()</strong> output (Replaced with RunAwait() at line 32)</p><pre>thread |    elapsed | message       <br>    T1 |        172 | Main A        <br>    T1 |      21777 | DoWork A      <br>    T6 |    4050258 | DoWork B      <br>    T1 |    4072817 | Main B        <br>    T1 |    4093170 | Main.Action A <br>    T1 |    4108001 | Main.Action B <br>    T1 |    4117813 | Main.Action C</pre><p>T1 is the main thread, it’s also responsible for UI operations InvokeAction is for simulating a common WPF application working pattern, it runs an async operation then pushes the action to T1 to update UI. In the sample, T1 call a (relatively) long-running asyncDoWork method and is expected to handle actions that are pushed from the InvokeAction method.</p><p>When running RunResult even if T1 is idle, actions invoked from InvokeAction are waiting DoWork method to complete. On the contrary we run atRunAwait method because T1 is not blocked they do not wait for DoWork to complete.</p><p>To see one other cons of Task blocking let’s modify the first sample with Task.Wait() and examine outputs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60002d023e800e3fad5f0f0001ecf4ba/href">https://medium.com/media/60002d023e800e3fad5f0f0001ecf4ba/href</a></iframe><pre>thread |    elapsed | message<br>    T1 |         26 | Main A<br>    T1 |       5310 | DoWork A<br>    T4 |    1141904 | DoWork B<br>    T1 |    1143257 | Main B</pre><p>In the first sample after Task.Delay() called, T1 was released so it was free to be used for another operation but when used Task.Wait() or Task.Result T1 was also held during the execution of T4.</p><h4>When All</h4><p>Task.WhenAll is used for waiting for multiple Tasks to complete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53fe41564d6676882d62affc74151889/href">https://medium.com/media/53fe41564d6676882d62affc74151889/href</a></iframe><pre>thread |    elapsed | message<br>    T1 |         20 | Main A<br>    T9 |      16673 | 3 - DoWork A<br>    T7 |      16666 | 1 - DoWork A<br>   T10 |      16706 | 4 - DoWork A<br>    T8 |      16685 | 2 - DoWork A<br>   T10 |    2047585 | 1 - DoWork B<br>   T10 |    4061792 | 2 - DoWork B<br>   T10 |    6100200 | 3 - DoWork B<br>   T10 |    8122513 | 4 - DoWork B<br>   T10 |    8127856 | Main B</pre><p>When all of the tasks in param have the same return type like Task&lt;T&gt;it returns T[] .If they are different types like Task&lt;TA&gt; and Task&lt;TB&gt; it returns Task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79e5b0394be2bf058e89413ba34b57b5/href">https://medium.com/media/79e5b0394be2bf058e89413ba34b57b5/href</a></iframe><p>Assigned statements can be shortened with the following method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f6024642f538b419cd267a3c19a40f9/href">https://medium.com/media/4f6024642f538b419cd267a3c19a40f9/href</a></iframe><p><strong>yield return in Task</strong></p><p>There is also support for <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield">yield </a>return in async methods, return type should be IAsyncEnumerable and await foreach should be used for iteration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f63f2a581c0d9b4c52e29a6896146731/href">https://medium.com/media/f63f2a581c0d9b4c52e29a6896146731/href</a></iframe><p>output:</p><pre>thread |    elapsed | message<br>    T1 |         51 | Main A<br>    T1 |       5099 | Main B<br>    T1 |      36979 | DoWork A<br>    T4 |    1167694 |   DoWork B 0<br>    T4 |    1172768 |   Main C 0<br>    T4 |    2259096 |   DoWork B 1<br>    T4 |    2261278 |   Main C 1<br>    T4 |    2265662 | DoWork C<br>    T4 |    2269866 | Main D</pre><h4>References and useful resources to go beyond basics</h4><ul><li><a href="https://codereview.stackexchange.com/a/205364">Initializing multiple variables with different types using parallel calls</a></li><li><a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming">Async/Await - Best Practices in Asynchronous Programming</a></li><li><a href="https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html">ASP.NET Core SynchronizationContext</a></li><li><a href="https://devblogs.microsoft.com/dotnet/configureawait-faq/">ConfigureAwait FAQ - .NET Blog</a></li><li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.yield?view=net-6.0">Task.Yield Method (System.Threading.Tasks)</a></li><li><a href="https://codeblog.jonskeet.uk/2011/05/08/eduasync-part-1-introduction/">Eduasync part 1: introduction</a></li><li><a href="https://stackoverflow.com/questions/13159080/how-does-taskint-become-an-int">How does Task become an int?</a></li><li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield">yield contextual keyword - C# Reference</a></li><li><a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.synchronizationcontext?view=net-6.0">SynchronizationContext Class (System.Threading)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=382f1a09dc11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET 6 Minimal API]]></title>
            <link>https://medium.com/@_fatih/net-6-minimal-api-c0b7a1197672?source=rss-15565c94f10e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0b7a1197672</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[dotnet6]]></category>
            <category><![CDATA[minimal-api]]></category>
            <dc:creator><![CDATA[fatih]]></dc:creator>
            <pubDate>Sun, 24 Oct 2021 17:54:03 GMT</pubDate>
            <atom:updated>2021-10-24T17:54:03.817Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is minimal API and why is it needed.</h3><p>ASP.NET is a popular web framework, it&#39;s fast, open-source, has really good IDEs like Visual Studio, VS Code. There are plenty of sources for learning it. ASP.NET is quite convenient for developing a well-structured robust web app. But besides these pros, it has some cons.</p><p>When you compare an ASP.NET app with some of the popular web frameworks like Expressjs or Python Flask one of the pros is becoming clearly visible.</p><p>To see what is different, let&#39;s develop the apps that do the same work with Flask, Expressjs, and ASP.NET.</p><p>The app will return the current year as a response to a get request.</p><p>Flask is first, it&#39;s just 8 lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d441783370240bf2eb319976ca9428/href">https://medium.com/media/13d441783370240bf2eb319976ca9428/href</a></iframe><p>Then Expressjs, quite similar to the flask app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6bb34c369a073d168f863317b04de99/href">https://medium.com/media/c6bb34c369a073d168f863317b04de99/href</a></iframe><p>Lastly, the same app with ASP.NET.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92668196e9721592bb9b77d59b6ba7b2/href">https://medium.com/media/92668196e9721592bb9b77d59b6ba7b2/href</a></iframe><p>Nearly 50 lines of code which is almost four times more than others, having more lines of code is not an important metric, but readability is. Someone with no framework knowledge can easily understand what express.js and flask code do at first glance, but it’s not the same for ASP.NET.</p><p>When looking ASP.NET app you first see a messy configuration ceremony. It’s doing some configuration in a class then more configuration at another class, It’s more difficult to understand or remember when we compare it with flask and express.js. Additionally, this is not a common form of an asp.net app, mostly there are controllers and controller route patterns to learn.</p><p>With the minimal API, this configuration mess will be drastically reduced. Here is a sample app doing the same job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70b45c0c70124eb3990747f2e1e210c5/href">https://medium.com/media/70b45c0c70124eb3990747f2e1e210c5/href</a></iframe><p>It&#39;s just 8 line code (can be reduced to 4). It&#39;s so easy to understand and remember</p><p>This syntax became possible thanks to some features of C#10. These are <a href="https://docs.microsoft.com/en-us/dotnet/core/compatibility/sdk/6.0/implicit-namespaces">global using</a> and <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/top-level-statements">top-level statement</a>.</p><p><strong>Global using</strong> feature allows defining frequently used using directives in just one place. Syntax is below</p><pre>global using System;</pre><p>If you add <em>&lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;</em> to proj file its add global using directives to auto-generated cs file.</p><p><strong>The top-level statement</strong> is syntactic sugar, compiler reads executable statement until to end of file or any of class/struct/namespace declaration then creates the main method with them. Here are some samples of how is the main method <em>approximately</em> generated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28a61bfc1e405acf766d256c54290530/href">https://medium.com/media/28a61bfc1e405acf766d256c54290530/href</a></iframe><blockquote>top level statement<strong> </strong>feature may mislead that you can declare function without class in C# but you can’t. <strong>There can be only one cs file with top level statement</strong> so it’s true for only one file. I think it’s little bit fuzzy , main method in Program class doesn’t look so bad</blockquote><p>Here are some capabilities of minimal API</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbd850265170fc4a6a55607b12341e2a/href">https://medium.com/media/bbd850265170fc4a6a55607b12341e2a/href</a></iframe><blockquote>Checkout <a href="https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06158727">this really good document</a> for more sample</blockquote><p>A Complete minimal API project: <a href="https://github.com/faaydemir/dotnet6-minimal-api">https://github.com/faaydemir/dotnet6-minimal-api</a> (<em>this repo also contains Github Actions to publish app to Google Cloud Run</em><a href="https://medium.com/@_fatih/github-actions-for-deploy-google-cloud-run-4f0338bb7f39"><em> see this post </em></a><em>for more</em>)</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0b7a1197672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Github Actions For Deploy Google Cloud Run]]></title>
            <link>https://medium.com/@_fatih/github-actions-for-deploy-google-cloud-run-4f0338bb7f39?source=rss-15565c94f10e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f0338bb7f39</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[fatih]]></dc:creator>
            <pubDate>Sun, 24 Oct 2021 15:36:54 GMT</pubDate>
            <atom:updated>2021-10-24T15:36:54.237Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://cloud.google.com/run">Goole Cloud Run</a> (GCR) is a serverless cloud service such as <a href="https://aws.amazon.com/lambda/">AWS Lambda </a>or <a href="https://azure.microsoft.com/en-us/services/functions">Azure Function</a> or <a href="https://developers.google.com/learn/topics/functions">Google Cloud Function</a>. It has common serverless features like auto-scaling, pay as you, etc. The shiny feature of GCR has supported custom docker container, you can deploy any container image to GCR.</p><p>This article is about deploying an app to cloud run with GitHub Actions, here is a diagram of what will be achieved at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*Sy85cpQOPkjQi_7WpnsrcA.png" /></figure><p>Before you start you should</p><ul><li>create a dockerized web app then push it to Github,</li><li>create a <a href="https://cloud.google.com/">Google Cloud</a> account and enable billing. There is <a href="https://cloud.google.com/free/docs/gcp-free-tier/#free-trial">free credit </a>to try Google Cloud (if you can’t use free credit for any reason, because of Cloud Run is a pay-as-you-go service, it will cost almost free to try it. See <a href="https://cloud.google.com/sdk/gcloud/reference/beta/billing">1</a> <a href="https://cloud.google.com/billing/docs/how-to/budgets">2</a> for more detail</li><li>install Docker (optional, will be used at testing at local).</li></ul><h3><strong>Configure Cloud Run with CLI</strong></h3><p>I will use only google cloud cli for configurations, you should install Google Cloud SDK from <a href="https://cloud.google.com/sdk/docs/install">here</a>. I’ll run some beta commands so you should check Beta Commands at the stage you choose which component to install.</p><p>Next, we will continue with the following steps</p><ul><li>Create and Google Cloud Project and will enable billing for this project.</li><li>Add the required services to the project.</li><li>Create a service account and set permissions.</li><li>Test it locally.</li><li>Create GitHub Actions to publish the app via Google Cloud Run</li></ul><blockquote><a href="https://gist.github.com/faaydemir/47c053a6d6e8af1e5991a1c8c3f336c3">this gist</a> contains all command to use. it’s more practical to set config values like &lt;project-name&gt; with find-replace in this file</blockquote><p>First, check if cloud CLI is installed successfully, open your terminal app, and write the following command</p><pre>gcloud --version</pre><p>Log in to Google Cloud</p><pre>gcloud auth login</pre><p>Create a project (replace &lt;project-name&gt; with your project name)</p><pre>gcloud projects create &lt;project-name&gt;</pre><p>Check if the project is added.</p><pre>gcloud projects list</pre><p>Select created the project as the active project.</p><pre>gcloud config set project &lt;project-name&gt;</pre><p>List billing accounts</p><pre>gcloud beta billing accounts list</pre><blockquote>After this command, you should see your billing account. If you can’t, you should check <a href="https://cloud.google.com/sdk/gcloud/reference/beta/billing">this doc </a>for troubleshooting.</blockquote><p>Enable billing for the current project.</p><pre>gcloud beta billing projects link &lt;project-name&gt; --billing-account &lt;ACCOUND_ID like 11AA19-22BB31-112233&gt;</pre><p>After enabling billing successfully, we can add the required services. We need:</p><ul><li>Google Cloud Run (GCR) for serve app</li><li>Cloud Registry for store docker images that be used at GCR</li></ul><pre>gcloud services enable run.googleapis.com</pre><pre>gcloud services enable containerregistry.googleapis.com</pre><p>Now we create a service account, <a href="https://cloud.google.com/iam/docs/understanding-service-accounts">see for more detail about the service account</a></p><pre>gcloud iam service-accounts create &lt;service-account-name&gt; --description=&quot;-&quot; --display-name=&lt;service-account-name&gt;</pre><pre>gcloud iam service-accounts list</pre><p>We will add the following roles to the service account</p><ul><li>roles/iam.serviceAccountUser</li><li>roles/storage.admin</li><li>roles/run.admin</li></ul><pre>gcloud projects add-iam-policy-binding &lt;project-name&gt; --member=&quot;serviceAccount:&lt;service-account-name&gt;@&lt;project-name&gt;.iam.gserviceaccount.com&quot; --role=&quot;roles/storage.admin&quot;</pre><pre>gcloud projects add-iam-policy-binding &lt;project-name&gt; --member=&quot;serviceAccount:&lt;service-account-name&gt;@&lt;project-name&gt;.iam.gserviceaccount.com&quot; --role=&quot;roles/iam.serviceAccountUser&quot;</pre><pre>gcloud projects add-iam-policy-binding &lt;project-name&gt; --member=&quot;serviceAccount:&lt;service-account-name&gt;@&lt;project-name&gt;.iam.gserviceaccount.com&quot; --role=&quot;roles/run.admin&quot;</pre><p>Check roles</p><pre>gcloud projects get-iam-policy &lt;project-name&gt;</pre><p>The last step of configuration is creating a secret key for the service account. This key will be used for login with the service account.</p><pre>gcloud iam service-accounts keys create &lt;path&gt;/GCP_SA_KEY.json --iam-account=&lt;service-account-name&gt;@&lt;project-name&gt;.iam.gserviceaccount.com</pre><p>Now, all necessary configuration is completed, we can deploy the container image to Cloud Registry and start the GCR service with it.</p><p>Before creating GitHub Actions, it’ll be good to try at local to check if everything is ok. First login with a service account.</p><pre>gcloud auth activate-service-account &lt;service-account-name&gt;@&lt;project-name&gt;.iam.gserviceaccount.com --key-file=&lt;path&gt;/GCP_SA_KEY.json</pre><p>Configure docker</p><pre>gcloud auth configure-docker</pre><p>Open your project root folder in terminal, build and push docker image to Google Cloud Registry</p><pre>docker build -t gcr.io/&lt;project-name&gt;/&lt;image-name&gt;:latest .</pre><p>Check if the image is pushed.</p><pre>gcloud container images list --repository=gcr.io/&lt;project-name&gt;</pre><p>Start GCR service. Before the run, check the port arg is same as the port exposed in Dockerfile</p><pre>gcloud run deploy path \ — region us-central1 — image gcr.io/&lt;project-name&gt;/&lt;image-name&gt; — platform managed — allow-unauthenticated — memory 256Mi — port 443 — project &lt;project-name&gt;</pre><p>List Cloud Run Services to check and see project url</p><pre>gcloud beta run services list</pre><p>Then open the URL to ensure everything is ok.</p><h3><strong>Create Github Action</strong></h3><p>First, we need to set some secrets, open following URL then add given secrets</p><p><em>github.com/&lt;username&gt;/&lt;repo&gt;/settings/secrets/actions/new</em></p><ul><li><em>Name</em>: GCP_PROJECT_ID <em>value: </em>&lt;project-name&gt;</li><li><em>Name</em>: GCP_SA_EMAIL <em>value: </em>&lt;service-account-name&gt;@&lt;project-name&gt;.iam.gserviceaccount.com</li><li><em>Name</em>: GCP_SA_KEY ,<em>value</em>: copy all from GCP_SA_KEY.json</li></ul><p>Open your project root folder and create a yaml file at this path <em>&lt;projectroot&gt;/.github/workflows/&lt;name-of-action&gt;.yaml</em> and copy following content to it. (replace &lt;image-name&gt; with yours)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2903a3b42268e0e5747aa4c2ca8d3ffd/href">https://medium.com/media/2903a3b42268e0e5747aa4c2ca8d3ffd/href</a></iframe><p>then commit and push changes to Github.</p><p>To check if everything is ok, first, see if the action was completed successfully (at <strong>https://github.com/&lt;user-name&gt;/&lt;repo-name&gt;/actions)</strong> then run the following command and check the last deployed date.</p><pre>gcloud beta run services list</pre><p>That&#39;s all, thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f0338bb7f39" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>