<?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 Sandun Pushpika on Medium]]></title>
        <description><![CDATA[Stories by Sandun Pushpika on Medium]]></description>
        <link>https://medium.com/@sandun.pushpika123?source=rss-86c92714cb73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*384zhSIXthC4cui_tmYV9Q.jpeg</url>
            <title>Stories by Sandun Pushpika on Medium</title>
            <link>https://medium.com/@sandun.pushpika123?source=rss-86c92714cb73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:26:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandun.pushpika123/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[SemaphoreSlim in .NET: Controlling Concurrency When Thousands of Requests Hit Your API]]></title>
            <link>https://medium.com/@sandun.pushpika123/semaphoreslim-in-net-controlling-concurrency-when-thousands-of-requests-hit-your-api-185483f9f936?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/185483f9f936</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[concurrency-control]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[semaphore]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 16:12:34 GMT</pubDate>
            <atom:updated>2026-09-14T16:12:34.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pq4nLm59eO00GLQn7AAuXQ.png" /></figure><p>Imagine this. It’s <strong>11:11</strong>.</p><p>Your e-commerce application has just started its biggest sale of the year. Thousands of customers are trying to place orders at almost the same time. Some are buying shoes. Some are buying phones. Some are buying laptops.</p><p>And behind the scenes, your application needs to process thousands of payments through an external payment provider such as Stripe.</p><p>Everything looks fine…</p><p>Until suddenly, your application starts making hundreds or thousands of requests to the payment provider at the same time.</p><p>And then you start seeing:</p><pre>429 Too Many Requests<br>Timeouts<br>Connection errors<br>Failed payments<br>Retries<br>Slow response times</pre><p>So the question becomes:</p><blockquote><strong><em>How do we handle a huge number of incoming requests without overwhelming an external API?</em></strong></blockquote><p>This is where <strong>SemaphoreSlim</strong> can become very useful.</p><h3>First, Let’s Understand the Problem</h3><p>Before talking about <strong>SemaphoreSlim</strong>, let&#39;s reproduce the problem.</p><p>I’m going to use <strong>LINQPad</strong> for the examples because it makes experimenting with concurrency really easy.</p><p>Let’s imagine that we have an e-commerce application where every order requires a payment.</p><p>For simplicity, we’re going to simulate the payment provider using Task.Delay().</p><p>Each payment will:</p><ul><li>Take somewhere between 1 and 5 seconds.</li><li>Sometimes fail.</li><li>Sometimes succeed.</li></ul><p>Here’s our PaymentService:</p><pre>// Simulate a single payment call.<br>// Each task waits for a random time from 1 to 5 seconds.<br>// Just like a real API response, we simulate random failures and success.<br>class PaymentService{<br>    public async Task MakePaymentAsync(int payment)<br>    {<br>        $&quot;Starting the payment {payment}&quot;.Dump();<br>        var rand = Random.Shared.Next(1000, 5000);<br>        await Task.Delay(rand);<br>        if (Random.Shared.Next(1, 5) % 2 == 0)<br>        {<br>            $&quot;Payment failed {payment}&quot;.Dump();<br>            return;<br>        }<br>        $&quot;Payment successful {payment}&quot;.Dump();<br>    }<br>}</pre><p>Now let’s simulate multiple customers trying to make payments at the same time:</p><pre>void Main()<br>{<br>    Task.WaitAll(GetConcurrentRequests().ToArray());<br>}<br><br>// Simulate multiple requests at the same time. Create 20 payments<br>IEnumerable&lt;Task&gt; GetConcurrentRequests()<br>{<br>    PaymentService paymentService = new PaymentService();<br>    for (int i = 0; i &lt; 20; i++)<br>    {<br>        yield return paymentService.MakePaymentAsync(<br>            Random.Shared.Next(2000, 5000));<br>    }<br>}</pre><p>Run it.</p><p>You will see something similar to:</p><pre>Starting the payment 2847<br>Starting the payment 3921<br>Starting the payment 4567<br>Starting the payment 2134<br>Starting the payment 4782<br>Starting the payment 3241<br>Starting the payment 2918<br>...</pre><p>Notice something interesting?</p><p><strong>All 20 payments start almost immediately.</strong></p><p>The fact that each payment contains:</p><pre>await Task.Delay(rand);</pre><p>doesn’t mean that the next payment waits for the previous one. Instead, the tasks are running concurrently.</p><p>So our application can effectively end up doing this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iv8NVu9RUX9eeOKun1oFSg.jpeg" /></figure><p>With 20 requests, this isn’t particularly scary.</p><p>But replace 20 with <strong>5,000 customers </strong>and things start getting interesting.</p><h3>“But Isn’t Concurrency a Good Thing?”</h3><p>Yes!</p><p>Concurrency itself is <strong>not the problem</strong>.</p><p>In fact, concurrency is one of the reasons asynchronous programming is so powerful.</p><p>The problem is <strong>uncontrolled concurrency</strong>.</p><p>Imagine the payment provider says:</p><blockquote><strong><em>“You can have a maximum of 5 payment operations running at the same time.”</em></strong></blockquote><p>But your application receives 5,000 requests.</p><p>Without any concurrency control, you might end up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBcyUxmllHXJ2NL6KFcgrA.png" /></figure><p>That’s a problem.</p><p>External APIs can have limits such as:</p><ul><li>Requests per second</li><li>Concurrent requests</li><li>Connection limits</li><li>Rate limits</li><li>Resource limits</li></ul><p>And these limits aren’t unique to payment providers.</p><p>The same problem can happen when calling:</p><ul><li>Payment APIs</li><li>Email providers</li><li>SMS providers</li><li>Shipping APIs</li><li>AI APIs</li><li>Internal microservices</li><li>Database-dependent services</li><li>File processing services</li></ul><p>So we need some kind of <strong>traffic controller</strong>.</p><h3>SemaphoreSlim</h3><p>Think of SemaphoreSlim like a room with a limited number of tickets. If we create new SemaphoreSlim(5), it means only <strong>5 tasks can enter the protected section at the same time</strong>. The first five payment requests take the five available permits and start processing. When a sixth request arrives, there are no permits left, so it has to wait. Once one of the first five payments finishes, it releases its permit, allowing the next waiting payment to continue. In simple terms, SemaphoreSlim acts like a <strong>traffic controller</strong>, controlling how many operations are allowed to run concurrently.</p><h3>Let’s Add It to Our Payment Service</h3><p>Our first change is surprisingly small.</p><pre>class PaymentService()<br>{<br>    private readonly SemaphoreSlim _semaphore = new(5);<br>    public async Task MakePaymentAsync(int payment)<br>    {<br>        await _semaphore.WaitAsync();<br>        try<br>        {<br>            $&quot;Starting the payment {payment}&quot;.Dump();<br>            var rand = Random.Shared.Next(1000, 5000);<br>            await Task.Delay(rand);<br>            if (Random.Shared.Next(1, 5) % 2 == 0)<br>            {<br>                $&quot;Payment failed {payment}&quot;.Dump();<br>                return;<br>            }<br>            $&quot;Payment successful {payment}&quot;.Dump();<br>        }<br>        finally<br>        {<br>            _semaphore.Release();<br>        }<br>    }<br>}</pre><p>That’s it.</p><p>We’ve just introduced a concurrency limit of <strong>5</strong>.</p><h3>What Actually Happens Now?</h3><p>Let’s say we have 20 payment requests. They all arrive almost simultaneously.</p><p>The first five requests reach:</p><pre>await _semaphore.WaitAsync();</pre><p>and successfully acquire a permit.</p><pre>Payment 1 → Permit 1<br>Payment 2 → Permit 2<br>Payment 3 → Permit 3<br>Payment 4 → Permit 4<br>Payment 5 → Permit 5</pre><p>Now:</p><pre>Available permits = 0</pre><p>Payment 6 reaches:</p><pre>await _semaphore.WaitAsync();</pre><p>There are no permits available.</p><p>So it waits.</p><p>Importantly, it <strong>waits asynchronously</strong>. It doesn’t need to block a thread while waiting.</p><p>Then Payment 1 finishes.</p><p>This code executes:</p><pre>_semaphore.Release();</pre><p>One permit becomes available.</p><p>Payment 6 can now continue.</p><p>So the flow becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFuF2TpkfSZG3PA0gS2c8A.png" /></figure><p>This is the key idea behind SemaphoreSlim.</p><p>Make sure to put everything within a try-catch block and add _semaphore.Release() within finally block, so that we can avoid permits being held forever.</p><h3>What About Slow Requests?</h3><p>Now let’s introduce another problem.</p><p>Imagine that the payment provider is having some issues. Some requests are taking a very long time. Our semaphore has only 5 permits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OumKeiRmIACUSIhmgLSCgQ.jpeg" /></figure><p>Eventually, we could have a large number of requests waiting for a permit.</p><p>SemaphoreSlim also allows us to specify a timeout.</p><p>Instead of:</p><pre>await _semaphore.WaitAsync();</pre><p>we can use:</p><pre>var acquired =<br>    await _semaphore.WaitAsync(<br>        TimeSpan.FromSeconds(3));</pre><p>Now we can check whether we actually acquired a permit:</p><pre>var acquired =<br>    await _semaphore.WaitAsync(<br>        TimeSpan.FromSeconds(3));<br>if (!acquired)<br>{<br>    &quot;Could not acquire semaphore within 3 seconds.&quot;<br>        .Dump();<br>     return;<br>}</pre><p>This gives us another useful behavior:</p><blockquote><strong><em>“Don’t wait forever for the external dependency to become available.”</em></strong></blockquote><h3>The Complete Example</h3><p>Putting everything together:</p><pre>class PaymentService()<br>{<br>    private readonly SemaphoreSlim _semaphore = new(5);<br>    public async Task MakePaymentAsync(int payment)<br>    {<br>        var acquired =<br>            await _semaphore.WaitAsync(<br>                TimeSpan.FromSeconds(3));<br>        if (!acquired)<br>        {<br>            $&quot;Payment {payment} timed out waiting.&quot;<br>                .Dump();<br>            return;<br>        }<br>        try<br>        {<br>            $&quot;Starting the payment {payment}&quot;.Dump();<br>            var rand = Random.Shared.Next(1000, 5000);<br>            await Task.Delay(rand);<br>            if (Random.Shared.Next(1, 5) % 2 == 0)<br>            {<br>                $&quot;Payment failed {payment}&quot;.Dump();<br>                return;<br>            }<br>            $&quot;Payment successful {payment}&quot;.Dump();<br>        }<br>        finally<br>        {<br>            &quot;Releasing semaphore permit&quot;.Dump();<br>            _semaphore.Release();<br>        }<br>    }<br>}</pre><p>And our test:</p><pre>void Main()<br>{<br>    Task.WaitAll(<br>        GetConcurrentRequests().ToArray());<br>}<br><br>IEnumerable&lt;Task&gt; GetConcurrentRequests()<br>{<br>    var paymentService = new PaymentService();<br>    for (int i = 0; i &lt; 20; i++)<br>    {<br>        yield return paymentService.MakePaymentAsync(<br>            Random.Shared.Next(2000, 5000));<br>    }<br>}</pre><p>Now our system behaves more like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Qx45w8MBoL3wa-6cvY5qQ.jpeg" /></figure><h3>One Important Clarification</h3><p>At this point, you might be thinking:</p><blockquote><em>“So </em><em>SemaphoreSlim solves API rate limiting?&quot;</em></blockquote><p><strong>Not exactly.</strong></p><p>SemaphoreSlim is primarily useful for <strong>limiting concurrency</strong>.</p><p>There’s an important difference between <strong>concurrent requests</strong> and <strong>requests per second.</strong></p><h3>Concurrent requests</h3><p>How many operations are running <strong>at the same time</strong>?</p><p>For example:</p><pre>Maximum 5 concurrent requests</pre><h3>Requests per second</h3><p>How many requests are allowed during a period of time?</p><p>For example:</p><pre>Maximum 100 requests per second</pre><p>These are different problems.</p><p>A SemaphoreSlim(5) can help you control, but it doesn’t automatically enforce:</p><pre>100 requests / second</pre><p>For actual rate limiting, you may need mechanisms such as:</p><ul><li>Token bucket</li><li>Leaky bucket</li><li>Fixed/sliding window rate limiting</li><li>.NET’s built-in rate-limiting APIs</li><li>A distributed rate limiter</li></ul><p>So always check the actual limits imposed by the external API you’re integrating with.</p><h3>One More Important Thing: Where Should the Semaphore Live?</h3><p>Consider this:</p><pre>class PaymentService<br>{<br>    private readonly SemaphoreSlim _semaphore = new(5);<br>}</pre><p>If your PaymentService is registered as a <strong>singleton</strong>, all callers share the same semaphore.</p><p>That’s often what you want when you’re trying to limit the concurrency of calls made by the application instance.</p><p>But if you create a new PaymentService for every request, you&#39;ll also create a new semaphore.</p><p>For example:</p><pre>Request 1<br>   │<br>   └── PaymentService → SemaphoreSlim(5)<br>Request 2<br>   │<br>   └── PaymentService → SemaphoreSlim(5)<br>Request 3<br>   │<br>   └── PaymentService → SemaphoreSlim(5)</pre><p>Now each service has its own semaphore. You haven’t really created a global limit of 5 anymore.</p><p>So <strong>the lifetime of the semaphore matters</strong>.</p><h3>The Mental Model</h3><p>If you remember only one thing from this article, remember this:</p><p>Think of SemaphoreSlim as a room with a limited number of <strong>keys</strong>.</p><pre>SemaphoreSlim(5)</pre><p>A task needs a key:</p><pre>await _semaphore.WaitAsync();</pre><p>It enters the room.</p><p>When it’s finished:</p><pre>_semaphore.Release();</pre><p>It returns the key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dw7MMBp3FQujlugjDm7loA.jpeg" /></figure><h3>The Pattern to Remember</h3><p>In real .NET applications, you’ll frequently see this pattern:</p><pre>await _semaphore.WaitAsync();<br>try<br>{<br>    // Limited-concurrency operation<br>}<br>finally<br>{<br>    _semaphore.Release();<br>}</pre><p>And when you need a timeout:</p><pre>var acquired =<br>    await _semaphore.WaitAsync(<br>        TimeSpan.FromSeconds(3));<br>if (!acquired)<br>{<br>    // Could not acquire a permit<br>    return;<br>}<br>try<br>{<br>    // Limited-concurrency operation<br>}<br>finally<br>{<br>    _semaphore.Release();<br>}</pre><h3>Final Takeaway</h3><p>When thousands of requests arrive at the same time, <strong>the solution isn’t always to process everything immediately</strong>.</p><p>Sometimes you need a traffic controller.</p><p>SemaphoreSlim gives you a simple way to say:</p><blockquote><strong><em>“I can accept as many requests as I want, but only N operations are allowed to execute this particular piece of work at the same time.”</em></strong></blockquote><p>For our payment example:</p><pre>new SemaphoreSlim(5)</pre><p>means:</p><blockquote><strong><em>“Only 5 payment operations can be inside this protected section concurrently.”</em></strong></blockquote><p>The remaining operations don’t disappear. They wait for a permit to become available. And that’s the core idea behind SemaphoreSlim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=185483f9f936" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Plugin Based Integration Architecture in ASP.NET Core]]></title>
            <link>https://medium.com/@sandun.pushpika123/designing-a-plugin-based-integration-architecture-in-asp-net-core-7c76bc286b1c?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c76bc286b1c</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 09:24:52 GMT</pubDate>
            <atom:updated>2026-03-07T15:24:40.572Z</atom:updated>
            <content:encoded><![CDATA[<p>When building modern SaaS platforms, integrating with external services is almost inevitable. Whether it’s <strong>Google Drive</strong>, <strong>OneDrive</strong>, or <strong>Dropbox</strong>, users expect seamless connectivity with the tools they already use.</p><p>At first, the implementation seems straightforward. You define an interface for drive operations and create separate implementations for each provider. Then, somewhere in your application logic, you determine which provider to execute:</p><pre>if (provider == &quot;GoogleDrive&quot;)<br>{<br>    // Google Drive logic<br>}<br>else if (provider == &quot;OneDrive&quot;)<br>{<br>    // OneDrive logic<br>}<br>else if (provider == &quot;Dropbox&quot;)<br>{<br>    // Dropbox logic<br>}</pre><p>It works, Until it doesn’t.<br>As more integrations are added, this approach quickly becomes problematic:</p><ul><li>The application becomes tightly coupled to specific providers.</li><li>Every new integration requires modifying existing logic.</li><li>Testing becomes harder.</li><li>The codebase becomes messy with conditional branching.</li><li>The system violates the Open/Closed Principle.</li></ul><p>This is where a <strong>plugin based integration architecture</strong> becomes essential.</p><p>In this article, we’ll explore how to design a clean, extensible, and production ready plugin architecture in ASP.NET Core that allows you to add new integrations such as Google Drive, OneDrive, or Dropbox without touching the core application logic.</p><h4>Okey… How can we do this?</h4><p>A plugin based integration architecture can be implemented in multiple ways, depending on the overall system design, extensibility requirements, and complexity of the integration layer.</p><p>In practice, the most common design approaches include:</p><ul><li><strong>Strategy Pattern</strong></li><li><strong>Factory Pattern</strong></li><li><strong>A combination of Strategy and Factory patterns</strong></li></ul><p>Each approach has its own trade offs.</p><p>In this article, I will focus specifically on implementing a <strong>Factory based plugin resolution approach in ASP.NET Core</strong>, while still leveraging interface driven design</p><h4>Let’s Dive In</h4><p>Imagine there is a feature in Application X, when a user uploads a file to the application X, it should automatically be uploaded to connected drive (GoogleDrive, DropBox, OneDrive,..etc). Currently, application X has support only for <strong>GoogleDrive</strong> and <strong>DropBox</strong>.</p><p>To achieve the goal, we should mainly have:</p><ul><li><strong>DriveFactory</strong></li><li><strong>IDriveService</strong></li><li><strong>GoogleDriveService</strong></li><li><strong>DropBoxService</strong></li></ul><p><strong>Basic DTOs and Type Enum:</strong></p><p>Before implementing the factory layer, we need to establish a small set of core abstractions that remain independent of any specific drive provider.</p><pre>public class DriveSettings<br>{<br>    public string FolderName { get; set; }<br>    public string AccessToken { get; set; }<br>}</pre><p><strong>DriveSettings</strong> represents the minimal configuration required to interact with a drive provider.</p><p>Instead of creating provider specific configuration classes inside the application core, we define a <strong>generic configuration object</strong> that can support any drive implementation.</p><pre>public class DriveResponse<br>{<br>    public bool Success { get; set; }<br>    public string Message { get; set; }<br>}</pre><p>When integrating multiple external systems, one common challenge is <strong>inconsistent response handling</strong>.</p><p>Each provider returns errors and success responses differently. To avoid leaking those inconsistencies into the application core, we define a standardized response wrapper.</p><pre>public enum DriveType<br>{<br>    GOOGLE_DRIVE,<br>    DROPBOX<br>}</pre><p>The <strong>DriveType</strong> enum provides a strongly typed mechanism for identifying which drive implementation should be resolved by the factory.</p><p><strong>IDriveService:</strong></p><pre>public interface IDriveService<br>{<br>    DriveType DriveType { get; }<br>    DriveResponse UploadFile(Stream file, DriveSettings driveSettings);<br>}</pre><p>The <strong>IDriveService</strong> abstraction enforces a consistent behavior across all drive implementations (Google Drive, Dropbox, OneDrive, etc.).</p><p>At the heart of a plugin based architecture lies a <strong>stable contract</strong> that all integrations must implement.</p><p><strong>GoogleDriveService:</strong></p><pre>public class GoogleDriveService : IDriveService<br>{<br>    public DriveType DriveType =&gt; DriveType.GOOGLE_DRIVE;<br>    public DriveResponse UploadFile(FileStream file, DriveSettings driveSettings)<br>    {<br>        // Google Drive Specific Implementation<br>    }<br>}</pre><p>This is where, the implementation for google drive uploading files, takes place.</p><p><strong>DropBoxService:</strong></p><pre>public class DropBoxService : IDriveService<br>{<br>    public DriveType DriveType =&gt; DriveType.DROPBOX;<br>    public DriveResponse UploadFile(FileStream file, DriveSettings driveSettings)<br>    {<br>        // DropBox Specific Implementation<br>    }<br>}</pre><p>This is the class for DropBox implementation.</p><p>Finally, the <strong>most important</strong> parts of plugin based architecture,</p><pre>public interface IDriveFactory<br>{<br>    IDriveService Resolve(DriveType driveType);<br>}<br><br>public class DriveFactory : IDriveFactory<br>{<br>    private readonly Dictionary&lt;DriveType, IDriveService&gt; _driveServices;<br><br>    public DriveFactory(IEnumerable&lt;IDriveService&gt; driveServices)<br>    {<br>        _driveServices = driveServices<br>            .ToDictionary(s =&gt; s.DriveType, s =&gt; s);<br>    }<br><br>    public IDriveService Resolve(DriveType driveType)<br>    {<br>        if (!_driveServices.TryGetValue(driveType, out var service))<br>            throw new NotSupportedException($&quot;Drive type &#39;{driveType}&#39; is not supported.&quot;);<br><br>        return service;<br>    }<br>}</pre><ul><li>The <strong>DriveFactory</strong> is responsible for giving you the correct drive service (Google Drive, Dropbox, etc.) based on the DriveType.</li><li>When the application starts, all implementations of IDriveService are injected into the factory.</li><li>The constructor stores them in a <strong>dictionary</strong>, mapping each DriveType to its corresponding service.</li><li>When Resolve() is called, the factory quickly looks up the correct service from the dictionary and returns it.</li><li>If no matching service exists, it throws an error.</li></ul><p>So instead of using if-else or switch statements, the factory cleanly and efficiently selects the correct drive implementation.</p><p>Final Step: Adding services in <strong>Program.cs.</strong></p><pre>// Program.cs<br><br>builder.Services.AddScoped&lt;IDriveService, GoogleDriveService&gt;();<br>builder.Services.AddScoped&lt;IDriveService, DropboxDriveService&gt;();<br>builder.Services.AddSingleton&lt;IDriveFactory, DriveFactory&gt;();</pre><h4>Example Usage:</h4><pre>app.MapPost(&quot;/upload&quot;, async (<br>        IFormFile file,<br>        DriveType driveType,<br>        IDriveFactory driveFactory,<br>        CancellationToken cancellationToken) =&gt;<br>    {<br>        if (file == null || file.Length == 0)<br>            return Results.BadRequest(&quot;File is required.&quot;);<br><br>        await using var stream = file.OpenReadStream();<br><br>        var driveService = driveFactory.Resolve(driveType);<br><br>        var response = driveService.UploadFile((FileStream)stream, driveSettings);<br><br>        return response.Success<br>            ? Results.Ok(response)<br>            : Results.BadRequest(response);<br>    })<br>    .WithOpenApi();</pre><p>In this example, a single endpoint is created to upload a file to a given drive. No need of creating separate if-else logics or separate endpoints for each drive.</p><p><strong>Architecture Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R092mmYB3kpUp2vU_wkbmg.png" /><figcaption>Plugin Architecture using Factory Pattern</figcaption></figure><h4>How to integrate a new Drive in the Future?</h4><p>Imagine you want to integrate OneDrive or any other drive to this application. When you alreay have the base architecture ready, all you have to do,</p><ol><li>Create <strong>OneDriveService </strong>which implements <strong>IDriveService.</strong></li><li>Add an enum member to <strong>DriveType</strong> enum.</li><li>Register the newly created service in <strong>Program.cs.</strong></li></ol><p>No need of any business logic change :-)</p><h4>What can be improved in this architecture?</h4><p>In very large systems, even enum based factories can become limiting because:</p><ul><li>Enums require modification when adding new providers.</li><li>Plugins may need to be loaded dynamically (via assemblies).</li></ul><p>At that level, you evolve toward:</p><ul><li>Metadata based resolution.</li><li>Attribute based mapping.</li><li>Reflection based plugin loading.</li><li>Modular architecture (separate integration assemblies).</li></ul><p>But for most SaaS systems, the DI-backed factory approach provides the perfect balance between simplicity and scalability.</p><p>See you all in another article! :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c76bc286b1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Text Searching with PostgreSQL Tutorial]]></title>
            <link>https://medium.com/@sandun.pushpika123/full-text-searching-with-postgresql-tutorial-6b8d7beafcac?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b8d7beafcac</guid>
            <category><![CDATA[full-text-search]]></category>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[fulltext-search]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 07:06:04 GMT</pubDate>
            <atom:updated>2025-03-29T07:06:04.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*YiHvzj6M_GAeD9Q3yIZzYA.png" /></figure><p>In today’s data-driven world, retrieving relevant information quickly is crucial, whether you’re building a search engine, filtering user-generated content, or enabling advanced queries in a database-driven application. PostgreSQL, a powerful open-source relational database, comes with built-in <strong>full-text search</strong> capabilities that allow you to perform fast and intelligent text-based searches without relying on third-party search engines like Elasticsearch.</p><p>Let’s dive into some main core fundamentals that should be known before implementing full-text search.</p><h3>Core components</h3><h4>1. Document</h4><p>A <strong>document</strong> is the fundamental unit of content that can be searched. It can consist of single column, multiple columns combined, dynamic content,<br>related table content.</p><h4>2. tsvector</h4><p>A <strong>tsvector</strong> represents searchable preprocessed content in PostgreSQL.</p><h4>3. tsquery</h4><p>Represents a search query that can efficiently search through tsvectors.</p><pre>SELECT to_tsvector(&#39;english&#39;, &#39;Example of postgresql sql full text searching&#39;) @@ to_tsquery(&#39;full-text &amp; search&#39;);</pre><h4>4. Lexemes</h4><p>Lexemes are the <strong>normalized</strong> forms of words that represent their core meaning. PostgreSQL applies several preprocessing steps to extract lexemes, ensuring more relevant search results.</p><p>These steps include: Converting to lowercase, removing stop words, stemming, handling special characters.</p><h3>Tutorial</h3><h4>Objective</h4><p>We need to create a <strong>PostgreSQL view</strong> that joins multiple related tables and enables <strong>full-text search (FTS)</strong> on the combined data. The goal is to check whether any records match a given search query efficiently.</p><p>Below is the database structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*uwKf3UkonW9EksriTB-y0A.png" /><figcaption>Database structure</figcaption></figure><h4>Step 1: Create tsvector columns in tables</h4><pre>ALTER TABLE product ADD COLUMN search_vector tsvector<br>GENERATED ALWAYS AS (<br>        to_tsvector(&#39;english&#39;,<br>            coalesce(name,&#39;&#39;) || &#39; &#39; ||<br>            coalesce(description,&#39;&#39;)<br>        )<br>) STORED;<br><br>CREATE INDEX search_vector_idx ON product USING GIN(search_vector);</pre><p>This SQL code enhances full-text search in the <strong>product</strong> table by adding a <strong>search_vector</strong> column, which is automatically generated using PostgreSQL&#39;s <strong>to_tsvector</strong> function. It converts the <strong>name</strong> and <strong>description</strong> fields into a searchable format, removing common words and improving search accuracy.</p><p>The <strong>GIN</strong> index on <strong>search_vector</strong> speeds up text-based queries, allowing efficient product searches without relying on slow <strong>LIKE</strong> queries. This setup ensures that any updates to <strong>name</strong> or <strong>description</strong> automatically reflect in the <strong>search_vector</strong>, making searches faster and more optimized.</p><blockquote>Note: <strong>coalesce()</strong> method in PostgreSQL is used for handling null values</blockquote><p>Do the same thing for other tables where we need to search for content. This means adding a search_vector column and creating a GIN index for those tables as well, so searches on those tables are faster and more efficient, just like we did for the product table.</p><pre>ALTER TABLE supplier ADD COLUMN search_vector tsvector<br>GENERATED ALWAYS AS (<br>        to_tsvector(&#39;english&#39;,<br>            coalesce(name,&#39;&#39;) || &#39; &#39; ||<br>            coalesce(address,&#39;&#39;)<br>        )<br>    ) STORED;<br><br>CREATE INDEX supplier_search_vector_idx ON supplier USING GIN(search_vector);<br><br>ALTER TABLE category ADD COLUMN search_vector tsvector<br>GENERATED ALWAYS AS (<br>        to_tsvector(&#39;english&#39;,<br>            coalesce(name,&#39;&#39;)<br>        )<br>    ) STORED;<br><br>CREATE INDEX category_search_vector_idx ON category USING GIN(search_vector);</pre><h4>Step 2: Create necessary view with search_vector columns</h4><pre>CREATE VIEW product_view AS<br>SELECT<br>    p.*,<br>    s.name AS supplier_name,<br>    c.name AS category,<br>    s.search_vector AS supplier_search_vector,<br>    c.search_vector AS category_search_vector<br>FROM product p<br>    LEFT JOIN supplier s ON p.supplier_id = s.id<br>    LEFT JOIN category c ON p.category_id = c.id</pre><h4>Step 3: Perform the searching</h4><p>Now you can perform the search query as below</p><pre>SELECT * FROM product_view<br>    WHERE search_vector @@ plainto_tsquery(&#39;english&#39;,&#39;Americano espresso with hot water&#39;) OR<br>          supplier_search_vector @@ plainto_tsquery(&#39;english&#39;,&#39;Americano espresso with hot water&#39;) OR<br>          category_search_vector @@ plainto_tsquery(&#39;english&#39;,&#39;Americano espresso with hot water&#39;)</pre><p>This SQL query is searching for records in the <strong>product_view</strong> table that match the phrase &quot;<strong><em>Americano espresso with hot water</em></strong>&quot; in any of the three search columns: <strong>search_vector</strong>, <strong>supplier_search_vector</strong>, or <strong>category_search_vector</strong>.</p><ul><li><strong>plainto_tsquery(&#39;english&#39;, &#39;Americano espresso with hot water&#39;)</strong>: This converts the search phrase into a format that PostgreSQL can use for efficient text searching, ignoring common words (like &quot;with&quot; or &quot;and&quot;).</li><li>The query checks if the phrase matches any of the three vectors (<strong>search_vector</strong>, <strong>supplier_search_vector</strong>, or <strong>category_search_vector</strong>), which are pre-calculated for fast searching in the <strong>product_view</strong> table.</li></ul><p>Additionally you can check the performance using,</p><pre>EXPLAIN ANALYZE SELECT * FROM product_view<br>    WHERE search_vector @@ plainto_tsquery(&#39;english&#39;,&#39;Americano espresso with hot water&#39;) OR<br>          supplier_search_vector @@ plainto_tsquery(&#39;english&#39;,&#39;Americano espresso with hot water&#39;) OR<br>          category_search_vector @@ plainto_tsquery(&#39;english&#39;,&#39;Americano espresso with hot water&#39;)</pre><h3>Conclusion</h3><ul><li>PostgreSQL provides better full-text searching approach with no additional infrastructure like Elasticsearch.</li><li>Better for small and medium projects as an alternative to Elasticsearch.</li><li>When dealing with complex data migration and transformation requirements, Elasticsearch typically necessitates the use of an ETL (Extract, Transform, Load) tool, which can result in significant costs. In contrast, PostgreSQL offers a more cost-effective solution for such use cases, making it a suitable alternative.</li><li>Compared to specialized search engines like Elasticsearch, PostgreSQL’s full-text search is not as feature-rich.</li><li>Although PostgreSQL performs well for basic searches, very complex queries with a high volume of text data may not be as fast as Elasticsearch or other specialized search engines.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b8d7beafcac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Scaling Techniques: Enhancing Performance and Efficiency]]></title>
            <link>https://medium.com/@sandun.pushpika123/database-scaling-techniques-enhancing-performance-and-efficiency-7702b03f2980?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/7702b03f2980</guid>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[database-scaling]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[advance-database]]></category>
            <category><![CDATA[database-performance]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 03:16:39 GMT</pubDate>
            <atom:updated>2025-02-10T03:16:39.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*TquiNOs52tZbOqCTj7pOaA.png" /></figure><p>As the application grows in size and complexity, managing the data used by the application becomes hard. There could be issues like slow speed of data retrieval, data lost and unavailability. Database scaling techniques help ensure optimal performance, availability, and reliability. This article explores various strategies to scale your database effectvely.</p><h4>What are the common techniques in database scaling?</h4><ul><li>Indexing</li><li>Sharding</li><li>Database caching</li><li>Replication</li><li>Vertical scaling</li></ul><p>Let’s dive into one by one!</p><h3>Indexing</h3><p>Indexing is one of the mostly used techniques to ensure query performance. An index is also a data structure that ensures the fast data retreival.</p><h4><strong>How to works</strong></h4><ul><li>Indexes are created on one or more columns in a table.</li><li>The database maintains an ordered data structure (e.g., B-Trees or Hash Indexes) to speed up searches.</li><li>When a query searches for indexed columns, the database quickly locates the relevant records without scanning the entire table.</li></ul><h4>Advantages</h4><ul><li>Speeds up search queries by reducing the number of scanned rows.</li><li>Improves efficiency in sorting and filtering operations.</li></ul><h4>Considerations</h4><ul><li>Indexes need additional storage.</li><li>Frequent updates and inserts can downgrade performance due to index maintenance.</li><li>Improper indexing strategies can lead to performance degradation instead of improvement.</li></ul><h3>Sharding</h3><p>Sharding is a technique that devides database into smaller pieces. These pieces are called <strong>shards. </strong>Each shard contains a subset of data. <br>Imagine you have an application that runs globally and one country contains millions of records. It’s difficult for one database to handle this amount of data. This is where sharding comes into play. Database can be divided into different shards according to the country. When a query is getting executed it is not searching for the whole database, instead it is searching only inside a specific shard.</p><h4>How It Works</h4><ul><li>A shard key determines how data is distributed across different database instances.</li><li>Queries are directed to the relevant shard, reducing the amount of data scanned. (Like the above example, it queries in the shard of a specific country)</li><li>Shards operate independently, allowing better parallel processing and scalability.</li></ul><h4>Advantages</h4><ul><li>Enables horizontal scaling by distributing load across multiple machines.</li><li>Improves performance by reducing query load per shard.</li><li>Allows handling massive datasets by distributing storage across multiple nodes.</li></ul><h4>Considerations</h4><ul><li>Complex to implement and manage.</li><li>Requires careful shard key selection to avoid data skew.</li></ul><h3>Database Caching</h3><p>Database caching is a process of storing frequently accessed data in memory to reduce the load on any database. It can be achievedthrough in-memory solutions like Redis, Memcached, or using built-in database caching mechanisms.</p><h4>How It Works</h4><ul><li>Frequently accessed queries are stored in a high-speed memory cache.</li><li>Subsequent requests for the same data retrieve results from the cache instead of querying the database.</li><li>Cache expiration and invalidation mechanisms ensure consistency.</li></ul><h4>Advantages</h4><ul><li>Reduces database load and query execution time.</li><li>Improves application responsiveness and scalability.</li></ul><h4>Considerations</h4><ul><li>Requires cache invalidation strategies to ensure data consistency.</li><li>Can introduce complexity in cache management.</li><li>Not all queries benefit from caching, especially those involving frequently updated data.</li></ul><h3>Replication</h3><p>Replication is the process of maintaining multiple copies of data, usually from a primary database to one or more secondary databases, for distributing read traffic for high availability.</p><h4>How It Works</h4><ul><li>Writes go to a primary database, while read requests go to secondary databases.</li><li>Replication can be synchronous, which ensures immediate consistency, or asynchronous, which allows some replication lag.</li><li>Load balancers distribute read requests across replicas.</li></ul><h4>Advantages</h4><ul><li>Improves availability and fault tolerance.</li><li>Supports load balancing in read-heavy applications.</li><li>Provides data redundancy for better disaster recovery capabilities.</li></ul><h4>Considerations</h4><ul><li>It increases the complexity of data synchronization.</li><li>It may have stale reads due to replication lag.</li><li>Writes remain bottlenecked on the primary database unless additional strategies, such as multi-primary replication, are also implemented.</li></ul><h3>Vertical Scaling</h3><p>Vertical scaling involves upgrading the CPU, RAM, or disk storage of a single database server to handle more workload.</p><h4>How It Works</h4><ul><li>More CPU cores, memory, or faster disk storage is added to increase performance.</li><li>The very same database instance keeps running, but with bigger capacity.</li><li>Usually, minimal changes are required from database applications.</li></ul><h4>Advantages</h4><ul><li>Much easier to put into practice, compared to horizontal scaling.</li><li>Useful for an application with low to moderate scaling requirements.</li><li>No additional complexity of database partitioning or sharding.</li></ul><h4>Considerations</h4><ul><li>Limited by hardware constraints, there is a ceiling for scaling up.</li><li>Over time, much more expensive in comparison with horizontal scaling.</li><li>Only one single point of failure, if the database server crashes.</li></ul><h3>Conclusion</h3><p>The choice of a particular scaling technique is determined by the workload, volume, and scalability requirements of the application. Most often, these techniques go hand in hand to achieve thorough performance and efficiency. Indexing, caching, replication, and sharding are just a few examples that ensure a database will remain responsive and reliable at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7702b03f2980" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Flow Simplified]]></title>
            <link>https://medium.com/@sandun.pushpika123/kubernetes-flow-simplified-02aa4ba18088?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/02aa4ba18088</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops-tool]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 09:01:22 GMT</pubDate>
            <atom:updated>2025-01-12T09:01:22.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*QZv1Wx2lEY8QPtuJ_8pRQg.png" /></figure><p>Kubernetes is widely being used as an open-source container orchestration platform. Kubernets, also referred as K8s, is designed to automate deployment, scaling and management of containerized applications. It’s important to understand how kubernetes works under the hood.</p><p>In this article, Let’s learn how an HTTP request reaches your application running in a K8s pod. Before we dive into that, let’s walk through basic concepts in K8s.</p><h3>Basic concepts</h3><ul><li><strong>Containers: </strong>Container is a software package with the essential tools to run your application. This will be running inside the Pod.</li><li><strong>Pods: </strong>Smallest deployable compute object in K8s.</li><li><strong>Nodes: </strong>A node is a virtual or physical worker machine. Pods are running inside these nodes.</li><li><strong>Clusters : </strong>A cluster can be defined as a group of nodes.</li><li><strong>Kubelet: </strong>An agent that runs inside the pods to ensure that the containers are running as expected.</li><li><strong>API Server</strong>: Facilitates communication with the cluster.</li><li><strong>Scheduler</strong>: Assigns pods to nodes.</li><li><strong>Controller Manager</strong>: Maintains the cluster’s desired state.</li><li><strong>etcd</strong>: Stores all cluster data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J24rWbX7yNg6vOwFje2_Mw.jpeg" /><figcaption>Figure 01: Cluster architecture from kubernetes.io</figcaption></figure><p>Apart from the above concepts, It’s better you have a clear understanding about <strong>Service</strong>, <strong>Ingress</strong> and <strong>Load Balancer</strong>.</p><h4>What do you think a Service is?</h4><p>A <strong>service</strong> is like a middleman that helps other applications or users to talk to your containers. There are different types of services in K8s.</p><ol><li><strong>ClusterIP:</strong> Used for internal communication because this is only accessible within the cluster.</li><li><strong>NodePort: </strong>Exposes the application to the outside world using a port on each node.</li><li><strong>LoadBalancer: </strong>Works with cloud providers to expose the service to be managed by a load balancer provided by cloud provider.</li><li><strong>ExternalName:</strong> Maps the Service to an external resource, like a database hosted elsewhere.</li></ol><h4>What is an Ingress in K8s?</h4><p>An <strong>Ingress</strong> acts like a receptionist at an office. It’s the gateway that helps outside visitors (users) find the right office room (your application) inside the building (Kubernetes cluster).</p><p>In technical terms, It routes the users to relevant services depending on the rules you set.</p><h4>What does the load balancer in K8s do?</h4><p><strong>Load balancer</strong> is like a traffic cop. It makes sure that the traffic will be handled by distributing to all available nodes.</p><p>Alright, It’s time to dive into the most important part!!</p><h3>How does an HTTP request reach your application?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Fz_ll8eVjeCfFms_YB5HgQ.png" /><figcaption>Figure 02: How HTTP requests flow to Pods.</figcaption></figure><p>Above diagram shows how HTTP requests go into the pod where your application’s container is running. Request goes through few components. Let’s discuss about them.</p><h4>Step 1:</h4><p>User enters your application’s url (<strong><em>www.example.com</em></strong><em>) </em>In a web browser.</p><h4>Step 2:</h4><p>Once the user has entered the URL, first it reaches the DNS server and it get the IP address of the URL provided. And then the request navigates to the Load Balancer with that IP address.</p><blockquote><strong>Note:</strong> Reaching to the load balancer only occurs if there is load balancer implemented.</blockquote><blockquote>Instead of a load balancer, A proxy server also can be implemented.</blockquote><h4>Step 3:</h4><p>Load balancer is the entry point to the cluster and is responsible many tasks like handling the traffic, navigating the request to the relevant ingress controller. Once the request is arrived to the <strong>load balancer</strong>. It passes the request to the relevant<strong> ingress controller</strong>.</p><h4>Step 4:</h4><p>Once the request has reached the Ingress Controller, Ingress Controller decides which ingress rules to apply to the specific request. And finally the request will be forwarded to the relevant pods.</p><p>Above steps will give you a basic idea of how HTTP requests make it to the pod.</p><h3>Why should we use kubernetes?</h3><p>Kubernetes gives us many features that will make deployment, scalability and management of the application easier. Here are few features K8s has,</p><ul><li><strong>Container Orchestration</strong>: Automating deployment and management.</li><li><strong>Scaling</strong>: Automatically adjusting application resources.</li><li><strong>Self-Healing</strong>: Restarting failed containers.</li><li><strong>Load Balancing</strong>: Efficiently distributing traffic.</li><li><strong>Declarative Configuration</strong>: Using YAML/JSON files for application management.</li></ul><h3>When not to use K8s?</h3><p>While Kubernetes (K8s) is a powerful tool for managing containers, it’s not always the right choice for every situation. Here are scenarios when you might not want to use Kubernetes:</p><ul><li><strong>Small Apps</strong>: For simple or single-container apps, Kubernetes is overkill.</li><li><strong>No Scaling Needs</strong>: If your app won’t need to handle traffic or grow, simpler tools are better.</li><li><strong>Limited Resources</strong>: Kubernetes needs a lot of memory, CPU, and storage — skip it if resources are tight.</li><li><strong>Short-Term Projects</strong>: Setting up Kubernetes takes time, so it’s not ideal for temporary apps or demos.</li><li><strong>No DevOps Expertise</strong>: If your team isn’t familiar with managing infrastructure, Kubernetes can be hard to handle.</li><li><strong>Non-Containerized Apps</strong>: If your app doesn’t run in containers, Kubernetes isn’t the right fit.</li></ul><h3>Conclusion</h3><p>In Kubernetes, a request from a user typically reaches a<strong> Load balancer</strong> and then to <strong>Ingress Controller</strong>, which applies ingress rules and routes it to the appropriate <strong>Pod</strong> running the application. This flow ensures high availability and efficient load balancing.</p><p>Kubernetes has significant advantages, such as scalability, self-healing, and support for different environments. However, it comes with complexity, resource requirements, and a deep learning curve. For large, dynamic applications, Kubernetes is invaluable, but for simpler setups, it might be not worthy and a cost. Choose Kubernetes based on your project’s needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02aa4ba18088" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RabbitMQ With ASP.NET Core in Action]]></title>
            <link>https://blog.devops.dev/rabbitmq-with-asp-net-core-in-action-3c0f71ad67fb?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c0f71ad67fb</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 11:16:55 GMT</pubDate>
            <atom:updated>2024-07-30T15:55:27.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jra2Ybcf0o7xpRvhwC5Tg.png" /></figure><h3>What is RabbitMQ?</h3><p>RabbitMQ is an efficient, open-source message broker that facilitates communication between services and applications. RabbitMQ is widely been used in micro services for communications.</p><p>It is easy to deploy and supports various messaging protocols, including AMQP (Advanced Message Queuing Protocol) and MQTT (MQ Telemetry Transport), among others like STOMP (Simple (or Streaming) Text Oriented Messaging Protocol).</p><p>RabbitMQ excels in providing dynamic and robust routing capabilities, making it adaptable to the evolving needs of users and services. It uses message queues to handle messages in a FIFO (First In, First Out) order, which simplifies process scaling.</p><p>In this article, we will be discussing how RabbitMQ can be used in ASP.NET Core micro services. Before we dive in to development, Let’s look at some basic concepts in RabbitMQ to gain a better understanding of what we are going to do.</p><h3>Fundamental Concepts in RabbitMQ</h3><h4>Producers/Publishers</h4><p>Producers or the Publishers can be considered as the message sender. Let’s say that you write a letter to your friend. And you give the letter to the post office or postbox to send to your friend. In this scenario, you are the <strong>producer</strong><em>.</em></p><h4>Task</h4><p>Task is the message or the data that the producer sends. In the above scenario, letter is the <strong>task</strong><em>.</em></p><h4>Queue</h4><p>Queue is one of the most important components in RabbitMQ. It is the one that holds your data before giving to the receiver. It is like the post box that keeps all the mails. Queue works in <strong>FIFO(First in First out) </strong>way. The first message goes out first.</p><h4>Binding</h4><p>Binding is the <strong>connection </strong>between producers and exchanges.</p><h4>Consumer</h4><p>Consumer is the one that waits for the message from RabbitMQ. This is the receiver.</p><h4>Exchange</h4><p>Exchange is the one that is responsible for routing the message. Exchanges determine how the messages are routed to the queues. Exchange gets the message from producers.</p><h4>Routing Key</h4><p>This is a string used by exchange to determine the destination queue.</p><p>Let’s now dive into the development on implementing RabbitMQ with ASP.NET Core</p><h3>Ohh Yeahh!! Let’s code!</h3><ol><li>First create a solution. And inside in it, create two WebAPI projects. One project as a API gateway(RabbitMqSample) and the other one as a micro service(SampleMicroservice).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*7QOkaWbrYkCXlpzVqpkm6A.png" /><figcaption>Two Projects</figcaption></figure><p>2. Next, Create a <em>Services </em>Folder under <strong>RabbitMqSample</strong> Web Api project.</p><p>3. Create a <strong>MessagePublisherService.cs</strong> and <strong>IMessagePublisher.cs</strong> under <strong>Services</strong> folder.</p><p><strong>IMessagePublisher</strong> interface and <strong>MessagePublisherService</strong> class.</p><pre>namespace RabbitMqSample.Services.Interfaces;<br><br>public interface IMessagePublisher<br>{<br>    Task SendMessage&lt;T&gt;(T message);<br>}</pre><pre>using System.Text;<br>using System.Text.Json;<br>using RabbitMQ.Client;<br>using RabbitMqSample.Services.Interfaces;<br><br>namespace RabbitMqSample.Services;<br><br>public class MessagePublisherService : IMessagePublisher<br>{<br>    private IConnection _connection;<br>    private IChannel _channel;<br><br>    public MessagePublisherService()<br>    {<br>        InitReceiveService().Wait();<br>    }<br><br>    private async Task InitReceiveService()<br>    {<br>        var factory = new ConnectionFactory()<br>        {<br>            HostName = &quot;localhost&quot;<br>        };<br>        _connection = await factory.CreateConnectionAsync();<br>        _channel = await _connection.CreateChannelAsync();<br>    }<br>    <br>    public async Task SendMessage&lt;T&gt;(T message)<br>    {<br><br>        var json = JsonSerializer.Serialize(message);<br>        var body = Encoding.UTF8.GetBytes(json);<br><br>        await _channel.ExchangeDeclareAsync(&quot;test-exchange&quot;,ExchangeType.Direct);<br>        await _channel.QueueDeclareAsync(&quot;test&quot;,exclusive:false);<br>        await _channel.QueueBindAsync(&quot;test&quot;, &quot;test-exchange&quot;,&quot;test&quot;);<br>        <br>        await _channel.BasicPublishAsync(&quot;test-exchange&quot;, &quot;test&quot;,body);<br>        Console.WriteLine(&quot;Message published!&quot;);<br>    }<br>}</pre><p>Let’s try to understand what is inside <strong>MessagePublisherService</strong> class.</p><p>Creating connection and channel:</p><pre>private async Task InitReceiveService()<br>{<br>  var factory = new ConnectionFactory()<br>  {<br>    HostName = &quot;localhost&quot;<br>  };<br>  _connection = await factory.CreateConnectionAsync();<br>  _channel = await _connection.CreateChannelAsync();<br>}</pre><p>To create a connection to the RabbitMQ server. We have to create an instance of <strong>ConnectionFactory</strong> class providing required parameters. That requires <strong>HostName </strong>which, in our case, is “localhost”.</p><p>If default passwords are changed in RabbitMQ, you should provide <strong>Username </strong>and<strong> Password</strong> as well. Since I use default username and passwords, i don’t need to provide username and password.</p><p>And next, after we created a connection using <strong>ConnectionFactory</strong>, we can open up a channel using the <strong>_connection</strong>.</p><p>After successfully creating a connection and a channel. We can start producing message as below.</p><p>Sending messages:</p><pre>    public async Task SendMessage&lt;T&gt;(T message)<br>    {<br><br>        var json = JsonSerializer.Serialize(message);<br>        var body = Encoding.UTF8.GetBytes(json);<br><br>        await _channel.ExchangeDeclareAsync(&quot;test-exchange&quot;,ExchangeType.Direct);<br>        await _channel.QueueDeclareAsync(&quot;test&quot;,exclusive:false);<br>        await _channel.QueueBindAsync(&quot;test&quot;, &quot;test-exchange&quot;,&quot;test&quot;);<br>        <br>        await _channel.BasicPublishAsync(&quot;test-exchange&quot;, &quot;test&quot;,body);<br>        Console.WriteLine(&quot;Message published!&quot;);<br>    }</pre><p>We cannot directly send the objects. We have to serialize into a json string format and get the bytes array.</p><p>Using the <strong>_channel</strong> we created earlier, an Exchange is declared with the type <strong>Exchange.Direct. </strong>We must provide a title to the exchange to identify the exchange that is declared.</p><p>And then we can declare a Queue using <strong>_channel.QueueDeclareAsync</strong>. A name/title for the queue is required. In our case, “<strong>test</strong>” is the title. And exclusive is set to be False.</p><blockquote>Note: if exclusive is set to true, consumer and the publisher will not be able to connect to the queue at the same time</blockquote><p>And then, we can bind the queue and the exchange together using <strong>_channel.QueueBindAsync</strong>. We have to provide the necessary parameters for binding them. <strong>queue name(‘test’), exchange name(‘test-exchange’) and a routing key(‘test’).</strong></p><p>Finally, publish the message using <strong>BasicPublishAsync. </strong>Few parameters are provide here. <strong>“test-exchange”</strong> — exchange name, <strong>“test”</strong> — routing key, <strong>body </strong>— the message.</p><p>4. Let’s now add these services as scoped services in <strong>Program.cs. </strong>And create an endpoint for sending a message.</p><pre>using Microsoft.AspNetCore.Mvc;<br>using RabbitMqSample.Services;<br>using RabbitMqSample.Services.Interfaces;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddSingleton&lt;IMessagePublisher, MessagePublisherService&gt;();<br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/&quot;, () =&gt; &quot;Hello World!&quot;);<br><br>app.MapGet(&quot;/send-message&quot;, async ([FromServices] IMessagePublisher publisher) =&gt;<br>{<br>    var randomObj = new<br>    {<br>        name = &quot;hello&quot;,<br>        age = 20<br>    };<br><br>    await publisher.SendMessage(randomObj);<br>    return &quot;Done&quot;;<br>});<br><br>app.Run();</pre><p>5. Next, create a consumer in the <strong>SampleMicroservice</strong> project. For that I have created a service folder under the project. And inside the service folder, I have created<strong> ReceiveMessageService.cs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*kytNlHZOMo6PeCvDtP1CEQ.png" /></figure><p>6. Let’s have a look at <strong>ReceiveMessageService.cs</strong></p><pre>public class ReceiveMessagesService : BackgroundService<br>{<br>}</pre><p><strong>ReceiveMessageService</strong> class is inherited by <strong>BackgroundService</strong> because it is going to be running in the background because the messages should be captured once they arrive.</p><pre>public class ReceiveMessagesService : BackgroundService<br>{<br>    private IConnection _connection;<br>    private IChannel _channel;<br><br>    public ReceiveMessagesService()<br>    {<br>        InitReceiveService().Wait();<br>    }<br><br>    private async Task InitReceiveService()<br>    {<br>        var factory = new ConnectionFactory()<br>        {<br>            HostName = &quot;localhost&quot;<br>        };<br>        _connection = await factory.CreateConnectionAsync();<br>        _channel = await _connection.CreateChannelAsync();<br>    }<br>    <br>    private async Task ReceiveMessage()<br>    {<br>        await _channel.QueueDeclareAsync(&quot;test&quot;, exclusive:false);<br><br>        var consumer = new EventingBasicConsumer(_channel);<br>        consumer.Received += (model, ea) =&gt;<br>        {<br>            var body = ea.Body.ToArray();<br>            var message = Encoding.UTF8.GetString(body);<br>            Console.WriteLine($&quot;Received: {message}&quot;);<br>        };<br><br>        await _channel.BasicConsumeAsync(consumer,&quot;test&quot;,true, &quot;TestConsume&quot;,false,false);<br>        Console.WriteLine(&quot;Consumed&quot;);<br>    }<br><br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        await ReceiveMessage();<br>    }<br><br>    public override void Dispose()<br>    {<br>        _channel.CloseAsync().Wait();<br>        _connection.CloseAsync().Wait();<br>        base.Dispose();<br>    }<br>}</pre><p><strong>InitReceiveService() </strong>is for intializing a connection to RabbitMQ and creating channel as described above.</p><p>Inside <strong>ReceiveMessage() </strong>method, It creates a connection to the <strong>“test”</strong> queue that we defined the producer.</p><p>Consuming messages:</p><pre>var consumer = new EventingBasicConsumer(_channel);<br>consumer.Received += (model, ea) =&gt;<br>{<br>  var body = ea.Body.ToArray();<br>  var message = Encoding.UTF8.GetString(body);<br>  Console.WriteLine($&quot;Received: {message}&quot;);<br>};<br><br>await _channel.BasicConsumeAsync(consumer,&quot;test&quot;,true, &quot;TestConsume&quot;,false,false);</pre><p>The above code creates a consumer and starts listening if there is any message from the <strong>“test”</strong> queue.</p><p>7. Once the service is created. We can register it as a hosted service in <strong>Program.cs</strong>.</p><pre>using SampleMicroservice.Services;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddHostedService&lt;ReceiveMessagesService&gt;();<br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/&quot;, () =&gt; &quot;Hi&quot;);<br><br>app.Run();</pre><p>8. All we have left is, setting up the RabbitMQ server. We will set it up on docker.</p><p>9. Create a <strong>docker-compose.yml</strong> file under the solution like below.</p><pre>services:<br>  rabbitmq:<br>    container_name: &quot;rabbitmq&quot;<br>    image: &quot;rabbitmq:3.8-management&quot;<br>    ports:<br>      - &quot;5672:5672&quot;<br>      - &quot;15672:15672&quot;</pre><p>10. Now run <strong>docker compose up. </strong>Once it is finished, run <strong>RabbitMqSample</strong> and <strong>SampleMicroservice</strong>. And try sending a message.</p><h3>Conclusion</h3><ul><li>RabbitMQ and ASP.NET Core integration provides a powerful and flexible messaging solution for modern web applications.</li><li>By leveraging RabbitMQ’s robust routing capabilities and ASP.NET Core’s versatile framework, developers can build scalable and reliable systems that handle complex messaging scenarios efficiently.</li><li>we’ve explored the fundamental concepts of RabbitMQ, and demonstrated how to set up RabbitMQ within an ASP.NET Core application.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c0f71ad67fb" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/rabbitmq-with-asp-net-core-in-action-3c0f71ad67fb">RabbitMQ With ASP.NET Core in Action</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSL Simplified]]></title>
            <link>https://medium.com/@sandun.pushpika123/ssl-simplified-9af7140fbc58?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/9af7140fbc58</guid>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[under-the-hood]]></category>
            <category><![CDATA[ssl-certificate-providers]]></category>
            <category><![CDATA[sslsecurity]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 06:29:38 GMT</pubDate>
            <atom:updated>2024-04-13T06:29:38.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is SSL…?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*x0EbzLc0jProZ6puoXZX8Q.png" /></figure><p>SSL, or Secure Sockets Layer, is like a really cool thing used for safe internet stuff. It’s like, um, a secret code that makes sure nobody can steal your info when you’re online.</p><h3>How Does SSL Do Its Thing?</h3><p>So, when you go to a safe website, you see HTTPS in the address. That means it’s secure, kinda like wearing a virtual mask. The server gives your browser a secret code (it’s called a key) to unlock the door. Then, both sides can talk in secret without anyone listening in.</p><p>Throughout this whole dance, SSL is the superhero protecting you by doing three things:</p><ul><li><strong>Authentication</strong>: Certificates from fancy Certificate Authorities check if websites are for real or not. It’s like a secret handshake to know you’re in the right place.</li><li><strong>Encryption</strong>: Imagine your data is a secret message. SSL turns it into gibberish so sneaky people can’t figure it out.</li><li><strong>Data Integrity</strong>: SSL adds locks and seals to your data so it can’t be changed on the way to its destination.</li></ul><h3>How Exactly Does SSL Handshake Work Under The Hood? (A little deep dive)</h3><p>SSL uses different cryptographic techniques and protocols. Lets see a diagram representation of a simplified handshake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*MpJ1InXvRuSSrxAy66kG3w.png" /><figcaption>SSL Handshake</figcaption></figure><ol><li>The handshake begins with a client sending a “Hello” message to the server. The message includes all the information such as SSL/TLS version the client supports, the cryptographic algorithms the client can use and all the other parameters for initiating a handshake.</li><li>The server recieves the client’s hello message. And then the server responds back a “Hello” message along with its SSL/TLS version, SSL certificate and its cryptographic algorithms.</li><li>Once the client gets the SSL certificate, Client starts verifying its authenticity using CA’s public key which is installed on the client’s side. The client generates a “Pre-master secret” and encrypts it with server’s public key obtained from the certificate. And the encrypted pre-master secret is sent back to the server.</li><li>The server decrypts the encrypted pre-master secret with its private key. And the server responds with a finished message.</li><li>Client decrypts server’s finished message to verify its integrity of the handshake. If successful, Client sends a finished message back to the server.</li><li>Finally, SSL handhsake is completed with a secure connection between the client and server.</li></ol><p>Throughout the SSL handshake process, several cryptographic techniques, including asymmetric and symmetric encryption, digital signatures, and hash functions, are employed to secure the communication channel and authenticate the parties involved. This ensures that sensitive information exchanged between the client and server remains protected from eavesdropping, tampering, and impersonation attacks.</p><h3>Wait!! What was the SSL certificate used in the handshake?</h3><p>In the process of handshake, SSL certificate can be considered as one of the most important components. It is a digital document that binds a public key to an entity such as a website or a web app. SSL certificate contains,</p><ul><li><strong>Public Key:</strong> used in the client’s side to encrypt data</li><li><strong>Server Identity Information: </strong>server’s domain, organization and etc.</li><li><strong>CA (Certification Authority) Signature: </strong>the certificate is digitally signed by Certification Authority ensuring the clients can trust the certificate.</li><li><strong>Validity Period: </strong>specifies the duration that the certification can be used.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*MNpmQJIyXFFMs8JPAlVYRA.png" /><figcaption>A valid certificate can be ssen like this</figcaption></figure><h3>Benefits of SSL</h3><p>SSL is totally awesome and everyone should use it! Some good things are:</p><ul><li><strong>Super Security</strong>: It stops bad guys from snooping on your internet business, keeping your secrets safe.</li><li><strong>Trust and Love</strong>: People like you more when your website is safe, so you get more hugs and smiles from your visitors.</li><li><strong>Google Likes You</strong>: Being secure makes Google happy and they might give you a gold star in their search results!</li><li><strong>Staying Out of Trouble</strong>: Following the rules like GDPR and PCI DSS is easy when you’re using SSL.</li></ul><h4>Challenges and Stuff</h4><p>SSL isn’t perfect, but it’s still pretty rad. Here are some things to watch out for:</p><ul><li><strong>Certificate Confusion</strong>: It’s hard to keep track of all the secret certificates, so sometimes things can go wrong if you’re not careful.</li><li><strong>Speed Bumps</strong>: All the secret stuff in SSL can slow things down, especially on old computers.</li><li><strong>Don’t Mix It Up</strong>: Using secure and non-secure things together can make your website explode, so be careful.</li></ul><p>So, SSL is like a superhero cape for your internet adventures. Keep using it to stay safe out there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9af7140fbc58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth Simplified]]></title>
            <link>https://medium.com/@sandun.pushpika123/oauth-simplified-988ec1e839a5?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/988ec1e839a5</guid>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[oauth-token]]></category>
            <category><![CDATA[oauth2-provider]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 08:38:33 GMT</pubDate>
            <atom:updated>2023-08-07T08:38:33.741Z</atom:updated>
            <content:encoded><![CDATA[<p>OAuth is a commonly used way to permit access to protected data without sharing the passwords. OAuth stands for <strong>Open Authentication. </strong>And considered as a protocol. This is widely being used by large companies such as Google, Facebook, Microsoft, etc.</p><p>OAuth protocol provides a way for resource owners to share resources stored in a server to a client. (Could be another application). For an example, a person has a folder in his google drive which contains some specific documents. And those documents should be automatically retrieved by another application like LinkedIn. The person doesn’t not have to provide his google drive credentials. Instead, LinkedIn provides a way to connect to google drive through OAuth. And LinkedIn will only be granted to selected services.</p><h3>Grant Types in OAuth 2.0</h3><p>The Authorization framework provides several grant types to grant the access to a resource.</p><ul><li><strong>Authorization Code Grant </strong>: This is widely used in many applications. Authorization server returns a single-use code which can be exchanged for access tokens from authorization server.</li><li><strong>Implicit Grant</strong> : In this flow, the authorization server returns the Access Token as a parameter in the callback URI or as a response to a form post.</li><li><strong>Authorization Code with Proof Key Code Exchange(PKCE)</strong> : This is similar to Authorization Code Grant, but with few features to make it more secure.</li><li><strong>Resource Owner Credentials Grant Type</strong> : This grant type shares resource owners’ credentials with the Authorization server. This grant is only recommended with clients that are completed trusted.</li><li><strong>Client Credentials Grant Type</strong> : Used for non-interactive applications such as automated processes, microservices, etc. In this grant type, the application is authenticated by using Client Id and Client Secret.</li><li><strong>Device Authorization Flow : </strong>This is used to give access to apps on input-constrained devices, such as smart TVs.</li></ul><p>Here in this article, Authorization Code Grant type will be briefly explained.</p><h3>Authorization Code Grant Type</h3><p>Authorization Code Grant Type is one of the grant types that is widely being used by REST APIs. There are several steps to perform to grant access through Authorization Code Flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIV0WldpxsgnQi0yfnWXZw.jpeg" /><figcaption>Authorization Code Flow</figcaption></figure><ol><li><strong>First Step :-</strong> Generate Authorization URL with necessary query parameters and redirecting user to the Auth URL.</li></ol><p>An example of authorization URL :-</p><pre>https://authorization-server.com/authorize?<br> response_type=code<br> &amp;client_id=GnKMnwErW0mOTBu0DKSPq9_4<br> &amp;redirect_uri=https://www.oauth.com/playground/authorization-code.html<br> &amp;scope=photo+offline_access<br> &amp;state=9X96X2nVXBO3vxEg</pre><blockquote>Note :- Auth Url is different according to the OAuth provider. Usually, Auth Url might look like http://{OAuth Domain}/oauth/authorize</blockquote><p>When user clicks on login, user should be redirected to auth url. This URL will prompt a consent screen for user to grant permissions. There are few parameters to consider in the above URL,</p><ul><li><strong>client_Id (Required)</strong> <strong>:- </strong>This is provided by the OAuth Service Provider when creating an application in their consoles.</li><li><strong>redirect_uri (Required) :- </strong>This is the url that the requested <strong>code</strong> will be sent along with other additional info like <strong>State</strong>.</li><li><strong>scope (Required) :-</strong> This parameter is for defining the permissions to be granted by the application.</li><li><strong>state (Optional) :-</strong> This is an optional parameter. This could be used for verification purposes.</li><li><strong>response_type (Required) :-</strong> Response type is set to code because the response to the redirection url will be a <strong>code</strong> in the Authorization Code Flow.</li></ul><p>2. <strong>Second Step :-</strong> Exchange the code for an access token.</p><p>In the first step, user will get a consent screen to grant access. If user clicks on access, A <strong>code </strong>will be sent to the redirection url which will be used to get access tokens. API is responsible for sending a post request with the code to the OAuth server to get the tokens.</p><pre>POST https://authorization-server.com/token<br><br>grant_type=authorization_code<br>&amp;client_id=yMM3DjjpDiGOp1_AY_tuj9p3<br>&amp;client_secret=dl1jdBQqKSmCykAdG-sxjZVJLgWr47PwMg0c1hxTK21Zb7Hk<br>&amp;redirect_uri=https://www.oauth.com/playground/authorization-code.html<br>&amp;code=npQYWdkyK6S_GG3C2OHFE8kNOv4QZRcF-D4US71GwPrUXIjs</pre><blockquote>Note that the client’s credentials are included in the POST body in this example. Other authorization servers may require that the credentials are sent as a HTTP Basic Authentication header.</blockquote><p>In the above POST request, there are few new parameters for you to understand.</p><ul><li><strong>grant_type :- </strong>This is for defining the grant type used to obtain tokens.</li><li><strong>client_id :-</strong> This is provided by the OAuth service provider.</li><li><strong>client_secret :-</strong> This is also provided by the OAuth service provider.</li><li><strong>redirection_uri :-</strong> Redirection URL to redirect if any error occurs.</li><li><strong>code :-</strong> The code received in the first step. This is a single-used code with a limited life time.</li></ul><p>This POST request will return a JSON response with the tokens in JWT format and along with its life times. An example of the response is shown below.</p><pre>{<br>  &quot;token_type&quot;: &quot;Bearer&quot;,<br>  &quot;expires_in&quot;: 86400,<br>  &quot;access_token&quot;: &quot;fu8Rs5fE1QL2qvcdXJkrYJ7IujmjCfqEvqcz3FUiVDQau2O5DzGi6z4fCMtYCQAfSPOmyFHB&quot;,<br>  &quot;scope&quot;: &quot;photo offline_access&quot;,<br>  &quot;refresh_token&quot;: &quot;oWvvLjUKw7iq1ScfeFYfcEJB&quot;<br>}</pre><blockquote>Note that some OAuth providers are not directly providing refresh token. In such cases, Refresh token will be able to be requested in the auth url. Carefully read the documentation of the OAuth provider, Before integrating.</blockquote><p>3. <strong>Third Step :-</strong> Store tokens in a safer way and access services with tokens.</p><p>Generally, tokens provided by OAuth providers are JWT tokens. Those tokens contain scopes and other user information. All the tokens should be safely stored because anyone with the tokens can access any service scoped in the token.</p><p>In the next article, Let’s talk on using OAuth with google services.</p><h3>Conclusion</h3><ul><li>OAuth is used as a way for sharing resources without sharing credentials.</li><li>OAuth shares JWT tokens to give access.</li><li>Authorization Code Grant Type is the widely used grant type to permit access to resources.</li><li>Auth Code Flow can be implemented in few simple steps like creating an auth url, get a code by the auth url and exchange the code to obtains tokens.</li><li>Remember that the flow might be slightly different in different OAuth providers.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=988ec1e839a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture Simplified]]></title>
            <link>https://medium.com/@sandun.pushpika123/clean-architecture-simplified-e3e11907e762?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3e11907e762</guid>
            <category><![CDATA[onionarchitecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Sun, 07 Aug 2022 19:13:43 GMT</pubDate>
            <atom:updated>2022-08-07T19:19:12.348Z</atom:updated>
            <content:encoded><![CDATA[<p>When building an application, it is important to make it maintainable, testable and scalable. There are different architectures that developers can follow to build maintainable systems.</p><p>Larger applications might have tons of files, too many lines of code and many connections between tons of classes. What if the system need to change a line in a class? It is going to affect all the other classes that inherited the changed class. Developers might have to give a huge effort to figure out the places to be changed. So it is important to organize the files. The developers use separations of concerns through the folders or the layers. This is basically one of the things that an architecture helps to achieve.</p><h3><strong>What is Clean Architecture?</strong></h3><p>Clean Architecture is an architecture that uses <strong>Dependency Inversion Principle</strong>(DIP) and <strong>Domain Driven Design</strong>(DDD). Clean Architecture divides application into <strong>layers</strong>. This is how clean this achieves separations of concerns principle. This architecture is also known as Onion architecture and Hexagonal Architecture, followed by Ports and Adapters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDJJTy3TsA6pOBceFVs6kA.jpeg" /><figcaption>Onion View Of Clean Architecture</figcaption></figure><p>Compare the above view as an onion. Upper peels are depending on lower peels. The same theory applies in clean architecture. That is why it is also called as Onion Architecture. Lower layers are not depending on upper layer but upper layers are. As you can see in the above image, Domain layer, also known as application core does not depend on any other layer. And infrastructure depends on application core. User interface layer depends on infrastructure layer and application core layer.</p><h4>Application Core</h4><p>This layer consists of classes that are not depending on Infrastructure or UI layer, like models, entities, interfaces, handlers, etc. The types that could be inside application core layer,</p><ul><li>Interfaces</li><li>Domain Services (Services which do not depend on other layers)</li><li>Entities (Business model classes)</li><li>DTOs</li><li>Aggregates (Groups of Entities)</li><li>Custom Exceptions</li><li>Domain Events and Handlers</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*BEVlaBm1g0ccChDzSvWDVw.png" /><figcaption>Eg Of Application Core File Structure</figcaption></figure><h4>Infrastructure</h4><p>This layer plays a big role when dealing with outside services and outside APIs. This basically includes implementations of the interfaces defined in application core (Like Data access implementations and Business logic implementations). Infrastructure layer always has a reference to Application Core layer. What is included in infrastructure?</p><ul><li>Classes like DbContext</li><li>Data access implementations</li><li>Services like File logger, Smtp Services, etc. (Any service dealing with outside APIs are also belonging to here)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*PoHUWOUv4nf70C6qxriEuQ.png" /><figcaption>Eg of Infrastructure layer’s file structure</figcaption></figure><h4>User Interface</h4><p>This is the entrance to the application and this layer directly and indirectly depends on all other layers in the application. This layer consists of things which the client side deals with. This layer is the most upper layer in the architecture and this is usually a dependent of infrastructure. But no direct call to infrastructure layer. Types included in UI layer is as shown below,</p><ul><li>View Models</li><li>Controllers</li><li>Custom Filters</li><li>Custom Middleware</li><li>Startup</li><li>Views</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*C512-Vxsxw1a7_bEPXwsAQ.png" /><figcaption>Eg of UI layer’s file structure</figcaption></figure><h3>Conclusion</h3><p>As you have learned from the above explanations, Clean architecture can be used to build highly maintainable and testable systems because of the fact that how it is structured. Clean Architecture achieves separation of concerns principle through layers(Core, Infrastructure and UI). Because of the way it is structured and connected, it is easy to perform testing on the project. Maintaining the project gets easier because the project is well structured in a way that changes can not affect other classes. Clean Architecture has become one of the widely used architectures among the developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3e11907e762" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Importance Of Dependency Injection]]></title>
            <link>https://medium.com/@sandun.pushpika123/dependency-injection-f79530568dfa?source=rss-86c92714cb73------2</link>
            <guid isPermaLink="false">https://medium.com/p/f79530568dfa</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[dependencies]]></category>
            <dc:creator><![CDATA[Sandun Pushpika]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 05:57:35 GMT</pubDate>
            <atom:updated>2022-07-19T15:21:00.029Z</atom:updated>
            <content:encoded><![CDATA[<p>Dependency injection is a widely used design pattern in large scaled applications. Dependency Injection is the mechanism of injecting the object or function to the one that it depends on, leading to loosely coupled programs.</p><h3><strong>Why do we need dependency injection?</strong></h3><p>In an application, there could be many classes that directly inherit other classes. See below for an example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxCPIafXSGvESvwV0hTE0g.jpeg" /><figcaption>This is an example of tightly coupled program.</figcaption></figure><p>The above is an example for a<strong> tightly coupled</strong> program. A large scale application is usually built by many developers. If class B and class A are built by two developers. And if class B is not declared before class A, It gives a compile time error because class A directly depends on class B.</p><p>we use dependency injection to get rid of these issues. It helps to create <strong>loosely coupled</strong> programs.</p><h3><strong>How it works?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5t12_DA55g2uiTmuQgp1Q.jpeg" /><figcaption>Inverted Dependency Graph</figcaption></figure><p>As shown in the above graph, Class A does not directly inherit class B. Class A has a reference to interface B. And class B has the implementation of interface B. So whatever changed in class B does not affect on class A. Even though the developer of Class B has not even created Class B, It doesn’t affect for compile time errors. This is called a <strong>loosely coupled</strong> program.</p><p>How application chooses which implementation is to be injected, is occurred in an IoC container. It is the container where we define which service is injected when a specific interface reference is called. See below for better understanding,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2OOiNhZ0oWLI5XDre-EJA.jpeg" /></figure><p><strong><em>Conclusion:</em></strong></p><p>Dependency injection helps to build maintainable, reusable and extensible code. It mostly uses abstraction. No module depends on the other modules. All the modules depend on abstraction.</p><p>We will talk about IoC (Inversion of Control) in the next article.</p><p>Thanks for reading! Please feel free to comment your questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f79530568dfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>