<?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 Levent Ozturk on Medium]]></title>
        <description><![CDATA[Stories by Levent Ozturk on Medium]]></description>
        <link>https://medium.com/@leventozturk?source=rss-203269f130d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TUrdJwYO3yYfduIRX3C_mw.png</url>
            <title>Stories by Levent Ozturk on Medium</title>
            <link>https://medium.com/@leventozturk?source=rss-203269f130d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:19:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leventozturk/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[Black ‘Queue’ Down]]></title>
            <link>https://medium.com/@leventozturk/black-queue-down-0583bec2cafb?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0583bec2cafb</guid>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 19:26:46 GMT</pubDate>
            <atom:updated>2025-10-27T19:26:46.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*W2Xxa4oqltgZHhh4ySYoOQ.jpeg" /></figure><p>Hello everyone, after a long break.</p><p>Today, I want to talk about what should be considered to prevent message loss under heavy load in queue systems, which are commonly used in distributed architectures.</p><p>Let’s begin!</p><p>Our applications are often hard-dependent on one or more services. In other words, the application cannot function at all unless those services are up and running. This is usually a deliberate architectural decision, and the infrastructure is built accordingly. I won’t even count the database among these anymore.</p><p>A queue system is also used in most modern applications, and in many cases, it is a hard dependency as well. In such situations, when the queue structure becomes unreachable, certain precautions are taken to mitigate the issue. I will discuss some of these precautions with you.</p><p>First, I would like to point out that everything I will explain in this article can be found in the following project on my GitHub:<br> <a href="https://github.com/leventozz/outbox-relay">https://github.com/leventozz/outbox-relay</a></p><p>Technologies used in the sample project:</p><ul><li>.NET 8</li><li>MSSQL</li><li>EFCORE 9</li><li>RabbitMQ 7.1.2</li></ul><h4>Outbox Pattern</h4><p>When a queue system is mentioned in distributed systems, the first pattern that comes to mind is the Outbox Pattern. Of course, using OP is not limited to distributed systems. Whenever your application requires a lossless queue system, OP is the approach to use.</p><p>In short, OP is an architectural pattern used in microservices or distributed systems to ensure data consistency.</p><p>Core idea: to securely record a data change in a service and the message that conveys this change to other systems within the same atomic transaction.</p><ol><li>A service performs an operation (e.g., a money transfer request).</li><li>Within the same transaction, an event is added to an “outbox” table.</li><li>A separate process (e.g., a background worker or event relay) reads this outbox table and sends the events to the message queue (e.g., Kafka, RabbitMQ).</li><li>After the event is sent, the outbox record is marked as “processed.”</li></ol><p>The purpose here is to write a request to a database table first, instead of immediately writing it to the queue, and then process it periodically. This way, if the application cannot reach the queue, no data is lost; instead, the database stores the message until the queue becomes available again.</p><h3>Atomicity</h3><p>So what is this atomic transaction and why is it important?</p><p>An atomic transaction either succeeds completely and all changes become permanent, or in case of an error the system returns to its previous state as if no changes were applied.<br> This is crucial for the Outbox Pattern because we do not want the following scenario:</p><ol><li>A money transfer request arrives and is written to theMoneyTransferRequest table; the DB operation completes.</li><li>Then a separate DB operation is started to write to the Outbox table.</li></ol><p>If the flow works like this, the database connection might be lost after the write to MoneyTransferRequest, and the corresponding record may never reach the Outbox table. That directly causes data loss. Therefore these two writes must occur within the same databse operation (the same transaction). If the transaction succeeds, both tables are updated. If it fails, neither table is changed.</p><p>I will continue with code examples. In my sample project there is a simple money transfer scenario in practice it is more about updating a linked wallet than the transfer itself. I chose this because message loss in such operations causes serious problems. First, the application receives a request via the API and, based on that request, write the necessary records to the databases.</p><pre>public async Task&lt;Transaction&gt; RegisterTransactionAsync(int fromAccountId, int toAccountId, decimal amount)<br>{<br>    await _unitOfWork.BeginTransactionAsync();<br>    try<br>    {<br>        var transactionEntity = new Transaction<br>        {<br>            Id = Guid.NewGuid(),<br>            FromAccountId = fromAccountId,<br>            ToAccountId = toAccountId,<br>            Amount = amount,<br>            Status = (short)TransactionStatus.Pending,<br>            CreatedAt = DateTimeOffset.UtcNow<br>        };<br><br>        CreateTransactionMessage createTransactionMessage = new CreateTransactionMessage<br>        {<br>            Id = transactionEntity.Id<br>        };<br><br>        var payload = JsonSerializer.Serialize(createTransactionMessage, JsonDefaults.Default);<br>        var outboxEntity = new Outbox<br>        {<br>            Id = Guid.NewGuid(),<br>            Payload = payload,<br>            Status = (short)OutboxStatus.Pending,<br>            RetryCount = 0,<br>            CreatedAt = DateTimeOffset.UtcNow<br>        };<br>        await _unitOfWork.TransactionRepository.CreateAsync(transactionEntity);<br>        await _unitOfWork.OutboxRepository.CreateAsync(outboxEntity);<br>        await _unitOfWork.CommitAsync();<br>        return transactionEntity;<br>    }<br>    catch<br>    {<br>        await _unitOfWork.RollbackAsync();<br>        throw;<br>    }<br>}</pre><p>In the project, I implemented operations using a Unit of Work, which ensures atomicity. The CreateAsync methods do not contain SaveChangesAsync. This allows both tables to be written within a single database transaction, thereby achieving atomicity.</p><p>Additionally, the project includes two worker services: a publisher and a consumer. Now, let’s discuss the PublisherWorkerService.</p><pre>public class PublisherWorkerService : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        while (!stoppingToken.IsCancellationRequested)<br>        {<br>            try<br>            {<br>                await ProcessPendingOutboxMessagesAsync(stoppingToken);<br>            }<br>            catch (Exception ex)<br>            {<br>                _logger.LogError(ex, &quot;An unexpected error occurred while processing outbox messages.&quot;);<br>            }<br><br>            await Task.Delay(_pollingInterval, stoppingToken);<br>        }<br>    }<br><br>    private async Task ProcessPendingOutboxMessagesAsync(CancellationToken cancellationToken)<br>    {<br>        using var scope = _serviceScopeFactory.CreateScope();<br><br>        var dbContext = scope.ServiceProvider.GetRequiredService&lt;AppDbContext&gt;();<br>        var outboxRepository = scope.ServiceProvider.GetRequiredService&lt;IOutboxRepository&gt;();<br>        var rabbitMqPublisher = scope.ServiceProvider.GetRequiredService&lt;IRabbitMqPublisher&gt;();<br><br>        var pendingOutboxes = await outboxRepository.ClaimPendingMessagesAsync();<br><br>        if (!pendingOutboxes.Any())<br>        {<br>            _logger.LogDebug(&quot;No pending outbox record to be processed was found.&quot;);<br>            return;<br>        }<br><br>        var successfulOutboxes = new List&lt;Guid&gt;();<br>        var failedOutboxes = new List&lt;(Guid Id, int NewRetryCount, string ErrorMessage, bool IsMaxRetryReached)&gt;();<br><br>        foreach (var outbox in pendingOutboxes)<br>        {<br>            if (cancellationToken.IsCancellationRequested)<br>            {<br>                _logger.LogWarning(&quot;The process has been canceled, the outbox processing is being stopped.&quot;);<br>                break;<br>            }<br><br>            try<br>            {<br>                CreateTransactionMessage? message;<br><br>                try<br>                {<br>                    message = JsonSerializer.Deserialize&lt;CreateTransactionMessage&gt;(outbox.Payload, JsonDefaults.Default);<br><br>                    if (message == null)<br>                    {<br>                        var errorMsg = &quot;The outbox payload could not be deserialized.&quot;;<br>                        _logger.LogError($&quot;{errorMsg} OutboxId: {outbox.Id}&quot;);<br>                        failedOutboxes.Add((outbox.Id, outbox.RetryCount, errorMsg, true));<br>                        continue;<br>                    }<br>                }<br>                catch (JsonException jsonEx)<br>                {<br>                    _logger.LogError(jsonEx,<br>                        &quot;The outbox payload contains invalid JSON and cannot be deserialized. OutboxId: {OutboxId}&quot;,<br>                        outbox.Id);<br><br>                    failedOutboxes.Add((outbox.Id, outbox.RetryCount, $&quot;Invalid JSON: {jsonEx.Message},&quot;, true));<br>                    continue;<br>                }<br><br>                //at least once. check duplicates on consumer side<br>                await rabbitMqPublisher.PublishAsync(message, cancellationToken);<br>                successfulOutboxes.Add(outbox.Id);<br>            }<br>            catch (Exception ex)<br>            {<br>                _logger.LogError(ex, &quot;An error occurred while processing the outbox record. OutboxId: {OutboxId}, RetryCount: {RetryCount}&quot;,<br>                    outbox.Id, outbox.RetryCount);<br><br>                var newRetryCount = outbox.RetryCount + 1;<br>                var errorMessage = $&quot;{ex.GetType().Name}: {ex.Message}&quot;;<br><br>                var isMaxRetryReached = newRetryCount &gt;= _maxRetryCount;<br><br>                if (isMaxRetryReached)<br>                {<br>                    _logger.LogWarning(<br>                        &quot;The outbox record has reached the maximum retry count and will be marked as Failed. OutboxId: {OutboxId}, RetryCount: {RetryCount}&quot;,<br>                        outbox.Id, newRetryCount);<br>                }<br>                else<br>                {<br>                    _logger.LogInformation(<br>                        &quot;The outbox record will be retried. OutboxId: {OutboxId}, RetryCount: {RetryCount}/{MaxRetry}&quot;,<br>                        outbox.Id, newRetryCount, _maxRetryCount);<br>                }<br><br>                failedOutboxes.Add((outbox.Id, newRetryCount, errorMessage, isMaxRetryReached));<br>            }<br>        }<br><br>        await using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);<br><br>        try<br>        {<br>            if (successfulOutboxes.Any())<br>            {<br>                await outboxRepository.BulkUpdateStatusAsync(successfulOutboxes, (short)OutboxStatus.Completed);<br>            }<br><br>            if (failedOutboxes.Any())<br>            {<br>                var maxRetryReachedIds = failedOutboxes.Where(f =&gt; f.IsMaxRetryReached).Select(f =&gt; f.Id).ToList();<br>                var retryableIds = failedOutboxes.Where(f =&gt; !f.IsMaxRetryReached).Select(f =&gt; f.Id).ToList();<br><br>                if (maxRetryReachedIds.Any())<br>                {<br>                    await outboxRepository.BulkUpdateStatusAsync(maxRetryReachedIds, (short)OutboxStatus.Failed);<br>                }<br><br>                if (retryableIds.Any())<br>                {<br>                    await outboxRepository.BulkUpdateStatusAsync(retryableIds, (short)OutboxStatus.Pending);<br>                }<br><br>                var retryInfos = failedOutboxes.Select(f =&gt; (f.Id, f.NewRetryCount, f.ErrorMessage)).ToList();<br>                await outboxRepository.BulkUpdateRetryInfoAsync(retryInfos);<br>            }<br>            await transaction.CommitAsync(cancellationToken);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Failed to update outbox statuses in database. Rolling back transaction.&quot;);<br>            await transaction.RollbackAsync(cancellationToken);<br>        }<br>    }<br>}</pre><p>The code may seem long, but the process is actually very simple:</p><ol><li>Retrieve messages to be processed from the Outbox database.</li><li>Publish them.</li><li>Update the published messages in the Outbox database.</li></ol><p>The challenge here is scalability.</p><h4>Scalability and Race Condition</h4><p>If you run multiple instances of this worker service, you must ensure that the data retrieved from the database does not overlap. You do not want to publish the same message twice or mark it as published incorrectly. Therefore, the content of my ClaimPendingMessagesAsync method is as follows:</p><pre>public async Task&lt;IEnumerable&lt;Outbox&gt;&gt; ClaimPendingMessagesAsync(int batchSize = 5)<br>{<br>    var sql = $@&quot;<br>        UPDATE TOP (@batchSize) Outboxes<br>        SET <br>            Status = @newStatus,<br>            LastAttemptAt = GETUTCDATE() <br>        OUTPUT <br>            inserted.*<br>        FROM <br>            Outboxes WITH (UPDLOCK, READPAST, ROWLOCK)<br>        WHERE <br>            Status = @oldStatus <br>            AND (<br>                RetryCount = 0 <br>                OR <br>                DATEADD(second, POWER(2, RetryCount), LastAttemptAt) &lt;= GETUTCDATE()<br>            );<br>    &quot;;<br><br>    SqlParameter[] parameters =<br>    [<br>        new() { ParameterName = &quot;@batchSize&quot;, Value = batchSize, SqlDbType = SqlDbType.Int },<br>        new() { ParameterName = &quot;@newStatus&quot;, Value = (short)OutboxStatus.Processing, SqlDbType = SqlDbType.SmallInt },<br>        new() { ParameterName = &quot;@oldStatus&quot;, Value = (short)OutboxStatus.Pending, SqlDbType = SqlDbType.SmallInt }<br>    ];<br><br>    return await _context.Outboxes<br>        .FromSqlRaw(sql, parameters)<br>        .AsNoTracking()<br>        .ToListAsync();<br>}</pre><p>The goal here is to atomically change records in the Outbox table with a “Pending” status to “Processing” so that no other process can claim them simultaneously. This ensures that a message is not processed by multiple workers at the same time.</p><ul><li>UPDLOCK: Places an update lock on the read rows (prevents other transactions from accessing the same row).</li><li>READPAST: Skips locked rows (prevents deadlocks).</li><li>ROWLOCK: Locks at the row level.</li></ul><p>Additionally, instead of updating the status of successful or failed Outbox records immediately, I keep them in memory lists and update them atomically in a single operation. This reduces the risk of zombie messages in case of a connection loss or similar issues.</p><h3>Exponential Backoff</h3><p>If RabbitMQ crashes, the Publisher will receive an error and increment the message&#39;s RetryCount. This SQL logic increases the retry interval exponentially (2, 4, 8, 16 seconds…) as RetryCount grows. This gives a failing system time to recover and prevents active Publisher instances from overwhelming a downed RabbitMQ with hundreds of requests per second, effectively avoiding a self-inflicted DDoS.</p><h3>At-Least-Once Delivery</h3><p>At-least-once delivery is a delivery strategy in message- or event-based systems that guarantees a message reaches the receiver at least once. While it ensures the message is not lost, the same message may be delivered multiple times. In such cases, duplicate publish handling is expected to occur on the Consumer side. Now, I will explain the ConsumerWorkerService.</p><pre>protected override async Task ExecuteAsync(CancellationToken cancellationToken)<br>{<br>    while (!cancellationToken.IsCancellationRequested)<br>    {<br>        try<br>        {<br>            _connection = await _rabbitMqClientService.GetConnectionAsync();<br>            _channel = await _connection.CreateChannelAsync();<br><br>            await _channel.BasicQosAsync(prefetchSize: 0, prefetchCount: 1, global: false, cancellationToken: cancellationToken);<br><br>            _consumer = new AsyncEventingBasicConsumer(_channel);<br><br>            _consumer.ReceivedAsync += (sender, @event) =&gt;<br>                Consumer_ReceivedAsync(sender, @event, cancellationToken);<br><br>            await _channel.BasicConsumeAsync(<br>                queue: RabbitMqConstants.TransactionQueueName,<br>                autoAck: false,<br>                consumer: _consumer);<br><br>            _logger.LogInformation(&quot;Consumer subscribed to queue. Waiting for messages.&quot;);<br><br><br>            while (!cancellationToken.IsCancellationRequested)<br>            {<br>                await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);<br>            }<br>        }<br>        catch (OperationCanceledException)<br>        {<br>            _logger.LogWarning(&quot;Consumer Worker Service cancelled.&quot;);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogCritical(ex, &quot;Consumer Worker Service failed critically.&quot;);<br>        }<br>    }<br>}<br><br>private async Task Consumer_ReceivedAsync(object sender, BasicDeliverEventArgs @event, CancellationToken cancellationToken)<br>{<br>    CreateTransactionMessage createTransactionMessage;<br><br>    try<br>    {<br>        createTransactionMessage = JsonSerializer.Deserialize&lt;CreateTransactionMessage&gt;(<br>            Encoding.UTF8.GetString(@event.Body.ToArray()),<br>            JsonDefaults.Default);<br><br>        if (createTransactionMessage == null)<br>        {<br>            throw new InvalidOperationException(&quot;Deserialized message is null.&quot;);<br>        }<br>    }<br>    catch (Exception ex)<br>    {<br>        _logger.LogWarning(ex, &quot;Failed to deserialize message. Sending to NACK.&quot;);<br>        await _channel.BasicNackAsync(@event.DeliveryTag, false, false);<br>        return;<br>    }<br><br>    using (var scope = _serviceScopeFactory.CreateScope())<br>    {<br>        var consumerHandler = scope.ServiceProvider.GetRequiredService&lt;IMessageHandler&lt;CreateTransactionMessage&gt;&gt;();<br>        try<br>        {<br>            await consumerHandler.HandleAsync(createTransactionMessage, cancellationToken);<br>            await _channel.BasicAckAsync(deliveryTag: @event.DeliveryTag, multiple: false);<br>        }<br>        catch (SqlException ex)<br>        {<br>            _logger.LogWarning(ex, &quot;Transient database error detected. Requeuing message. DeliveryTag: {DeliveryTag}&quot;, @event.DeliveryTag);<br><br>            await _channel.BasicNackAsync(<br>                deliveryTag: @event.DeliveryTag,<br>                multiple: false,<br>                requeue: true); <br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Permanent or unexpected error detected. Message will be NACKED (no requeue) to prevent infinite loop. DeliveryTag: {DeliveryTag}&quot;, @event.DeliveryTag);<br><br>            await _channel.BasicNackAsync(<br>                deliveryTag: @event.DeliveryTag,<br>                multiple: false,<br>                requeue: false);<br>        }<br>    }<br>}</pre><p>As you may notice, the consumer side is much simpler than the publisher side. The reason is as follows.</p><h3>Smart Publisher, Dumb Consumer</h3><p>The consumer should be as simple, idempotent, side-effect-free, and non-decision-making as possible. All business logic and complexity regarding when and how a message is produced reside in the publisher or upstream systems. Therefore, the worker only subscribes to the queue and starts listening for events. When an event arrives, it forwards it to the appropriate handler via HandleAsync and completes its task.</p><h3>Requeue</h3><p>On the consumer side, some exceptions are marked with requeue = false. This separates critical errors from minor, easily recoverable ones. For instance, if an exception occurs due to a temporary DB outage, the message is returned to the queue because it can be processed again once the DB is back online. However, if the exception is genuine and non-recoverable, the message is discarded to prevent an infinite loop.</p><h3>Overall</h3><p>The goals of this project were:</p><ul><li>No message loss in case RabbitMQ goes down.</li><li>Operations can resume from where they left off once RabbitMQ recovers.</li><li>No silent message loss under any load.</li><li>Atomicity maintained throughout all stages of the project.</li><li>Minimization of zombie messages (messages with indeterminate status).</li><li>Scalability without issues.</li></ul><p>As mentioned above, the project is available on <a href="https://github.com/leventozz/outbox-relay">GitHub</a>. Feedback and comments on the project are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0583bec2cafb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile App Development Journey from Start to End]]></title>
            <link>https://medium.com/@leventozturk/mobile-app-development-journey-from-start-to-end-10e885b76fe8?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/10e885b76fe8</guid>
            <category><![CDATA[play-store]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[close-testing]]></category>
            <category><![CDATA[app-store]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 07:40:13 GMT</pubDate>
            <atom:updated>2025-04-11T15:30:20.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*81zCAiWXi-PIY04PyZTAKA.jpeg" /></figure><p>Hello everyone,</p><p>As a backend developer, I recently went through a mobile app development journey using react-native. Because even though I have been in the software industry for many years, I didn’t know much about this subject and it was a matter of curiosity for me. While I had no idea about launching an app on a marketplace, I learned a lot of new things and I wanted to share them with you.</p><p>Let’s start if you are ready.</p><h3>Development Environment</h3><p>In this article, I will talk about the marketplace part of the app, not the development part.</p><p>I developed my application using Expo, which was not really a conscious choice, but towards the end of the journey Expo helped me a lot and I was glad I chose it. I didn’t want to break my comfort zone, so I did my development on a Windows computer using Visual Studio Code.</p><h3>What is Required?</h3><ul><li>Google Developer Account</li></ul><p>Of course, you need a Google developer account to be able to put apps on the Google Play market. You can open a Google developer account with the link below. When opening this account, Google will ask you for some documents to verify your identity. In order to avoid problems in this part, it would be best to provide an invoice issued in your name, including your address, to indicate your residence. <strong>And lastlly, if you are producing for the android environment, they want you to have at least one physical android device. You will have to enter your account from that device for your account to be active!</strong> I am not sharing any fees as fees vary from country to country. <a href="https://play.google.com/console/u/0/signup">https://play.google.com/console/u/0/signup</a></p><ul><li>Apple Developer Account</li></ul><p>You also need to have an Apple developer account. Although the process here is similar to Google, it is actually easier and shorter. <a href="https://developer.apple.com/">https://developer.apple.com/</a></p><blockquote>Don’t forget! It will take a few days for your developer accounts to be approved.</blockquote><h3>Design Needs</h3><h4>App Icon and Splash Screen</h4><p>Our application will first need an icon and splahs screen. There is a Figma template prepared by Expo for this. There is also a video explaining how you can design the app icon and splash screen for both iOS and Android. You can easily design your app icon and splash screen using this template.</p><p><strong>Figma Template:</strong> <a href="https://www.figma.com/design/lG6TYAYUdhQz9rdvWupZT3/Expo-App-Icon-%26-Splash-v2-(Community)-(Community)?m=auto&amp;is-community-duplicate=1&amp;fuid=1480183389075846674">Link</a></p><p><strong>Tutorial Video:</strong> <a href="https://www.youtube.com/watch?v=3Bsw8a1BJoQ">https://www.youtube.com/watch?v=3Bsw8a1BJoQ</a></p><p>You do not need to use Expo to use them. After exporting the images, you can use them in any way you want.</p><h4>Marketplace Images</h4><p>Like every application in the marketplaces, our application will need appropriate visuals to be displayed in the marketplaces. If you are a design-impaired person like me, don’t be afraid, I found a site made for this.</p><p><strong>AppMockup:</strong> <a href="https://app-mockup.com/">https://app-mockup.com/</a></p><p>With the paid or free templates available on this site, you can quickly create the necessary visuals for the marketplace (ios/android) of your application very easily. This site is actually based on Figma. So you may need a basic level of Figma knowledge, but why does ChatGPT exist anyway? :)</p><blockquote>Note: Make sure that the application images you upload for the App Store are .jpg, not .png. Images with .png can cause problems during upload.</blockquote><h3>Privacy Policy</h3><p>No matter how simple your app is or even if it is an app that does not keep/use data, marketplaces expect a privact policy from you. If you have data collection, processing, etc. in your application, I strongly recommend you to get help from a legal advisor on this issue. But if you have an application that does not have any of these, there is a site whre you can prepare a privacy policy in seconds and upload it.</p><p><strong>App Privacy Policy Generator:</strong> <a href="https://app-privacy-policy-generator.firebaseapp.com/">https://app-privacy-policy-generator.firebaseapp.com/</a></p><p>Step by step, the site asks you simple questions about your app, creates the appropriate privacy policy, and at the end of the process deploys it to Flycricket, giving you a url that you can give to marketplaces. A great service!</p><blockquote>Note: If during your Expo build, you get an error like “invalid .png” about the your assets in your application, re-add all the pngs in your app using a png converter. If you manually changed the file extension(.jpg -&gt; .png) like me, you may encounter this error during Expo build.</blockquote><h3>Production Process</h3><p>After we have taken care of the parts so far, we come to the exciting part. How to get the app into production. After completing the above marketplace requirements, marketplaces will have a lot of questions about your app: “Is there a purchase for the product?”, ‘Does the app show ads?’, ‘What age range is your app suitable for?’. Answering these questions correctly will definitely make things easier. If everything is ok so far, we are ready to upload the first version to the marketplace.</p><h3>App Store Steps</h3><p>First of all, App Store asks you for your app with the “.ipa” extension. There are a few ways to get this, but I dont talk about them much in this article. Again, you can easily get your “.ipa” file for your app easily using Expo EAS. After you get the iOS build on Expo, you will see the option to publish for App Store. After doing this, you can see your app’s build on the App Store and prepare a new version. After you prepare your new version and send it for review, the Test Flight version will be ready for your app. The users you specify can download this Test Flight version to their phones and test it before the product is released to production. Testing this part with as many devices as possible will allow your app to provide a more smoother experience.</p><p>After your app goes through a short review process (1–2 days), you will be notified that your app is ready for production and congratulations! Your app is now ready for users to download on the App Store.</p><h3>Play Store Steps</h3><p>Now I will explain the process on the Play Store side. It’s similar to the App Store, but if your Google Developer Account was created after November 2023, you’re now required to test your application in a closed environment with 12 testers for 14 days.</p><h4>12 Testers Thing</h4><p>Google has a new way to improve the quality of apps uploaded to the marketplace. If you created your account after November 2023, Google expects you to test your app with at least 12 testers in a closed test for at least 14 days to get approval for your app.</p><h4>How To Get Testers</h4><p>Google says you can find testers in your family, among your colleagues, or by buying a service. I suggest finding other developers who need testers on forums and websites and test with them. I suggest checking out the Reddit platform for more information.</p><p>Another important thing to know is that the testers should open your application at least once a day during this 14-day period. This process is monitored by Google and is an important step in getting to production approval. If your application isn’t approved, Google might ask you to test it again for 14 days.</p><h4>What’s important in the closed testing process?</h4><ul><li>First of all, the 14 days will start as soon as you find 12 testers and get them to download your app. As I said before, you can test your apps with other developers who need test back on the forums.</li><li>For 14 days, testers must not delete your app. To deal with this, I suggest finding more than 12 testers. Someone will definitely delete your app in closed testing period.</li><li>Make sure you really test your app. While this process can be long and difficult, it’s also an opportunity to see how your app looks and behaves on different devices. Make the most of this process by ask feedback and using it to improve your app.</li><li>It’s important that testers open and test your app daily. If you feel that you cannot provide this, try to find more than 12 testers. If you find one new tester a day, that means your app has been opened at least once a day during the closed testing process.</li><li>During the closed testing period, publish multiple new versions and have your testers download and test each one. At the end of the closed testing period, Google will ask questions like, <strong>“What did you fix in your app based on the feedback you received?”</strong> The new versions you publish will show that you’ve fixed something.</li></ul><h4>After Closed Testing Completed</h4><p>After 14 days, you can apply for production approval via Play Console. During this application, Google ask you a lot of questions about the closed testing process. If you answer these questions correctly, it will be easier to get production approval. Once you have production approval, you won’t need a closed testing process for new releases in the app. If you have a question like:</p><blockquote><strong>“Do I have to do this closed testing process for every app I make after my first app?”</strong></blockquote><blockquote><strong>The answer is “YES!”.</strong></blockquote><p>Unfortunately, Google is not planning to change this process at this time. You have successfully passed your first app through the 14-day closed testing process, and now you want to release a new app. For this new app, you must also go through this 14-day closed testing process AGAIN.</p><h3>Conclusion</h3><p>Congratulations on making it this far! The next steps will be marketing your application. I hope you can find a way to make a good exit.</p><p>I would also like to talk about my app, which is the reason I wrote this article. “Ne Yesem?” This app is basically a food selection app. When you can’t decide what to eat, the app gives you two options to choose from. It asks you to choose one option, and then it gives you a new option. This continues until the options are finished. My goal is to reduce <strong>decision fatigue</strong>, which is when we’re overwhelmed by too many choices.</p><p>The app is currently only available in Turkish, as it focuses on Turkish food options. Please try my app and share your thoughts.</p><p>Apple Store: <a href="https://apps.apple.com/us/app/ne-yesem/id6743452152">Link</a></p><p>Google Play Store: <a href="https://play.google.com/store/apps/details?id=com.whattoeat.orderhelper&amp;pli=1">Link</a></p><p>Linkedin Post: <a href="https://www.linkedin.com/feed/update/urn:li:activity:7313487174635560961/">Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10e885b76fe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Alternative To Traditional Exception Handling in .NET]]></title>
            <link>https://medium.com/@leventozturk/an-alternative-to-traditional-exception-handling-in-net-2b7a49477532?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b7a49477532</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[net-core-8]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 18:03:24 GMT</pubDate>
            <atom:updated>2025-10-24T08:36:29.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Alternative To Traditional Exception Handling in .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*2zVYTpPCZTelkr_7vPIVJg.jpeg" /></figure><p>Hello everyone,</p><p>In today’s article, I would like to talk about an alternative to traditional exception handling in the .NET Core.</p><h3>What is traditional approach</h3><p>I admit it’s a bit pretentious to call it <em>traditional</em>, but in every large-scale project we always see a custom exception middleware and all the exceptions in the application are caught by this middleware and processed accordng to your needs.</p><pre>public ExceptionMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br>    public async Task InvokeAsync(HttpContext httpContext)<br>    {<br>        try<br>        {<br>            await _next(httpContext);<br>        }<br>        catch (Exception ex)<br>        {<br>            await HandleExceptionAsync(httpContext, ex);<br>        }<br>    }<br>    private Task HandleExceptionAsync(HttpContext context, Exception exception)<br>    {<br>        context.Response.ContentType = &quot;application/json&quot;;<br>        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;<br>        var response = new<br>        {<br>            StatusCode = context.Response.StatusCode,<br>            Message = &quot;Internal Server Error occurred.&quot;,<br>            Detailed = exception.Message <br>        };<br>        var jsonResponse = JsonConvert.SerializeObject(response);<br>        return context.Response.WriteAsync(jsonResponse);<br>    }<br>}</pre><p>As you can get, the code you see above will catch the error in the try-catch block and return the result. So far so good, but the try-catch block is actually a very costly block of code for us. Because:</p><blockquote><em>When an exception is thrown, the runtime creates an Exception object. Creating this object and setting the information in it, such as error messages and error codes, takes up extra memory and processing power. For example, when an exception is thrown:</em></blockquote><blockquote>-Error Message and Stack Trace are added to this object. Creating the stack trace is particularly costly because all the information on the call stack is captured and recorded.</blockquote><blockquote>-When an exception object is created, its life cycle in memory starts and the Garbage Collector has to clean it up later. This add an additional cost.</blockquote><p>Even if this is hardly noticeable in small-scale applications, it’s something you really need to consider in large-scale applications.</p><h3>So, what else can we do?</h3><p>This is where the <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-8.0"><strong>UseExceptionHandler</strong></a>, which has been around since the first version of .NET Core and has evolved over time, comes to our help. To put it simply: UseExceptionHandler is a middleware that provides specialized handling and management of errors that occur during application execution. In other words, the same process that we do by writing an extra middleware, it takes care of itself within the framework.</p><h3>How to use?</h3><blockquote>Note: You can find my project with sample codes in the <a href="https://github.com/leventozz/exception-handler">my github repo</a>.</blockquote><p>It is quite simple to use in the first place. You can implement it in your <strong>Program.cs</strong> file in a way similar to the following:</p><pre>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>    app.UseDeveloperExceptionPage();<br>}<br>else<br>{<br>    app.UseExceptionHandler(errorApp =&gt;<br>    {<br>        errorApp.Run(async context =&gt;<br>        {<br>            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;<br>            context.Response.ContentType = &quot;text/html&quot;;<br><br>            var exceptionHandlerPathFeature = context.Features.Get&lt;IExceptionHandlerPathFeature&gt;();<br>            if (exceptionHandlerPathFeature?.Error != null)<br>            {<br>                var logger = app.Services.GetRequiredService&lt;ILogger&lt;Program&gt;&gt;();<br>                logger.LogError($&quot;Something went wrong: {exceptionHandlerPathFeature.Error.Message}&quot;);<br>            }<br><br>            await context.Response.WriteAsync(exceptionHandlerPathFeature.Error.Message).ConfigureAwait(false);<br>        });<br>    });<br>    app.UseHsts();<br>}</pre><p>Now here, if you are in development environment, we provide a more detailed exception, and if you are in production environment, we provide the error you customized. Also, considering that our application is not MVC but an API, we provide a return accordingly in the production environment.</p><p>We are throwing an exception through the controller:</p><pre>[HttpGet(Name = &quot;GetWeatherForecast&quot;)]<br>public IEnumerable&lt;WeatherForecast&gt; Get()<br>{<br>    throw new NotImplementedException(&quot;test exception&quot;);<br>}</pre><p>As a result of this process, our outputs are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPnF06IDTDRv4mISwHmUZQ.jpeg" /><figcaption>Development Environment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBWJ08b7u5kHYOZfph8Npg.jpeg" /><figcaption>Production Environment</figcaption></figure><p>It’s actually that simple.</p><h3>Another option that comes with .NET 8: IExceptionHandler</h3><p>With .NET 8, IException middleware, which provides a different perspective on centralized exception handling, entered our lives. This is also very simple to use. In this approach, you create your own exception middleware, implement the IExceptionHandler interface and configure it according to your needs.</p><pre>public class ExcepitonMiddleware : IExceptionHandler<br>{<br>    public async ValueTask&lt;bool&gt; TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)<br>    {<br>        //Logging and other bussiness<br><br>        var problemDetails = new ProblemDetails<br>        {<br>            Status = StatusCodes.Status500InternalServerError,<br>            Title = &quot;Something went wrong...&quot;,<br>            Detail = exception.Message<br>        };<br><br>        httpContext.Response.StatusCode = problemDetails.Status.Value;<br><br>        await httpContext.Response<br>            .WriteAsJsonAsync(problemDetails, cancellationToken);<br><br>        return true;<br>    }<br>}</pre><p>Program.cs:</p><pre>builder.Services.AddExceptionHandler&lt;ExcepitonMiddleware&gt;();<br>builder.Services.AddProblemDetails();<br><br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>    app.UseDeveloperExceptionPage();<br>}<br>else<br>{<br>    app.UseExceptionHandler();<br>    app.UseHsts();<br>}</pre><p>Here again, we can make exception seperation for production and development environments.</p><p>Results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQR1ajp3GIAx_9cag8HH3A.jpeg" /><figcaption>Development Env.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_hd0bp-oDBUQHnrmn3_2Q.jpeg" /><figcaption>Production Env.</figcaption></figure><h3>Why should we consider using these approaches?</h3><p>I can give you several good reasons for this:</p><ul><li><strong>Performance:</strong> These two approaches are more optimized in terms of performance than the traditional middleware approach.</li><li><strong>Easy to implement:</strong> As you can see in the code examples, it will take a few minutes to implement the standard versions of these approaches. Customizing them to your needs will only take a few hours.</li><li><strong>Compliance with standards:</strong> Using a built-in tool in the .NET ecosystem makes your project easily understood by the wider community. This is especially useful in teamwork and open source projects.</li><li><strong>A Ready and Tested Solution:</strong> It is a thoroughly tested and optimized middleware developed by the .NET team. Many of the details you need to consider when writing your own custom middleware are already covered in this middleware. This ensures reliability and stability, especially in sensitive issues such as error handling.</li></ul><h3>Conclusion</h3><p>In this article, I want to talk about different approaches that you can use instead of traditional exception handling. Of course, remember that the necessity of these approaches depends on your application. So the correctness and suitability of a method is directly related to your project and your needs. By thinking in this way, you can determine the most suitable approach for you. You can also access the sample project where I applied these approaches from <a href="https://github.com/leventozz/exception-handler">my github repo</a>. Thank you for reading this far.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b7a49477532" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Best Approach For Long Time-Taking Tasks in .Net]]></title>
            <link>https://medium.com/@leventozturk/the-best-approach-for-long-time-taking-tasks-in-net-9f84b4138987?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f84b4138987</guid>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[net-core-6]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[background-jobs]]></category>
            <category><![CDATA[hangfire]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 12:17:58 GMT</pubDate>
            <atom:updated>2024-06-01T12:17:58.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Best Approach For Long Time-Taking Tasks in .Net</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*tJSh7AWny7Sc0bIutx_dgw.jpeg" /></figure><p>Hello everyone,</p><p>Today I would like to talk about the most convenient method that you can apply in the .Net for tasks that take minutes, maybe hours: Hangfire Background Jobs</p><h3>When might we need it?</h3><p>If you’re doing something in your app that will take minutes or hours, and it affects the app frontend, you might want to take a look at Hangfire Background Jobs.</p><p>At the very beginning of long time-taking tasks, we can give reporting as an example. For example; Excel export is a common reporting example that we encounter in many applications. When you create a report with a large and complex data set and want to output it to Excel, this can take minutes. Here we will look at how we can approach such a situation.</p><h3>What is Hangfire?</h3><blockquote>Hangfire is a topic in itself, so I’ll just talk about what it is without going into too much detail.</blockquote><p>Hangfire is a .NET based background job management library. It allows developers to easily define and manage various background jobs, tasks or cron-style scheduled jobs.</p><p>There are 4 different main jobs on Hangfire. These are as follows:</p><ul><li><strong>Fire-and-Forget:</strong> This type of work is usually carried out immediately and not continued after completion.</li><li><strong>Delayed Jobs:</strong> Such works are planned to be executed after a certain period of time.</li><li><strong>Recurring Jobs:</strong> Bu tür işler, belirli aralıklarla (örneğin günlük, haftalık) tekrar eden işlerdir.</li><li><strong>Continuation Jobs:</strong> This type of work is scheduled to be carried out after the previous work has been completed.</li></ul><h3>Worst case scenario</h3><p>Let’s prepare a scenario like this to show what I explained above in code: Let’s have an endpoint that does an Excel export job and let’s imagine that this process takes about 1 minute and let’s write our code for it:</p><p>It’s a simple controller:</p><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class ReportController : ControllerBase<br>{<br>    [HttpGet(Name = &quot;GetReportWorst&quot;)]<br>    public async Task&lt;IActionResult&gt; GetRGetReportWorsteport()<br>    {<br>        await Task.Delay(TimeSpan.FromMinutes(1));<br>        return Ok();<br>    }<br>}</pre><p>The approach you see above is one of the worst approaches you can use in your application. Because the frontend can be blocked during this process, the process can be interrupted when switching to a different page, or other similar problems can be encountered. You can see the possible scenario when you stand up the project and make a request to this endpoint via swagger.</p><h3>Let’s use Background Jobs.</h3><p>First, we need a database. Because Hangfire needs a databas. Then we add the Hangfire library to our project.</p><blockquote><a href="https://www.nuget.org/packages/Hangfire">https://www.nuget.org/packages/Hangfire</a></blockquote><p>We add these codes to the Program.cs file:</p><pre>builder.Services.AddHangfire(config =&gt; config.UseSqlServerStorage(builder.Configuration.GetConnectionString(&quot;HangFireExampleConnection&quot;)));<br>builder.Services.AddHangfireServer(opt =&gt; opt.SchedulePollingInterval = TimeSpan.FromSeconds(1));<br>app.UseHangfireDashboard(); //To see background jobs on dashboard</pre><p>Then let’s create a simple clas containing our method that will do the job:</p><pre>public class ReportService<br>{<br>    public async Task GetReportAsync(CancellationToken cancellationToken)<br>    {<br>        //Do excel export things<br>        await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);<br>    }<br>}</pre><p>Let’s add this class to our services:</p><pre>builder.Services.AddTransient&lt;ReportService&gt;();</pre><p>Finally, let’s create our endpoint:</p><pre>[HttpPost(&quot;GetReportWithBackgroundJob&quot;)]<br>public async Task&lt;IActionResult&gt; GetReportWithBackgroundJob()<br>{<br>    IBackgroundJobClient client = new BackgroundJobClient();<br>    var jobId = client.Enqueue&lt;ReportService&gt;(job =&gt; job.GetReportAsync(CancellationToken.None));<br>    return Ok(&quot;BackgroundJob Started. jobId:&quot; + jobId);<br>}</pre><p>After standing up the application, let’s check Hangfire’s dashboard without triggering the endpoint:</p><blockquote>If you haven’t done any customization, the default address of the Hangfire dashboard will be: <a href="https://localhost/">https://localhost</a>:****/hangfire</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*vBioE5ab9EyQU-5OhVz4Mg.png" /><figcaption>Hangfire Dashboard</figcaption></figure><p>As you can see above, you can see all the jobs that Hangfire manages according to their types in this screen. After calling the endpoint, we are waiting for this method to appear in the “Processing” tab. After call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aUDwmuoin40yXMuWqn1PYg.png" /></figure><p>We will also use the jobId you see in the response in the future:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*PP_4mQvEu-k4-paByxpanw.png" /></figure><p>So far, we have been able to successfully add a 1 minute mission as a Bakground Job using Hangfire, so what do we do next?</p><h3>Check Background Jobs</h3><p>Another feature that Hangfire provides us is the ability to query the status of background jobs. We will do this as follows:</p><pre>[HttpGet(&quot;GetJobDetail&quot;)]<br>public async Task&lt;IActionResult&gt; GetJobDetail(string jobId)<br>{<br>    var jobDetails = JobStorage.Current.GetMonitoringApi().JobDetails(jobId);<br>    var state = jobDetails.History.OrderByDescending(h =&gt; h.CreatedAt).First().StateName;<br>    return Ok(state);<br>}</pre><p>And now when we run a background job and come to this endpoint with the jobId we have, we can see the status of that background job:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*7NQf64-LFpTA84Ugrc5msw.png" /></figure><p>After 1 minute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*IcraBzigGhat47U5BAJyDA.png" /></figure><p>We can now assign our long-running processes to a background process using Hangfire and periodically check the status of this process and inform the frontend accordingly. This way the frontend can continue without any blocking.</p><h3>Better Way: Use SignalR</h3><p>While writing an endpoint that checks the status of a background job, as in the example above, is not a bad approach, there is a much better way: Using the SignalR library!</p><p>Previously, I wrote an article about how SignalR and Worker Service can be used together:</p><p><a href="https://medium.com/@leventozturk/signalr-and-worker-service-in-net-core-1a3f5cebbb7e">SignalR and Worker Service in .Net</a></p><p>You can write the method that controls the background job in a while loop, check it every 10 seconds, and easily notify the frontend of the status with SignalR. In this way, you will avoid unnecessary requests and you will have a more professional approach. You can also find detailed information about this in the article I mentioned above.</p><h3>Final words…</h3><p>With the simple example above, I wanted to show how we can handle long reporting tasks that we often encounter in our business life. You should consider trying this method, which can be easily applied even to more complex cases that occur in real life.</p><p>You can also access the sample project I mentioned above from my GitHub account:</p><p><a href="https://github.com/leventozz/HangFireExample">Hangfire Example Repo</a></p><p>Thank you for reading.</p><p>Happy codding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f84b4138987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RulesEngine: Business Rule Helper]]></title>
            <link>https://medium.com/@leventozturk/rulesengine-business-rule-helper-f585ba918473?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f585ba918473</guid>
            <category><![CDATA[net6]]></category>
            <category><![CDATA[business-rule-engine]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 15:54:30 GMT</pubDate>
            <atom:updated>2024-03-10T15:54:30.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*wG_ZisoFLXolTiJh0H41QQ.jpeg" /></figure><p>Hello everyone,</p><p>Today, I would like to talk about business rules that we often encounter in the software development process and their implementation in practice. There is a <strong>Microsoft</strong> library that will help us with the business rules that need to be applied during a process in our application: <strong>RulesEngine</strong>.</p><h3>What is it?</h3><p>Library link: <a href="https://github.com/microsoft/RulesEngine">https://github.com/microsoft/RulesEngine</a></p><p>If we look directly at Microsoft’s definition:</p><blockquote>Rules Engine is a library/NuGet package for abstracting business logic/rules/policies out of a system. It provides a simple way of giving you the ability to put your rules in a store outside the core logic of the system, thus ensuring that any change in rules don’t affect the core system.</blockquote><p>Yes, as mentioned above, RulesEngine is a json-based business rule management library.</p><h3>Why is it needed?</h3><p>Or why should we use it? Imagine that each of the operations our application performs has more than one business rule. You can often see examples of this, especially in financial applications. In order to make a money transfer or a payment transaction, multiple business rules need to be applied to that transaction. If you don’t have a centralized business rule control system, your code will turn into a spaghetti of if else code blocks.</p><p>In such a case, when a new business rule is added or a rule is changed, the effort to make that change will be very high. At the same time, it would be very difficult for new developers coming into the project to understand this block of code and be able to write code on it. This is why we need a library like RulesEngine.</p><p>I have left the link to the library above, you can make a detailed examination from there. Now let’s see how we can use this library with a few console application examples.</p><h3>Examples</h3><p>First let’s install our nuget package:</p><blockquote>paket add RulesEngine — version 5.0.3</blockquote><p>After installing the package, we need to create our rules file. For this, we create a json file as below:</p><p>Basically, in a money transfer transaction, we will check if there is sufficient funds in the account sending money.</p><pre>[<br>  {<br>    &quot;WorkflowName&quot;: &quot;Transfer&quot;,<br>    &quot;Rules&quot;: [<br>      {<br>        &quot;RuleName&quot;: &quot;BalanceControl&quot;,<br>        &quot;SuccessEvent&quot;: &quot;10&quot;,<br>        &quot;ErrorMessage&quot;: &quot;you do not have enough funds for this transaction.&quot;,<br>        &quot;ErrorType&quot;: &quot;Error&quot;,<br>        &quot;RuleExpressionType&quot;: &quot;LambdaExpression&quot;,<br>        &quot;Expression&quot;: &quot;input1.Balance &gt;= input2&quot;<br>      }<br>    ]<br>  }<br>]</pre><p>Then we add this json file to the directory where our application is located. Note that here you can manage these rules with cache through Redis.</p><p>Then we create our object that will act as a bank account:</p><pre>class BankAccount<br>{<br>    public string AccountNumber { get; set; } = &quot;123456789&quot;;<br>    public int Balance { get; set; } = 1000;<br>}</pre><p>The rest of the code is as follows:</p><pre>using Newtonsoft.Json;<br>using RulesEngine.Models;<br>using RulesEngine.Extensions;<br><br>decimal transferAmount = 1500;<br>dynamic input1 = new BankAccount();<br>dynamic input2 = transferAmount;<br>var inputs = new dynamic[]<br>    {<br>        input1,<br>        input2<br>    };<br>var files = Directory.GetFiles(Directory.GetCurrentDirectory(), &quot;TransferRules.json&quot;, SearchOption.AllDirectories);<br>if (files == null || files.Length == 0)<br>    throw new Exception(&quot;Rules not found.&quot;);<br>var fileData = File.ReadAllText(files[0]);<br>var workflow = JsonConvert.DeserializeObject&lt;List&lt;Workflow&gt;&gt;(fileData);<br>var bre = new RulesEngine.RulesEngine(workflow.ToArray(), null);<br>string message = string.Empty;<br>List&lt;RuleResultTree&gt; resultList = bre.ExecuteAllRulesAsync(&quot;Transfer&quot;, inputs).Result;<br>resultList.OnSuccess((eventName) =&gt;<br>{<br>    message = &quot;Money transfer took place&quot;;<br>});<br>resultList.OnFail(() =&gt;<br>{<br>    var failedRule = resultList.Find(r =&gt; !r.IsSuccess);<br>    if (failedRule != null)<br>    {<br>        message = failedRule.ExceptionMessage;<br>    }<br>    else<br>        message = &quot;exception&quot;;<br>});<br>Console.WriteLine(message);<br>class BankAccount<br>{<br>    public string AccountNumber { get; set; } = &quot;123456789&quot;;<br>    public int Balance { get; set; } = 1000;<br>}</pre><ul><li>In the first step, our dynamic variables are created.</li><li>Then the rules we set from the json file are read.</li><li>The rules are executed for the inputs we specify and the message we receive according to the result is written on the screen.</li></ul><p>So, you can run and apply all the business rules that need to be applied in a money transfer phase with a single line of code.</p><h3>For enthusiasts</h3><p>Information on how this library works is available here: <a href="https://github.com/microsoft/RulesEngine/wiki/Introduction#how-it-works">https://github.com/microsoft/RulesEngine/wiki/Introduction#how-it-works</a></p><p>But to summarize briefly; the rules that meet the conditions are taken from the required database, matched with the incoming input messages through a wrapper, and the rules are provided by the rules engine.</p><h3>Negative sides</h3><ul><li>Debbugging difficulty: When you debug a rule to understand why it passes or fails, you may not get very meaningful results. But you can get used to it as you use it.</li><li>Complex rule writing: When you try to write very complex rules, the fact that the expression is a plain string doesn’t help you much.</li></ul><h3>Conclusion</h3><p>If you have to control a large number of business rules in your project, give this library a try. Once you get used to it, you can easily write even complex rules and keep your code clean and understandable.</p><p>Thank you for reading this far. You can access the sample project I created above from here: <a href="https://github.com/leventozz/rulesengine-example">https://github.com/leventozz/rulesengine-example</a></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f585ba918473" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursive Methods : Could it be simplest way to solve the problem?]]></title>
            <link>https://medium.com/@leventozturk/recursive-methods-could-it-be-simplest-way-to-solve-the-problem-5eb5bb2e07a7?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eb5bb2e07a7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[net6]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 10:57:34 GMT</pubDate>
            <atom:updated>2024-01-24T10:57:34.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recursive Methods : Could it be simplest way to solve the problem?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*PhzK9uN2edMu7GE1gCn5AA.jpeg" /></figure><p>Hello everyone,</p><p>Today, I will try to explain what recursive methods are, which are often used in artificial intelligence and machine learning. Probably most of us have used recursive methods while coding without realizing it. Let’s talk about some details in this article.</p><h3>What is?</h3><p>Short description: A method or algorithm that invokes itself one or more times with different arguments.</p><blockquote>In the world of computer science and programming, there are different methods and techniques for solving various algorithmic problems. One of these methods, the “recursive” method, is a powerful approach to solving a problem by breaking it down into smaller sub-problems. The recursive method has a number of advantages in making problems more understandable, readable and manageable.</blockquote><p>Let me give a simple code example:</p><pre>class Program<br>{<br>    static void Main()<br>    {<br>        int number= 5;<br>        int result= FactorialRecursive(number);<br><br>        Console.WriteLine($&quot;{result}&quot;);<br>    }<br><br>    static int FactorialRecursive(int n)<br>    {<br>        if (n == 0 || n == 1)<br>            return 1;<br><br>        return n * FactorialRecursive(n - 1);<br>    }<br>}</pre><h3>Why should we consider using it?</h3><p>When you should use it actually depends on your algorithm and your project, but let’s take a look at what advantages it gives us in general:</p><p><strong>Simplifying Complex Problems:</strong></p><p>One of the most important advantages of the recursive method is the ability to break a complex problem into smaller and more understandable sub-problems. This simplifies the solution by focusing on smaller and more manageable pieces, rather than solving a complex problem.</p><p><strong>Improving Redability of Code:</strong></p><p>Another important advantage of the recursive method is its ability to improve the readability of the code. A recursive function works by calling a smaller version of itself instead of solving the problem directly.</p><p><strong>Flexibility in Algorithm Design:</strong></p><p>The flexibility of a recursive method is also related to its ability to adapt to various algorithmic problems. For example, recursive methods can be used effectively in many areas such as tree structures, sorting algorithms and graph problems.</p><p>Of course, it is not certain that recursive methods will give you these advantages. But it is still worth considering. You should test the most suitable method for your algorithm and then implement it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*a8m46v3hb9bz1hLi.png" /><figcaption>source: geeksforgeeks</figcaption></figure><h3>Recursive methods in artificial intelligence</h3><p>In fact, what got us thinking about this approach is that recursive methods are used very often in artificial intelligence.</p><p>A common occurrence in artificial intelligence (AI) applications is the complexity of data structures and the use of tree-structured data structures. These trees often have a complex hierarchy, and recursive methods are very useful for navigating or performing operations on this hierarchy.</p><p>For example, consider a language tree. This tree represents a sentence or word structure. By visiting this tree, recursive methds can be used for tasks such as understanding language structure, analyzing word features or applying grammar rules.</p><p>At the same time, AI applications often work with large data sets. Recursive methods are an effective solution for processing and analyzing these data sets and selecting data with specific characteristics. A recursive approach breaks the data set into small pieces and processes each piece to arrive at an overall solution.</p><p>For example, consider an image processing algorithm. Recursive methods can be used to find specific patterns in the image or to analyze the image. By processing each pixel and dividing the image into smaller parts, the algorithm can detect regions with specific features.</p><p>These results can change the way we look at recursive methods!</p><h3>Back to coding</h3><p>In terms of coding, I will look at how recursive methods work in the .NET.</p><p>I gave a simple example of using a recursive method above, now let’s see how to write it without a recursive method:</p><pre>class Program<br>{<br>    static void Main()<br>    {<br>        int number= 5;<br>        int result= FactorialIterative(number);<br><br>        Console.WriteLine($&quot;{result}&quot;);<br>    }<br><br>    static int FactorialIterative(int n)<br>    {<br>        int factorial= 1;<br>        for (int i = 1; i &lt;= n; i++)<br>        {<br>            factorial*= i;<br>        }<br><br>        return factorial;<br>    }<br>}</pre><p>If you are seeing a recursive method for the first time, you will probably find the iterated version more readable. But once you get used to working with recursive methods, it will be easier to read and implement than an iteration.</p><p>Let’s continue with an example that is familiar to all of us:</p><pre>string word = &quot;hello&quot;;<br><br>string reversedWordRecursive = ReverseStringRecursive(word);<br>string reversedWordIterative = ReverseStringIterative(word);<br><br>Console.WriteLine($&quot;Original Word: {word}&quot;);<br>Console.WriteLine($&quot;Reversed Word (recursive): {reversedWordRecursive}&quot;);<br>Console.WriteLine($&quot;Reversed Word (iterative): {reversedWordIterative}&quot;);<br><br>//RECURSIVE<br>static string ReverseStringRecursive(string input)<br>{<br>    if (string.IsNullOrEmpty(input) || input.Length == 1)<br>        return input;<br>    return input[^1] + ReverseStringRecursive(input[0..^1]);<br>}<br><br>//ITERATIVE<br>static string ReverseStringIterative(string input)<br>{<br>    char[] charArray = input.ToCharArray();<br>    int start = 0;<br>    int end = input.Length - 1;<br>    while (start &lt; end)<br>    {<br>        char temp = charArray[start];<br>        charArray[start] = charArray[end];<br>        charArray[end] = temp;<br>        start++;<br>        end--;<br>    }<br>    return new string(charArray);<br>}</pre><h3>What about performance?</h3><p>Recursive methods tend to be inherently slower than iterations. There are several main reasons for this:</p><ul><li><strong>Function Call Overhead:</strong> Recursive methods create a new function call with each invocation. These function calls take up space in the call stack and require additional processor time to manage the function’s parameters, local variables and return address. Iterative methods, on the other hand, execute the same block of code repeatedly in a loop and therefore have less function call overhead.</li><li><strong>Memory Management:</strong> Recursive methods store local variables and state on the call stack with each call. This can significantly increase memory usage, especially when deep recursive calls are made. Iterative methods usually use less memory because they use the same variables over and over again.</li><li><strong>Compiler Optimizations:</strong> Compilers tend to better optimize iterative methods. For example, they can apply techniques such as loop unrolling, placing variables in registers, and optimizing memory access. Such optimizations can be more difficult to achieve in recursive methods.</li></ul><blockquote>NOTE: Some problems are naturally more amenable to recursive solutions, and in these cases recursive methods can be more readable and understandable. However, for simple problems such as array addition, iterative methods are often more efficient.</blockquote><p>I created a benchmark to explain this. Here is my code:</p><pre><br><br>BenchmarkRunner.Run&lt;Sumbenchmark&gt;();<br><br>public class Sumbenchmark<br>{<br>    static int[] HighVolumeArray()<br>    {<br>        int[] array = new int[10000];<br>        for (int i = 0; i &lt; array.Length; i++)<br>        {<br>            array[i] = i;<br>        }<br>        return array;<br>    }<br><br>    int[] testArray = HighVolumeArray();<br><br>    [Benchmark]<br>    public int SumOfArrayIterativeBenchmark()<br>    {<br>        return SumOfArrayIterative(testArray);<br>    }<br><br>    [Benchmark]<br>    public int SumOfArrayRecursiveBenchmark()<br>    {<br>        return SumOfArrayRecursive(testArray,0);<br>    }<br><br>    static int SumOfArrayIterative(int[] array)<br>    {<br>        int sum = 0;<br>        for (int i = 0; i &lt; array.Length; i++)<br>        {<br>            sum += array[i];<br>        }<br>        return sum;<br>    }<br><br>    static int SumOfArrayRecursive(int[] array, int index)<br>    {<br>        if (index &gt;= array.Length)<br>        {<br>            return 0;<br>        }<br>        return array[index] + SumOfArrayRecursive(array, index + 1);<br>    }<br>}</pre><p>This is the result I got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*2Jeizc9tpp9ICsv7y3WvZw.png" /><figcaption>The iteration seems to be 5 times faster.</figcaption></figure><h3>Conclusion</h3><p>As I have already mentioned in the note above, there are problems for which the recursive method is inherently appropriate and it is quite suitable for solving these problems. But for every problem that requires iteration, using the recursive method does not seem appropriate in terms of performance and general software approach. If you look at your problems from this point of view, you can find the best way for you.</p><p>Thank you for reading this far. If you also have examples of recursive methods, you can specify in the comments.</p><p>Happy codding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eb5bb2e07a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NET Aspire]]></title>
            <link>https://medium.com/@leventozturk/net-aspire-523e323ba3eb?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/523e323ba3eb</guid>
            <category><![CDATA[net8]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[aspire]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 21:26:15 GMT</pubDate>
            <atom:updated>2023-12-26T21:26:15.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*yTISD1rvscUt_gcBiAu0jQ.jpeg" /></figure><p>Hello everyone,</p><p>Today I’m coming to you with a brand new technology stack: .NET Aspire.</p><p>Aspire is a cloud ready stack for building distributed applications, introduced in preview with .NET 8.</p><p>Microsoft defines it as follows:</p><blockquote>.NET Aspire is an opinionated, cloud ready stack for building observable, production ready, distributed applications. .NET Aspire is delivered through a collection of NuGet packages that handle specific cloud-native concerns. Cloud-native apps often consist of small, interconnected pieces or microservices rather than a single, monolithic code base. Cloud-native apps generally consume a large number of services, such as databases, messaging, and caching.</blockquote><p>More info about Aspire: <a href="https://learn.microsoft.com/en-us/dotnet/aspire/get-started/aspire-overview">https://learn.microsoft.com/en-us/dotnet/aspire/get-started/aspire-overview</a></p><p>Let’s create our first Aspire project with you and take a brief look at what’s inside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*r3DQ2DfAHM1aUPUknGTcnA.jpeg" /><figcaption>Create New Project screen</figcaption></figure><p>To create an Aspire project, you must first have a version of Visual Studio Preview.</p><p>When you click on Create New Project and search for “Aspire”, you will see 2 results:</p><ul><li>The first option here is a completely empty Aspire template.</li><li>The second option is a stack with Blazor frontend, web API backend and even Redis.</li></ul><p>Let’s continue with the “Starter Application” and see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*luHtP-YMYnwfKEW0y16C0w.jpeg" /><figcaption>Net Aspire Solution Explorer</figcaption></figure><p>Our template with 4 projects is ready. Now let’s see what this template contains. The names of the projects actualy explain what they do. If you’ve dealt with distributed architecture before, these are familiar to you.</p><p>First, let’s look at Program.cs in AspireApp.ApiService :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-MmQkYoJcJj0KBx5Hd2xUA.jpeg" /><figcaption>AspireApp.ApiService\Program.cs</figcaption></figure><p>Here we see one minimal API that comes ready-made. It is not a screen we are very unfamiliar with.</p><p>Continue with AspireApp.AppHost\Program.cs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*K8VhXiWHjyF-dGNduON-PQ.jpeg" /><figcaption>AspireApp.AppHost\Program.cs</figcaption></figure><p>Here we see that two projects are registered to the host named “apiservice”, “webfronted” which are important.</p><blockquote>This is exactly where Aspire enables you to configure your distributed services. When more microservices are added to your project in the future, you will be able to easily register them here. Aspire will take care of these services for you.</blockquote><p>Continue with AspireApp.ServiceDefaults Extension.cs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4190e86a2d9927bf0f43dbac38bc93bd/href">https://medium.com/media/4190e86a2d9927bf0f43dbac38bc93bd/href</a></iframe><blockquote>NOTE: The <strong>.AddServiceDefaults()</strong> method we see in AspireApp.ApiService\Program.cs comes from here(line 14).</blockquote><p>These codes are new to us. You can see that Opentelemetry comes turned on by default to capture metrics, traces and logs. From line 77 onwards, even Prometheus and Azure Monitor codes are ready for the export of Opentelemetry data. It’s a convenience that will really come in handy.</p><blockquote><a href="https://medium.com/towardsdev/jaeger-with-opentelemetry-c2c6e07fa06c">https://medium.com/towardsdev/jaeger-with-opentelemetry-c2c6e07fa06c</a></blockquote><blockquote>Also you can check my article about Opentelemetry and Jaeger.</blockquote><p>Finally, let’s take a look at your <a href="http://aspireapp.web/">AspireApp.Web</a>\Program.cs file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i74j8DHUBtrnYVzRp0BtQg.jpeg" /><figcaption><a href="http://aspireapp.web/">AspireApp.Web</a>\Program.cs</figcaption></figure><p>Here we see that “<a href="http://apiservice/">http://apiservice</a>&quot; has been added as an HttpClient, which corresponds to the AspireApp.AppHost\Program.cs file.</p><p>So far, we have looked at roughly what each project does and what code it contains. As a first impression, we can realize that this technology stack makes a lot of things easier for us.</p><p>Now let’s try adding Redis output cache to the frontend:</p><p>I added that single line code in <a href="http://aspireapp.web/">AspireApp.Web</a>\Program.cs</p><pre>builder.AddRedisOutputCache(&quot;cache&quot;);</pre><p>And added registration codes in app host like this:</p><pre>var builder = DistributedApplication.CreateBuilder(args);<br><br>var redis= builder.AddRedisContainer(&quot;cache&quot;);<br><br>var apiservice = builder.AddProject&lt;Projects.AspireApp_ApiService&gt;(&quot;apiservice&quot;);<br><br>builder.AddProject&lt;Projects.AspireApp_Web&gt;(&quot;webfrontend&quot;)<br>    .WithReference(redis)<br>    .WithReference(apiservice);<br><br>builder.Build().Run();</pre><p>And changed minimal api like this:</p><pre>app.MapGet(&quot;/weatherforecast&quot;, [OutputCache] () =&gt;<br>{<br>    var forecast =  Enumerable.Range(1, 5).Select(index =&gt;<br>        new WeatherForecast<br>        (<br>            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),<br>            Random.Shared.Next(-20, 55),<br>            summaries[Random.Shared.Next(summaries.Length)]<br>        ))<br>        .ToArray();<br>    return forecast;<br>}).CacheOutput();</pre><p>That’s all. You don’t need any connection string or any other settings, Aspire does it all for you!</p><p>Let’s start our application by selecting AspireApp.AppHost as the startup project.</p><p>We are greeted by the Aspire dashboard where we can monitor everything. We can really monitor everything: Projects, Containers, Traces, Metrics…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NygYXCiQMt7BxnkXcimTuw.jpeg" /><figcaption>Aspire dashboard</figcaption></figure><p>In “Containers” you can see Redis container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dO_ZgX8NgkoIlDGrq3mkug.jpeg" /><figcaption>Aspire dashboard Containers tab</figcaption></figure><p>Let’s go to endpoint to see our UI under “Projects”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGRwMAlS9mQY-ljaw5Jn1A.jpeg" /><figcaption>Blazor UI Weather tab</figcaption></figure><p>After checking if our API is working by coming to the “Weather” tab, let’s take a look at the traces section in the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9SJoMfB0HqcZZEGU3SL4g.jpeg" /><figcaption>Aspire dashboard Traces tab</figcaption></figure><p>All trace data is here without any external tracing platform. It is serious.</p><p>This technological stack, which is currently in a preview state, offers many easy ways to build distributed architecture applications and more importantly, to monitor them. From this simple project, it’s up to your imagination what you can do with it!</p><p>You can find this sample project on my Github account: <a href="https://github.com/leventozz/net-aspire-app">https://github.com/leventozz/net-aspire-app</a></p><p>And as I mentioned above, you can also take a look at my article about Opentelemetry and traces(I gave information about creating and reading trace data):</p><p><a href="https://medium.com/towardsdev/jaeger-with-opentelemetry-c2c6e07fa06c">https://medium.com/towardsdev/jaeger-with-opentelemetry-c2c6e07fa06c</a></p><p>That’s all I can tell you about .NET Aspire for now. Thank you for taking the time to read it.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=523e323ba3eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotency on .NET]]></title>
            <link>https://medium.com/@leventozturk/idempotency-on-net-84d5c9ea57f5?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/84d5c9ea57f5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[net-7]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[idempotency]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 09:48:08 GMT</pubDate>
            <atom:updated>2023-11-22T09:48:08.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>Idempotency on .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*V0sCexTk9yQnhXxvMLzi0w.jpeg" /></figure><p>Hello,</p><p>Today I am going to talk about “Idempotency”, a topic that came to me unexpectedly and surprised me in my software life. That’s why I wanted to talk about it with you from the beginning to the end, so here we go!</p><p>The application you will see below can be found in the following <a href="https://github.com/leventozz/idempotency">repo on my github profile</a>.</p><h3>First of all, define!</h3><p><strong>Idempotence</strong>, refers to the property that the result of an operation does not change when it is applied one or more times. If an operation is idempotent, applying the same operation many times will not change or affect the result.</p><p>That’s all. Yes, you have to think a little bit simpler.</p><h4>The equivalent in software development language?</h4><p>If a method returns the same result every time it is called, it is an idempotent method.</p><blockquote>For example, since the request &quot;get/product/3&quot; will always give us the product with id 3, we can define this request as idempotent.</blockquote><h3>Why is this important?</h3><p>The importance of this is not really understood when we illustrate it as above. The keyword to emphasize this topic’s importance is <strong>“distributed architecture”</strong>!</p><p>Because;</p><p>Idempotent operations ensure consistency in the system in case the same request is sent several times. In a distributed architecture, a request may be sent more than once due to network failures, lost requests or coordination issues between services. Thanks to idempotent operations, we can deal with such situations and ensure that services maintain a consistent state.</p><blockquote>For example, imagine a payment service. When the user confirms a transaction, the payment service performs a payment, naturally. However, due to a bug on the user’s device or network issues, the confirmation request on the user side may be sent more than once. An idempotent payment service method would be designed to produce the same result when it receives the same payment request again. This ensures that only one payment is made, even if the user sends multiple confirmations.</blockquote><h3>In .NET</h3><p>Now that we have gone through the definitions and talked about where and why it matters to us. We can talk about what we can do to provide this feature.</p><p>Basically, we have to do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*WqRPUhbt9rc4JqfCnpqrzA.png" /></figure><h3>Steps</h3><ul><li>First, we need to make each request unique so that we can distinguish which request has already been processed and which has not. For this, it may be enough to take a parameter in the header of our requests.</li><li>You need to save this unique parameter in the request header when you process the request. This way you can distinguish which request you have already processed.</li><li>You can check the parameter in the header of each incoming request and return the appropriate response. Here, you can return a response that you have cached, you can also return a successful or failed response. This is up to the needs of your application.</li></ul><p>In fact, when you want to write an idempotent API, this is all you need to do.</p><h3>Detailed steps</h3><ul><li>You need to pay close attention to the unique parameter you create. Because, for example, in a scenario where sensitive transactions take place, such as a payment system, accidentally creating more than one of the same unique parameter at any time will cause major problems.</li><li>You have to choose the right platform for recording this unique parameter. In a transaction-intensive API, these reads will be very frequent, so a distributed cache may seem like the best choice, but again, you should choose it according to your application’s requirements.</li><li>If you are going to use a distributed cache, the lifetime of the cache you store should be meaningful to you. It should not create too much load, nor should it be so short that it cannot be accessed when needed.</li></ul><p>I talked about how you can make an API idempotent in the simplest way. By following these ways, you can easily set up your own idempotent structure in your application or you can do this much more easily with the nuget package I am about to show you.</p><h3>IdempotentAPI</h3><p><a href="https://github.com/ikyriak/IdempotentAPI">Package Github Link</a></p><p><a href="https://www.nuget.org/packages/IdempotentAPI/">Nuget Package</a></p><p>IdempotentAPI is an open source library that helps you write idempotent APIs, and it does it very well. You can access the details from the Github and Nuget links I added above. I will also explain how you can implement it in a simple way.</p><p>Description of this library by the author:</p><blockquote>The IdempotentAPI is an open-source NuGet library, which implements an <a href="http://asp.net/">ASP.NET</a> Core attribute (filter) to handle the HTTP write operations (POST and PATCH) that can affect only once for the given request data and idempotency-key.</blockquote><h3>Implementation</h3><ol><li>First, we create an API project. For simplicity, I will work with the WeatherForecastController that comes automatically when you create the API.</li><li>Then we add the IdempotentAPI library to our project.</li></ol><blockquote><em>PM&gt; Install-Package IdempotentAPI -Version 2.1.0</em></blockquote><p>We register the service in Program.cs.</p><pre>builder.Services.AddIdempotentAPI();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*ZZZC8OhZuozzSsdJOqgCyg.jpeg" /></figure><blockquote>This library supports both distributed cache and memory cache as primary cache. We will continue with distributed cache.</blockquote><p>3. So we also add the IdempotentAPI.Cache.DistributedCach package to our project.</p><p>We registers the services in Program.cs.</p><pre>builder.Services.AddDistributedMemoryCache(); <br>builder.Services.AddIdempotentAPIUsingDistributedCache();</pre><p>4. We mark the response DTO object we will use as [Serializable].</p><pre>[Serializable] <br>public class WeatherForecast <br>{  <br>  public DateOnly Date { get; set; }<br>  public int TemperatureC { get; set; }<br>  public int TemperatureF =&gt; 32 + (int)(TemperatureC / 0.5556);<br>  public string? Summary { get; set; }<br>}</pre><blockquote>Note: If we want to make all methods in the controller idempotent, we can also write the [Idempotent(ExpireHours = 48)] property on top of the controller. Like this:</blockquote><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>[Consumes(&quot;application/json&quot;)]<br>[Produces(&quot;application/json&quot;)]<br>[Idempotent(ExpireHours = 48)]<br>public class WeatherForecastController : ControllerBase</pre><p>5. So we mark our controller with these two properties.</p><pre>[Consumes(&quot;application/json&quot;)]<br>[Produces(&quot;application/json&quot;)] <br>public class WeatherForecastController : ControllerBase</pre><p>6. But for now we will make only one method idempotent. We write the required attribute on top of our method.</p><pre>[Idempotent(ExpireHours = 1)] <br>public IEnumerable&lt;WeatherForecast&gt; Post()</pre><blockquote>Note: This library will make your POST and PATCH actions idempotent. Please pay attention to this.</blockquote><p>That’s all. We are done coding, now let’s test it.</p><p>First, let’s make a request without adding the IdempotencyKey key to request header and see the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*7Rrqi58gZV4TCWYhNbSAbw.jpeg" /><figcaption>We’ve got an exception without IdempotencKey</figcaption></figure><p>This key is now expected in the header.</p><p>Now let’s set this key as &quot;1234&quot; and see the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*7aHl8eRefj3y29CS9j6Myw.jpeg" /></figure><p>Our randomly generated data arrived properly. Now let’s differentiate our key and try again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*IU5HWrwc8ZJoouPc5GFKzw.jpeg" /><figcaption>Diffrent key diffrent data</figcaption></figure><p>We have obtained different data again. Now let’s repeat our request with the &quot;1234&quot; key we used before. If everything is working correctly, we should see the same result as we got before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*2evWYAymNH7Px630mb90hg.jpeg" /><figcaption>You can check datas same as first try</figcaption></figure><p>It works very well!</p><h3>Conclusion</h3><p>In the simple example above, I used IdempotencyKey as a simple value to make it easy to understand. In real life, you have to ensure that the key you create here will be unique. This library is also open to different caching methods. You can check the library’s github page for this. Idempotency is a very important issue that you will definitely encounter if you use a distributed architecture. It will be the most beneficial method for you to determine the requests of your project correctly and build a structure suitable for your project. In this article, I have explained to you in a simple way what kind of principle we should work with.</p><p>As I mentioned at the beginning, you can access the simple application I wrote above from the <a href="https://github.com/leventozz/idempotency">repo on my github account</a>.</p><p>Thank you for reading this far. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84d5c9ea57f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jaeger with OpenTelemetry]]></title>
            <link>https://towardsdev.com/jaeger-with-opentelemetry-c2c6e07fa06c?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2c6e07fa06c</guid>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[jaegertracing]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 09:38:04 GMT</pubDate>
            <atom:updated>2023-10-25T15:59:04.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*LrA5oEtUW6jtjwFT_IXK7A.jpeg" /></figure><p>Hi everyone,</p><p>Today, I’m going to talk about <strong>JaegerTracing</strong>, a tracing platform. First of all, let me explain what observability is?</p><blockquote><strong>NOTE:</strong> Before getting into the subject, you should be familiar with OpenTelemetry and tracing in order to better understand this article. I recommend you to take a brief look at these topics before this article. I’ll write a separate article about Tracing and OpenTelemetry, but for now I will only talk about Jaeger to keep the article from getting too long.</blockquote><p>It is very important for us to know the performance of our application, how it will behave in the prod environment. This is called observability.</p><p><strong>Observability</strong> is simply the traceability rate of your application. The higher this ratio is in the development env, the better the behavior of the app in production can be predicted.I’ll explain the details of observability in detail in another article, so I will not elaborate too much now.</p><p>With logs, trace data and metrics you can monitor the performance and behavior of your application. APMs come into play when it comes to visualizing this data and making it searchable.</p><blockquote>APM: Application Performance Monitoring. Visualizes the collected log and metric data and allows you to query within this data.</blockquote><p>We can actually define Jaeger briefly in 2 terms: Open source, distributed tracing platform. It saves, indexes, visualizes, makes query. A free apm tool.</p><p>In this article, as an example in a .NET application, I will try to explain how the trace data I created using OpenTelemetry looks like with jaeger and how the graphics should be read.</p><blockquote>OpenTelemety: It is opensource observation framework. Allows you to set up a common structure independent from APM. Support by CNCF.</blockquote><h3>Let’s start with Docker</h3><p>Since we are going to stand up Jaeger in docker, we add the necessary codes to our docker-compose.yml file. You can also find these codes on Jaeger’s own site:</p><p><a href="https://www.jaegertracing.io/docs/1.50/getting-started/">Getting Started</a></p><p>docker-compose.yml:</p><pre>version: &#39;3.4&#39;<br>services:<br> jaeger:<br>  image: jaegertracing/all-in-one:1.49</pre><p>docker-compose.override.yml:</p><pre>services:<br> jaeger:<br>  container_name: &quot;jaeger-container&quot;<br>  ports: <br>   - 4317:4317 #grpc<br>   - 4318:4318 #http<br>   - 16686:16686 #ui</pre><p>First step completed.</p><h3>Explain the scenario</h3><p>In this example, we will examine an application that is partly built with a microservices infrastructure. We have Order API, Stock API and Payment API. Here’s how our flow works:</p><h4><strong>Order API(Redis Set, Redis Get and Db) → Stock API → Payment API</strong></h4><blockquote>In the example I tried to do a lot of processing to show a lot of variations, so I wanted to show you how they look on the Jaeger screen.</blockquote><p>In the real world, microservices communicate with each other through a message broker, but in this example they will communicate via http request so as not to make the topic too long. You can find the code on <a href="https://github.com/leventozz/observability-net">my github account</a>. I won’t talk much about the code part.</p><p>We have created our <strong>spans</strong> and <strong>events</strong> through OpenTelemetry, let’s talk a little bit about the Jaeger screen we will see by throwing our first request.</p><p>We stand up our containers using the “docker-compose up” command. Jaeger’s interface is available at: <a href="http://localhost:16686/">http://localhost:16686/</a></p><p>You will see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXjDi82qV6IiuhjCFFHtTQ.png" /><figcaption>Jaeger UI</figcaption></figure><p>As you can see, there is a simple and useful menu on the left side that allows us to search.</p><p>Since we define a resource for each api through OpenTelemetry, we see all our api in the “Servive” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*J5BzTL4ve0hk-l6lneeXxA.png" /><figcaption>Jaeger UI Search Menu</figcaption></figure><p>Let’s press the Find Traces button and see what we see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02-ZdKd-LpHm_f4qcapqLg.png" /><figcaption>Search results</figcaption></figure><p>On this screen you can see all the requests that your app makes and that you customize. We can see which path these requests took, how long it took, or if there was an error in the request.</p><p>The first two requests seen on the screen belong to elastic search, you can ignore them. Let’s examine the record I marked in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwxchejKlYA_bmpj1GQ29Q.png" /><figcaption>Trace details</figcaption></figure><p>Now we are talking. As you can see, we can examine which stages a request to Order.API goes through on its journey to Payment.API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*4s_-IBs8vBigACVR4yWylQ.png" /><figcaption>Request life cycle</figcaption></figure><p>With the help of the timeline on the right, we can see which operation lasted how long. By looking at this, we can understand where to intervene in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwxchejKlYA_bmpj1GQ29Q.png" /><figcaption>Timeline</figcaption></figure><p>You can customize the data to be displayed on this screen and the format of the data using the OpenTelemetry library. By setting new events and tags, you can ensure that you get the metric data you need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*1LQkaYnlOURT3ZmIje15CA.png" /></figure><p>Tracing is a huge topic in the software development world. In this article, I wanted to tell you about Jaeger, which is a very small part of it. Knowing the performance and behavior of your application will help us a lot in responding to possible errors.</p><p>Thanks for reading!</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2c6e07fa06c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/jaeger-with-opentelemetry-c2c6e07fa06c">Jaeger with OpenTelemetry</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithread Programming in .NET]]></title>
            <link>https://medium.com/@leventozturk/multithread-programming-in-net-d682cfd1f6bc?source=rss-203269f130d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d682cfd1f6bc</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Levent Ozturk]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 12:09:12 GMT</pubDate>
            <atom:updated>2023-09-24T14:34:35.603Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithread Programming in .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*e30sJ5KcWf6D4BqQ0Bh5Ww.jpeg" /></figure><p>Hi everyone,</p><p>In today’s article, I will try to give you basic information about multithread<em> </em>programming in .NET. The reason I say basic is that it will be up to you to use and elaborate this technology according to your own needs. I will explain how things work in synchronous-asynchronous programming and how methods can be used.</p><p>If you are ready, let’s get started!</p><p>First of all, we need to talk about what a “<strong>thread”</strong> is in .NET:</p><p><strong>Thread,</strong> is an independent unit of work inside an operating system process. Threads allow a program to execute multiple tasks or processes simultaneously. A process is the basic unit of execution launched at runtime of an application, and there can be multiple threads within a process.</p><p>And little bit sync and async programming:</p><p>In .net, there is a main thread that performs an operation. In sync programming, this main thread is blocked until the process is finished and is not used for other tasks.</p><p>In async programming, when the process is redirected to another phase, the thread is freed and can look at other processes.</p><h3>Waiter — Restaurant Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJqCvP6ch-WXiegjU6Yu6A.png" /></figure><p>One of the best examples to explain sync— async programming is the waiter and restaurant example:</p><p>An example of <em>sync programming</em> is when a waiter in a restaurant, after taking a customer’s order, waits for the chef to deliver the order to the customer. When we adapt this example to a<em>sync programming</em>, we explain that after the waiter has delivered the customer’s order to the chef, he is available to take other customers’ orders.</p><p><em>Sync programming</em> is an approach to programming in which operations run sequentially and step by step. One process is not completed until the next process is completed, and processes usually wait for each other. This can lead to wasted time waiting for a process to complete, especially when a large number of processes need to run simultaneously.</p><p><em>Async programming</em> is an approach to programming that allows a program to run its processes or tasks concurrently. The main goal of asynchronous programming is to start multiple processes at the same time and take care of other tasks while waiting for the results of these processes. This is especially important for increasing application performance and improving the user experience.</p><h4>Now, a few definitions:</h4><p><strong>Task:</strong> Taskis a return type. It is actually like a commitment. It means that the operation may not be completed immediately, but if it is completed, there will be a return.</p><p><strong>Async:</strong> If a method is marked as async, it is considered an async method and can wait for async operations using the await keyword in it.</p><p><strong>Await: </strong>The await specifies that the result of that asynchronous call is expected. Here, if the operation is incomplete, it will be waited for however long it takes.</p><h3>Multithread Programming</h3><blockquote>In fact, multithread programming is not directly related to sync-async programming. But I thought it would be useful as a preliminary information before moving on to multithread programming.</blockquote><p><em>Multithread programming</em> is a programming approach that allows a software application to run in multiple threads simultaneously. A thread is an independent execution unit within a process and enables the code of a program to execute in parallel. This can enhance an application’s performance, make more efficient use of multi-core processors, and handle some tasks asynchronously.</p><h4>In Wich Case?</h4><p>Looking at the definition of multithread programming, there is no reason not to use it in all cases. Especially in today’s multi-core and powerful computers, this option can be very attractive. But!</p><p>When doing multithread programming, the framework itself consumes more resources than it normally does when it divides the work you give it into parts and assigns a separate thread to each of them. You need to pay close attention to thread management, synchronization and possible problems such as race conditions. Otherwise, you will lose more than the performance you want to gain. We’ll talk about these later, but let’s talk about the most appropriate situations when you should choose multithread programming:</p><ol><li><strong>Long Running Processes:</strong> If your application has long-running processes (for example, reading or writing large files, complex math calculations), running these processes in parallel can increase application response time and improve performance.</li><li><strong>UI Response:</strong> When working with a graphical user interface (UI), it is important to run long-running processes in the background without affecting the user experience. This prevents the application from freezing or becoming unresponsive.</li><li><strong>Concurrent Processes:</strong> Multithread programming is important when you need to manage multiple processes at the same time (for example, when multiple users are online at the same time). You can parallelize by running each process in a separate thread.</li></ol><h4>TPL (Task Parallel Library)</h4><p>TPL is a library that provides a set of APIs and tools used for parallel programming, asynchronous operations and thread management. TPL’s main goal is to improve processing performance on multiprocessor systems and make parallel programming easier and more efficient.</p><p>Let’s take a look at a few methods inside this library:</p><p>Parallel.ForEach(): is a method that allows you to create parallel loops on collections or arrays. This method automatically manages parallel threads to process each element of the collection, helping you complete operations faster. <em>We need to be careful when using this method: The list we give to this method must be a </em><strong><em>voluminous list</em></strong><em>. In a low element count list, this method may run slower than a synchronous method.</em></p><pre><br>        List&lt;int&gt; numbers = Enumerable.Range(1, 1000).ToList();<br><br>        Parallel.ForEach(numbers, (number) =&gt;<br>        {<br>            Console.WriteLine($&quot;Number: {number}, Thread ID: {Task.CurrentId}&quot;);<br>        });<br><br>        Console.WriteLine(&quot;Done!&quot;);<br></pre><blockquote>In this example, we simply created a list of numbers from 1 to 1000 and divided each number in this list into parallel threads to speed up the process by increasing the number of cores used. In this example, each number can be defined as a job you need to do in a loop. By observing that each number is assigned a different thread id, we can see how the framework handles this internally.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0chryXGlgPLBGZzKYbESw.png" /><figcaption>You can see that there is no any order because of multithreading</figcaption></figure><p>As you can see in the example above, in parallel processing, the operations are not done sequentially. This is the most important problem we can face:</p><h4>Race Conditions</h4><blockquote>Race conditions, refer to situations encountered in multithreaded programming where multiple threads are trying to access the same resource or data at the same time. These situations occur when multiple threads are trying to modify or read the same data at the same time, with no guarantee of working in a specific order.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGX60D-kdoL9BQhs.png" /></figure><p>What we need to do to overcome this situation is to use the Interlocked.Add() method.</p><p>This method helps us to safely increment or decrement the value of a variable in multithreaded programming. This prevents multiple threads from interfering with the same process.</p><pre><br>        List&lt;int&gt; numbers = Enumerable.Range(1, 1000).ToList();<br>        long total = 0;<br><br>        Parallel.ForEach(numbers, (number) =&gt;<br>        {<br>            Console.WriteLine($&quot;Number: {number}, Thread ID: {Task.CurrentId}&quot;);<br>            Interlocked.Add(ref total, number);<br>        });<br><br>        Console.WriteLine($&quot;Total: {total}&quot;);</pre><blockquote>Here, the Interlocked.Add() method actually prevents threads from accessing the “total” variable at the same time. This prevents two threads from reading and incrementing total at the same time, thus preventing a race condition that could lead to incorrect results or data integrity issues. An important point that should not be overlooked here is the fact that “Interlocked.Add()” also comes at a significant cost.</blockquote><p>Another method:</p><p>Parallel.For(): I think there is no need for extra explanation for this method because the differences between Parallel.ForEach() and this method are the same as the differences between For and Foreach.</p><h4>The conclusion drawn so far</h4><p>So far, we’ve talked about how multithread programming works, when it makes sense to use it, and the problems that can arise. <br>When choosing this method, you should make sure that you really need this method and most importantly, you should perform performance testing. Because as I mentioned before, multithreaded programming can perform worse than normal in many cases. It is very important to write your code accordingly.</p><h4>A bit about performance</h4><p>We mentioned that due to race conditions, we need to lock the data used in multithreaded operations and ensure that other threads cannot operate on this data. We also mentioned that this operation is costly in terms of performance. Now let’s examine how we can use multithread programming with a little more performance.</p><p>Let’s look at the code first:</p><pre>List&lt;int&gt; numbers = Enumerable.Range(1, 1000).ToList();<br>int total = 0;<br><br>Parallel.ForEach(numbers, () =&gt; 0, (x, loop, subtotal) =&gt;<br>{<br>    subtotal += x;<br>    return subtotal;<br>},(y)=&gt; Interlocked.Add(ref total,y));</pre><blockquote>The parameters of Parallel.ForEach() are as follows:</blockquote><blockquote>*The first parameter is numbers, the collection to be processed.</blockquote><blockquote>*The second parameter is a function that represents an operation to be started before each thread starts. This operation uses each thread to calculate its local sum. This operation therefore starts with 0 when each thread starts its own calculation.</blockquote><blockquote>*The third parameter is a function that represents the process that handles each item. Each thread uses this function to calculate its local sum and returns.</blockquote><blockquote>*The fourth parameter is used to add the local sums of the threads to the main aggregation. This is done using the Interlocked.Add() method.<br>Threads have a local variable called subtotal when processing each item. This variable stores each thread’s local total.</blockquote><blockquote>Each thread calculates its local sum and returns the result, subtotal.</blockquote><blockquote>Using the Interlocked.Add() method, the local totals calculated by each thread are safely added to the main total variable.</blockquote><p>It may seem a bit complicated at first glance, but once you use it, you will understand its logic better.</p><p>We have come to the end of another article, and in this article I have tried to give you as much information as I can to give you an idea about multithread programming.<br>Thank you for reading this far. <br>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d682cfd1f6bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>