<?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 Paolo Fullone on Medium]]></title>
        <description><![CDATA[Stories by Paolo Fullone on Medium]]></description>
        <link>https://medium.com/@paolo.enrico?source=rss-1a0b612bc88c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ay_eo9xGqi20K33h</url>
            <title>Stories by Paolo Fullone on Medium</title>
            <link>https://medium.com/@paolo.enrico?source=rss-1a0b612bc88c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:52:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paolo.enrico/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[Health Checks for Multi-Database Access in C# WebAPI: A Practical Guide]]></title>
            <link>https://medium.com/@paolo.enrico/leveraging-healthchecks-on-a-distributed-system-f89bb22a7951?source=rss-1a0b612bc88c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89bb22a7951</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[health-check]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[webapi]]></category>
            <dc:creator><![CDATA[Paolo Fullone]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 22:58:11 GMT</pubDate>
            <atom:updated>2025-04-07T23:18:42.329Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will demonstrate how to use a health check to verify if one or more application users have access rights to a table (or many) using HealthCheck in a C# WebAPI. In the end, this is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*h0uXGpPbSuR8n8C6BzvW6g.png" /></figure><p>The problem solved here is that I don’t have access rights in databases, so I need to ask a DBA to create the user, grant access to the necessary tables, and create a cipher containing the connection string. Sometimes it’s frustrating to face all the development, win the battle against a very detailed CI/CD pipeline full of test requirements, and the application doesn’t work due to a missing grant.</p><p>So, we have an extension class that uses HealthChecks. Here’s how it’s set up (the complete code is in the end of the article):</p><pre>services.AddHealthChecks()<br>        .AddCheck(name: &quot;live&quot;, check: () =&gt; HealthCheckResult.Healthy(), tags: new[] { &quot;live&quot;, &quot;ready&quot; }, TimeSpan.FromSeconds(30))<br>        .AddKafka(kafkaConfig!, kafkaTopic!, name: &quot;Kafka&quot;)<br>        .AddSqlServer(sqlServer, name: &quot;SqlServer&quot;, failureStatus: HealthStatus.Unhealthy, tags: new[] { &quot;db&quot;, &quot;mssql&quot; })<br>        .AddOracle(oracle, name: &quot;Oracle&quot;, failureStatus: HealthStatus.Unhealthy, tags: new[] { &quot;db&quot;, &quot;oracle&quot; })<br>        .AddCheck&lt;HealthCheckExtensionMultiDatabase&gt;(name: &quot;MultiDatabase&quot;, failureStatus: HealthStatus.Unhealthy, tags: new[] { &quot;db&quot;, &quot;mssql&quot;, &quot;oracle&quot; });</pre><p>The <em>HealthCheckExtensionMultiDatabase </em>(what a long name!) handles this functionality. Here’s the implementation:</p><pre>public HealthCheckExtensionMultiDatabase(IDictionary&lt;string, (string connectionString, IList&lt;string&gt; Queries, string provider)&gt; databasesQueries)<br>{<br>    _databasesQueries = databasesQueries;<br>}<br><br>public async Task&lt;HealthCheckResult&gt; CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)<br>{<br>    var healthCheckResults = new Dictionary&lt;string, HealthCheckResult&gt;();<br><br>    foreach (var dbQuery in _databasesQueries)<br>    {<br>        foreach (var query in dbQuery.Value.Queries)<br>        {<br>            try<br>            {<br>                using (var connection = CreateConnection(dbQuery.Value.connectionString, dbQuery.Value.Provider))<br>                {<br>                    await connection.OpenAsync(cancellationToken);<br><br>                    using (var command = CreateCommand(query, connection, dbQuery.Value.Provider))<br>                    {<br>                        await command.ExecuteScalarAsync(cancellationToken);<br>                        healthCheckResults[$&quot;{dbQuery.Key}-{query}&quot;] = HealthCheckResult.Healthy(&quot;ok&quot;);<br>                    }<br>                }<br><br>            }<br>            catch (Exception ex)<br>            {<br>                var errorMessage = Regex.Unescape($&quot;Exception during query execution: {ex.Message}&quot;);<br>                healthCheckResults[$&quot;{dbQuery.Key}-{query}&quot;] = HealthCheckResult.Unhealthy(errorMessage);<br>            }<br>        }<br>    }<br><br>    var overallStatus = healthCheckResults.Values.All(result =&gt; result.Status == HealthStatus.Healthy) ? HealthStatus.Healthy : HealthStatus.Unhealthy;<br>    return new HealthCheckResult(overallStatus, description: &quot;Multi-database health check&quot;, data: healthCheckResults.ToDictionary(kvp =&gt; kvp.Key, kvp =&gt; (object)kvp.Value.Description!)!);<br>}<br><br>private DbConnection CreateConnection(string connectionString, string provider)<br>{<br>    return provider switch<br>    {<br>        &quot;SqlServer&quot; =&gt; new SqlConnection(connectionString),<br>        &quot;Oracle&quot; =&gt; new OracleConnection(connectionString),<br>        _ =&gt; throw new NotSupportedException($&quot;Provider {provider} is not supported.&quot;)<br>    };<br>}<br><br>private DbCommand CreateCommand(string query, DbConnection connection, string provider)<br>{<br>    return provider switch<br>    {<br>        &quot;SqlServer&quot; =&gt; new SqlCommand(query, (SqlConnection)connection),<br>        &quot;Oracle&quot; =&gt; new OracleCommand(query, (OracleConnection)connection),<br>        _ =&gt; throw new NotSupportedException($&quot;Provider {provider} is not supported.&quot;)<br>    };<br>}</pre><p>In the end we have the “Ok” HealthCheck:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTwsxgizwDtxZ89ry0kRDA.png" /></figure><p>But, in case the application user doesn’t have access to a table, we will see the error. In this case, since I used Oracle, we will see the “Table or view doesn’t exist” error from Oracle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*olYohaI3ASDe_ttXop8EGw.png" /></figure><p>To setup this I’ve created a script that runs in Docker Compose:</p><pre>alter session set container = XEPDB1;<br><br>CREATE USER ADMIN IDENTIFIED BY password;<br><br>GRANT CONNECT, RESOURCE TO ADMIN;<br><br>create table ADMIN.SAMPLE_MESSAGES (<br>   id                   number<br>      generated by default as identity<br>   primary key,<br>   message_id           raw(16) default sys_guid() not null,<br>   message_date         timestamp default current_timestamp not null,<br>   message_deleted_date timestamp default null<br>);<br><br>create table ADMIN.WO_ACCESS (<br>   id                   number<br>      generated by default as identity<br>   primary key,<br>   message_id           raw(16) default sys_guid() not null,<br>   message_date         timestamp default current_timestamp not null,<br>   message_deleted_date timestamp default null<br>);<br><br>-- Create TESTUSER<br>CREATE USER TESTUSER IDENTIFIED BY password;<br><br>GRANT CONNECT TO TESTUSER;<br><br>-- Grant access only to SAMPLE_MESSAGES<br>GRANT ALL PRIVILEGES ON ADMIN.SAMPLE_MESSAGES TO TESTUSER;<br><br>commit;</pre><p>And as demonstrated, if we use the TESTUSER the application will not be able to select ADMIN.WO_ACCESS, but if we change the user in appsettings, the HealthCheck returns Healthy.</p><p>You can check the complete code here:</p><p><a href="https://github.com/paolofullone/KafkaPlayground">GitHub - paolofullone/KafkaPlayground: Pub/Sub Kafka Playground - POC Multiple Consumers</a></p><p>As of this article, the working commit is:</p><p>b0a6c2cc0bd284247e4ae58235eada85e66bcda2</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89bb22a7951" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Scaling Data Processing with .NET, Kafka, and Parallel Consumers”]]></title>
            <link>https://blog.devgenius.io/scaling-data-processing-with-net-kafka-and-parallel-consumers-659362b4fe0d?source=rss-1a0b612bc88c------2</link>
            <guid isPermaLink="false">https://medium.com/p/659362b4fe0d</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Paolo Fullone]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 17:33:33 GMT</pubDate>
            <atom:updated>2025-03-27T15:52:28.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaling Data Processing with .NET, Kafka, and Parallel Consumers</h3><p>Recently, I had the opportunity to develop a Web API and a Worker to handle a substantial amount of data. To share what I learned, I’ve simplified some of the code I developed and decided to present it here — hopefully, it’ll be helpful to you! The main challenge was to reduce processing time, and our strategy was to leverage multiple partitions per Kafka topic. In this example, we’ll simulate a topic with 50 partitions.</p><p>Let’s start by setting up the foundation. Below is the docker-compose.yml file, which includes Kafka, Kafdrop (a Kafka UI), and an init-kafka service to create our topic:</p><pre>services:<br>  kafka:<br>    image: confluentinc/cp-kafka:latest<br>    hostname: kafka<br>    container_name: kafka-confluent<br>    networks:<br>      - broker-kafka<br>    ports:<br>      - &quot;9092:9092&quot;<br>      - &quot;9093:9093&quot;<br>    environment:<br>      KAFKA_KRAFT_MODE: &quot;true&quot;<br>      KAFKA_PROCESS_ROLES: controller,broker<br>      KAFKA_NODE_ID: 1<br>      KAFKA_CONTROLLER_QUORUM_VOTERS: &quot;1@kafka:9093&quot;<br>      KAFKA_LISTENERS: BROKER://kafka:9091,EXTERNAL://0.0.0.0:9092,CONTROLLER://kafka:9093<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: BROKER:PLAINTEXT,CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXT<br>      KAFKA_INTER_BROKER_LISTENER_NAME: BROKER<br>      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>      KAFKA_ADVERTISED_LISTENERS: BROKER://kafka:9091,EXTERNAL://127.0.0.1:9092<br>      KAFKA_AUTO_CREATE_TOPICS_ENABLE: &quot;true&quot;<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_LOG_CLEANER_ENABLE: &quot;false&quot;<br>      KAFKA_NUM_PARTITIONS: 1<br>      KAFKA_LOG_RETENTION_HOURS: 168<br>      KAFKA_LOG_RETENTION_BYTES: -1<br>      CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk<br>    cap_drop:<br>      - NET_RAW<br><br>  init-kafka:<br>    image: confluentinc/cp-kafka:latest<br>    container_name: init-kafka<br>    networks:<br>      - broker-kafka<br>    depends_on:<br>      - kafka<br>    entrypoint: [ &#39;/bin/sh&#39;, &#39;-c&#39; ]<br>    command: |<br>      &quot;<br>      # blocks until kafka is reachable<br>      kafka-topics --list --bootstrap-server kafka:9091<br><br>      echo -e &#39;Creating topic &#39;<br>      <br>      kafka-topics --bootstrap-server kafka:9091 --create --if-not-exists --topic kafka-playground-topic --partitions 50 --replication-factor 1<br>      <br>      echo -e &#39;Sucessfully created topic&#39;<br><br>      kafka-topics --list --bootstrap-server broker:29092<br>      &quot;<br><br>  kafdrop:<br>    image: obsidiandynamics/kafdrop:latest<br>    container_name: kafdrop-local<br>    networks:<br>      - broker-kafka<br>    depends_on:<br>      - kafka<br>    ports:<br>      - &quot;9001:9000&quot;<br>    environment:<br>      KAFKA_BROKER_CONNECT: kafka:9091<br><br>networks:<br>  broker-kafka:<br>    driver: bridge</pre><p>Once the docker-compose setup is running, you should see the Kafdrop interface with our newly created topic, kafka-playground-topic, sporting 50 partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tyJgCNrklk4nf67zDfYNFg.png" /></figure><h4>The Web API</h4><p>The Web API’s role is straightforward: it publishes a specified number of messages to the Kafka topic. In Kafdrop, you’ll notice the messages distributed across the 50 partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*qP5d7WFlzdVGLtqZe8PjBw.png" /></figure><h4>The Worker</h4><p>On the Worker side, we configured 10 parallel consumers per instance. When the Worker starts, you’ll see 10 consumers instantiated, each with a unique name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JmeIDxhwX4TjjD3C8o4Ow.png" /></figure><p>And we can see that in this case 10 consumers were instantiated and each one of them has a different Name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*b3xmOSuSohiiH6-JuVvfPQ.png" /></figure><p>Here’s how I implemented this in C#:</p><pre>    class KafkaMessageConsumer&lt;T&gt; : IMessageConsumer&lt;T&gt;<br>    {<br>        private readonly List&lt;IConsumer&lt;Null, byte[]&gt;&gt; _consumers;<br>        private readonly string _topic;<br>        private readonly JsonSerializerOptions _options = new(JsonSerializerDefaults.Web);<br><br>        public KafkaMessageConsumer(ConsumerConfig consumerConfig, string topic, int parallelConsumers)<br>        {<br>            _consumers = new List&lt;IConsumer&lt;Null, byte[]&gt;&gt;();<br>            for (int i = 1; i &lt;= parallelConsumers; i++)<br>            {<br>                _consumers.Add(new ConsumerBuilder&lt;Null, byte[]&gt;(consumerConfig).Build());<br>                Console.WriteLine($&quot;Criando consumer {i}&quot;);<br>            }<br>            _topic = topic;<br>        }<br><br>        public string Topic =&gt; _topic;<br><br>        public Task StartConsumer(CancellationToken cancellationToken)<br>        {<br>            foreach (var consumer in _consumers)<br>            {<br>                consumer.Subscribe(_topic);<br>            }<br>            return Task.CompletedTask;<br>        }<br><br>        public async Task ConsumeAsync(Func&lt;T, CancellationToken, Task&gt; handle, CancellationToken cancellationToken)<br>        {<br>            var tasks = _consumers.Select(consumer =&gt; Task.Run(async () =&gt;<br>            {<br>                while (!cancellationToken.IsCancellationRequested)<br>                {<br>                    try<br>                    {<br>                        var message = consumer.Consume(cancellationToken);<br>                        var consumeResult = await JsonSerializer.DeserializeAsync&lt;T&gt;(new MemoryStream(message.Message.Value), _options, cancellationToken);<br><br>                        if (cancellationToken.IsCancellationRequested)<br>                            break;<br><br>                        await handle(consumeResult!, cancellationToken);<br>                    }<br>                    catch (Exception ex)<br>                    {<br>                        Console.WriteLine(ex);<br>                    }<br>                }<br>            }));<br>            await Task.WhenAll(tasks.ToArray());<br>        }<br>    }</pre><h4>Scaling with Kubernetes</h4><p>With this setup, we deployed the Worker to a Kubernetes cluster and configured Horizontal Pod Autoscaling (HPA) to scale up to 5 pods. Each pod can process 10 messages concurrently, giving us a total capacity of 50 messages at once — perfectly matching our 50 partitions!</p><h4>Final Achievement</h4><p>Just to demonstrate what we achieved a simple log of the different consumers consuming the messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Khqbz5I0dV4gdm1h3mPftA.png" /></figure><h4>Check Out the Full Code</h4><p>You can explore the complete source code here:</p><p><a href="https://github.com/paolofullone/KafkaPlayground">GitHub - paolofullone/KafkaPlayground: Pub/Sub Kafka Playground - POC Multiple Consumers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=659362b4fe0d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/scaling-data-processing-with-net-kafka-and-parallel-consumers-659362b4fe0d">“Scaling Data Processing with .NET, Kafka, and Parallel Consumers”</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Postman to save the login token]]></title>
            <link>https://medium.com/@paolo.enrico/using-postman-to-save-the-login-token-9860222d0a6c?source=rss-1a0b612bc88c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9860222d0a6c</guid>
            <category><![CDATA[token]]></category>
            <category><![CDATA[store]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[postman]]></category>
            <dc:creator><![CDATA[Paolo Fullone]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 23:26:58 GMT</pubDate>
            <atom:updated>2023-02-27T23:34:44.458Z</atom:updated>
            <content:encoded><![CDATA[<p>It is a bit annoying when we’re developing an API and we set up the token and have to login and store the token in the Swagger interface every time we re-build the application.</p><p>So I’ve searched a little and found some interesting solutions that I wanna concentrate here in a very short register.</p><p>So, straight to the point, I created a very small script under “Tests”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*hQdFn-O_TvBERtG2eV8VqQ.png" /></figure><p>It captures the response of the Login call and stores into a “res” variable. In my case the token was inside the res.data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wEAqU20je3zkvlqnk7kxkg.png" /></figure><p>And you can also store on “Global” Environments in Postman, just replace</p><pre>// This:<br>pm.collectionVariables.set...<br><br>// by:<br>pm.environment.set...</pre><p>So, if you place the Login call in a root collection folder and all the other requests inside folders, you can choose the “Inherit auth from parent” option, then you have to create a local variable for the token only in the collection level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*Apl6zV0_9VzeCuaMNBPRMA.png" /><figcaption>Example of a protected route</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDifvWD_4m4WnW9EEm8Vjw.png" /><figcaption>Collection Variable that receives the token value</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCxznKmXoNaVdRpta3X6HA.png" /><figcaption>Authorization that will be inherited by all routes</figcaption></figure><p>With this, every time you hit login, the token will be captured, stored in a variable and all the protected routes will be available.</p><p>BTW I came to this solution while I was studying <a href="https://www.udemy.com/course/net-core-31-web-api-entity-framework-core-jumpstart/">this </a>course by <a href="https://medium.com/u/58e69609a06a">Patrick God</a>.</p><p>That’s all!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9860222d0a6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>