<?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 Sreyanth on Medium]]></title>
        <description><![CDATA[Stories by Sreyanth on Medium]]></description>
        <link>https://medium.com/@bvsreyanth?source=rss-93ad39721849------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r9PHaS8b0YCrOnMu9tZz9g.png</url>
            <title>Stories by Sreyanth on Medium</title>
            <link>https://medium.com/@bvsreyanth?source=rss-93ad39721849------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:50:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bvsreyanth/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[Mastering EF Core Performance Everything I Learned About Writing Faster Queries ]]></title>
            <link>https://bvsreyanth.medium.com/mastering-ef-core-performance-everything-i-learned-about-writing-faster-queries-5c936ef4d8f6?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c936ef4d8f6</guid>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[aspdotnet]]></category>
            <category><![CDATA[dot-net-developers]]></category>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 12:18:08 GMT</pubDate>
            <atom:updated>2026-07-21T12:18:30.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9wPyhgABTCFeTfU9pIM_w.jpeg" /></figure><p>Hi Everyone 👋</p><p>Performance isn’t something you think about on day one of a project.</p><p>When you’re building features, it’s easy to write a LINQ query, see it return the correct data, and move on. EF Core makes data access so simple that it’s easy to forget what’s happening behind the scenes. But as your application grows, so does your data. A query that feels instant with a few hundred records can become painfully slow when it has to process millions.</p><p>I learned this while exploring EF Core performance. I assumed the database was the bottleneck, but I quickly realized that many performance issues come from the way we write our queries. Fetching unnecessary columns, loading entire object graphs, tracking entities we never update, or accidentally generating dozens of SQL queries can all slow an application down.</p><p>This article is a collection of everything I learned while studying EF Core performance. Instead of presenting random tips, I’ll explain why each optimization matters, when you should use it, and when you shouldn’t.</p><h3><strong>Understanding How EF Core Executes a Query</strong></h3><p>Before optimizing anything, it’s important to understand what actually happens when you write a LINQ query.</p><p>When you write:</p><pre>var customers = await db.Customers<br>    .Where(c =&gt; c.IsActive)<br>    .ToListAsync();</pre><p><strong><em>EF Core doesn’t execute the query immediately.</em></strong></p><p><em>Instead, it builds an </em><strong><em>expression tree</em></strong><em> representing your LINQ query.</em></p><p><em>That expression tree is translated into SQL.</em></p><p><em>The SQL is sent to your database.</em></p><p><em>The database executes the SQL.</em></p><p><em>The results are returned.</em></p><p><em>If tracking is enabled, every entity is stored inside the Change Tracker.</em></p><p>Understanding this pipeline helped me realize something important:</p><blockquote><strong><em>The faster your SQL executes and the less data you transfer, the faster your application becomes.</em></strong></blockquote><h3><strong>Measure Before You Optimize</strong></h3><ol><li>One of the biggest lessons I learned is to never optimize blindly.</li></ol><p>2. Sometimes a query feels slow because of network latency.</p><p>3. Sometimes the issue is missing indexes.</p><p>4. Sometimes it’s JSON serialization instead of SQL.</p><p>Before changing code, measure it.</p><p>Useful tools include:</p><ul><li>EF Core query logging</li><li>ToQueryString()</li><li>SQL Server Execution Plans</li><li>Application Insights</li><li>Azure Monitor</li></ul><p>Performance improvements backed by measurements are always better than assumptions.</p><h4>Projection Is Usually Better Than Include</h4><p>This was probably the biggest performance lesson I learned.</p><p>Suppose you’re building an orders page that displays:</p><ul><li>Order ID</li><li>Customer Name</li><li>Total Amount</li></ul><p>Many developers write:</p><pre>var orders = await db.Orders<br>    .Include(o =&gt; o.Customer)<br>    .Include(o =&gt; o.Items)<br>    .ToListAsync();</pre><p>This loads far more data than the UI actually needs.</p><p>A better approach is projection.</p><pre>var orders = await db.Orders<br>    .Select(o =&gt; new OrderDto(<br>        o.Id,<br>        o.Customer.Name,<br>        o.Items.Sum(i =&gt; i.Price)))<br>    .AsNoTracking()<br>    .ToListAsync();</pre><p>Why it’s faster:</p><ul><li>Only required columns are selected.</li><li>Smaller network payload.</li><li>Less memory usage.</li><li>No unnecessary change tracking.</li></ul><p>Whenever I’m building APIs, projection has become my default choice.</p><h3>Use AsNoTracking for Read-Only Queries</h3><p>By default, EF Core tracks every entity it loads.</p><p>Tracking allows EF Core to detect changes before calling SaveChanges().</p><p>That’s useful for updates.</p><p>It isn’t useful when you’re only reading data.</p><pre>var products = await db.Products<br>    .AsNoTracking()<br>    .ToListAsync();</pre><p>Using AsNoTracking():</p><ul><li>Reduces memory usage.</li><li>Improves query performance.</li><li>Avoids unnecessary change tracking.</li></ul><p>A simple rule I now follow:</p><blockquote><em>If I won’t modify the entity, I use </em><em>AsNoTracking().</em></blockquote><h3>Deferred Execution Matters</h3><p>LINQ queries aren’t executed immediately.</p><p>They execute only when they’re materialized using methods like:</p><ul><li>ToListAsync()</li><li>FirstAsync()</li><li>SingleAsync()</li></ul><p>That means you should keep building your query before executing it.</p><p>Bad:</p><pre>var orders = await db.Orders.ToListAsync();</pre><pre>var activeOrders = orders =&gt; o.Status == OrderStatus.Active);</pre><p>Good:</p><pre>var activeOrders = await db.Orders<br>    .Where(o =&gt; o.Status == OrderStatus.Active)<br>    .ToListAsync();</pre><p>The second version lets SQL Server perform the filtering.</p><h3>Avoid the N+1 Problem</h3><p>The N+1 problem is one of the easiest ways to slow down an application.</p><p>Imagine loading 1000 orders at a time.</p><p>Then inside a loop:</p><pre>foreach (var order in orders)<br>{<br>    Console.WriteLine(order.Customer.Name);<br>}</pre><p>If lazy loading is enabled, EF Core may execute one additional query for every customer.</p><p>1000 orders can become 1001 SQL queries.</p><p>A projection solves this.</p><pre>var orders = await db.Orders<br>    .Select(o =&gt; new<br>    {<br>        o.Id,<br>        CustomerName = o.Customer.Name<br>    })<br>    .ToListAsync();</pre><p>One query is almost always better than thousands.</p><h3>Choose the Right Loading Strategy</h3><p>EF Core offers three ways to load related data.</p><h3>Eager Loading</h3><p>Uses Include().</p><p>Everything is loaded immediately.</p><p>Good when you truly need related entities.</p><h3>Explicit Loading</h3><p>Loads related data only when requested.</p><p>Useful when only some requests need the navigation property.</p><h3>Lazy Loading</h3><p>Automatically loads related entities when accessed.</p><p>Although convenient, it can easily cause N+1 problems.</p><p>For high-performance applications, I prefer projection or eager loading instead.</p><h3>Use Split Queries for Large Includes</h3><p>Loading multiple collections with Include() can generate huge SQL joins.</p><pre>var orders = await db.Orders<br>    .Include(o =&gt; o.Items)<br>    .Include(o =&gt; o.Payments)<br>    .AsSplitQuery()<br>    .ToListAsync();</pre><p>Instead of one enormous join, EF Core executes multiple smaller queries.</p><p>This avoids row duplication and can significantly reduce memory usage.</p><h3>Pagination Is Essential</h3><p>Returning thousands of rows is rarely a good idea.</p><p>Instead:</p><pre>const int pageSize = 50;</pre><pre>var page = await db.Orders<br>    .OrderByDescending(o =&gt; o.CreatedAt)<br>    .Skip((pageNumber - 1) * pageSize)<br>    .Take(pageSize)<br>    .ToListAsync();</pre><p>Even better, use keyset pagination when possible.</p><p>Instead of:</p><pre>.Skip(100000)</pre><p>Use:</p><pre>.Where(o =&gt; o.Id &gt; lastId)<br>.Take(50)</pre><p>Keyset pagination scales much better for large datasets.</p><h3>Indexes Matter More Than EF Core</h3><p>EF Core generates SQL.</p><p>The database decides how to execute it.</p><p>Indexes determine whether SQL Server performs a seek or a scan.</p><p>Creating indexes on frequently filtered columns can dramatically improve performance.</p><pre>modelBuilder.Entity&lt;Order&gt;()<br>    .HasIndex(o =&gt; new<br>    {<br>        o.CustomerId,<br>        o.Status<br>    });</pre><p>Always index columns used in:</p><ul><li>WHERE</li><li>JOIN</li><li>ORDER BY</li></ul><h3>Use Any Instead of Count</h3><p>If you only need to know whether something exists:</p><p>Don’t write:</p><pre>await db.Users.CountAsync(u =&gt; u.Email == email) &gt; 0;</pre><p>Write:</p><pre>await db.Users.AnyAsync(u =&gt; u.Email == email);</pre><p>Any() usually translates into an efficient SQL EXISTS.</p><h3>Bulk Updates Without Loading Entities</h3><p>EF Core introduced ExecuteUpdate().</p><p>Instead of:</p><ul><li>loading entities,</li><li>modifying them,</li><li>calling SaveChanges(),</li></ul><p>let SQL perform the update.</p><pre>await db.Orders<br>    .Where(o =&gt; o.Status == OrderStatus.Pending)<br>    .ExecuteUpdateAsync(s =&gt;<br>        s.SetProperty(<br>            o =&gt; o.Status,<br>            OrderStatus.Expired));</pre><p>One SQL statement.</p><p>No tracking.</p><p>No materialization.</p><h3>Batch SaveChanges</h3><p>Avoid this:</p><pre>foreach (var customer in customers)<br>{<br>    db.Customers.Add(customer);<br>    await db.SaveChangesAsync();<br>}</pre><p>Instead:</p><pre>db.Customers.AddRange(customers);</pre><pre>await db.SaveChangesAsync();</pre><p>Fewer database round trips mean better performance.</p><h3>DbContext Pooling</h3><p>Creating a DbContext has a cost.</p><p>ASP.NET Core supports pooling.</p><pre>builder.Services.AddDbContextPool&lt;AppDbContext&gt;(options =&gt;<br>{<br>    options.UseSqlServer(connectionString);<br>});</pre><p>Pooling reduces allocations and improves throughput.</p><h3>Compiled Queries</h3><p>Hot paths that execute thousands of times can benefit from compiled queries.</p><pre>static readonly Func&lt;AppDbContext, int, OrderDto?&gt; GetOrder =<br>    EF.CompileQuery(<br>        (AppDbContext db, int id) =&gt;<br>            db.Orders<br>                .AsNoTracking()<br>                .Where(o =&gt; o.Id == id)<br>                .Select(o =&gt; new OrderDto(<br>                    o.Id,<br>                    o.Customer.Name,<br>                    o.Items.Sum(i =&gt; i.Price)))<br>                .FirstOrDefault());</pre><p>Compiled queries skip repeated query compilation.</p><p>They’re useful for frequently executed queries.</p><h3>Cache Data That Rarely Changes</h3><p>Not every request needs to hit the database.</p><p>Examples:</p><ul><li>Countries</li><li>Categories</li><li>Roles</li><li>Currencies</li><li>Configuration</li></ul><p>These are great candidates for caching.</p><p>Using <strong>IMemoryCache</strong>, <strong>Redis</strong>, or <strong>hybrid caching</strong> can dramatically reduce database load and improve application performance.</p><h3>Inspect the SQL EF Core Generates</h3><p>EF Core hides SQL, but you shouldn’t ignore it.</p><p>You can inspect generated SQL using:</p><pre>var sql = query.ToQueryString();</pre><p>Reading generated SQL helped me understand:</p><ul><li>unnecessary joins,</li><li>duplicated columns,</li><li>missing filters,</li><li>inefficient queries.</li></ul><h3>Pass Cancellation Tokens</h3><p>ASP.NET Core already provides a cancellation token.</p><p>Use it.</p><pre>await db.Orders<br>    .ToListAsync(cancellationToken);</pre><p>If the client disconnects, the database operation can stop instead of consuming resources unnecessarily.</p><h3>Common Performance Mistakes</h3><p>Some mistakes appeared repeatedly while I was learning EF Core.</p><ul><li>Calling ToList() too early.</li><li>Returning entire entities from APIs.</li><li>Using Include() everywhere.</li><li>Forgetting AsNoTracking().</li><li>Missing indexes.</li><li>Calling SaveChanges() inside loops.</li><li>Using Count() when Any() is enough.</li><li>Never measuring performance.</li></ul><p>Avoiding these habits often produces bigger improvements than micro-optimizations.</p><h3>My Biggest Takeaways</h3><p>If I had to summarize everything I learned into a few rules, they would be these:</p><ul><li>Fetch only the data you actually need.</li><li>Let the database filter, sort, and aggregate.</li><li>Use projection by default.</li><li>Track entities only when you intend to update them.</li><li>Always paginate large result sets.</li><li>Create indexes based on real query patterns.</li><li>Measure before optimizing.</li><li>Read the SQL that EF Core generates.</li><li>Optimize only after understanding the bottleneck.</li></ul><p>Performance isn’t about finding one magical setting that makes every query fast.</p><p>It’s about consistently making small, informed decisions that reduce unnecessary work.</p><p>EF Core is capable of building high-performance applications, but it won’t do it automatically. Understanding how it translates LINQ into SQL and how the database executes those queries gives you the knowledge to write applications that remain fast as your data grows.</p><p>The biggest lesson I learned is that performance isn’t a final step before deployment it’s a habit. Every query you write is an opportunity to fetch less, transfer less, allocate less, and let the database do what it’s designed to do. Build those habits early, and your applications will scale much more gracefully.</p><h3>Thank You for Reading!</h3><p>Thank you for taking the time to read this guide. I hope the concepts, examples, and practical tips help you write faster and more efficient EF Core applications.</p><p>Happy coding, and may all your queries be fast! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c936ef4d8f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JavaScript Promises]]></title>
            <link>https://bvsreyanth.medium.com/understanding-javascript-promises-032434e2be75?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/032434e2be75</guid>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 12:53:33 GMT</pubDate>
            <atom:updated>2025-08-29T12:53:33.761Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever ordered food online, you’ve already understood the concept of a <strong>JavaScript Promise</strong> — you just didn’t know it yet.</p><p>But before we get there, let’s talk about something every developer stumbles into at first…</p><p>😵 What Is Callback Hell?</p><p>In JavaScript, we often use <strong>callbacks</strong> to handle tasks that take time — like fetching data or reading files. A callback is just a function passed into another function to run later.</p><p>But when you have <strong>many tasks</strong>, each depending on the previous one, you end up with <strong>nested callbacks</strong> like this</p><pre>getUser(userId, function(user) {<br>  getPosts(user.id, function(posts) {<br>    getComments(posts[0].id, function(comments) {<br>      console.log(comments);<br>    });<br>  });<br>});</pre><p>This is called <strong>callback hell</strong> — the code becomes hard to read, hard to maintain, and easy to mess up.</p><p><strong>🧹 Enter Promises — The Cleanup Crew</strong></p><p>A <strong>Promise</strong> is like saying:</p><blockquote><em>“I don’t have the result yet, but I’ll let you know when I do.”</em></blockquote><p>It helps you write cleaner code by <strong>flattening</strong> those nested callbacks</p><pre>getUser(userId)<br>  .then(user =&gt; getPosts(user.id))<br>  .then(posts =&gt; getComments(posts[0].id))<br>  .then(comments =&gt; console.log(comments))<br>  .catch(error =&gt; console.error(error));</pre><p>Much better, right?</p><h3>🍔 The Food Delivery Analogy</h3><p>Imagine you’re hungry and you order a burger online.</p><ul><li>You place the order → this is like <strong>calling an API</strong>.</li><li>The app says “Order placed” → this is the <strong>Promise</strong>.</li><li>You don’t have the burger yet — the Promise is still <strong>pending</strong>.</li><li>After some time, the burger arrives → the Promise is <strong>fulfilled</strong>.</li><li>Or maybe the restaurant cancels → the Promise is <strong>rejected</strong>.</li></ul><pre>const burgerOrder = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    const isAvailable = true;<br>    if (isAvailable) {<br>      resolve(&quot;Burger delivered!&quot;);<br>    } else {<br>      reject(&quot;Restaurant canceled the order.&quot;);<br>    }<br>  }, 2000);<br>});<br><br>burgerOrder<br>  .then(result =&gt; console.log(result))<br>  .catch(error =&gt; console.log(error));</pre><p>Async/await — The Smoother Way</p><p>Async/await is just <strong>syntactic sugar</strong> over Promises. It makes asynchronous code look like synchronous code</p><pre>async function getBurger() {<br>  try {<br>    const result = await burgerOrder;<br>    console.log(result);<br>  } catch (error) {<br>    console.log(error);<br>  }<br>}</pre><h3>When Should You Use Each?</h3><h4>Use Promises when</h4><ul><li>You need to run multiple tasks <strong>in parallel</strong> (Promise.all)</li><li>You’re chaining simple tasks</li><li>You’re working in older codebases</li></ul><h4><strong>Use async/await when:</strong></h4><ul><li>You want cleaner, more readable code</li><li>You’re doing <strong>sequential</strong> tasks</li><li>You prefer try/catch for error handling</li></ul><h4><strong>Conclusion</strong></h4><p>Promises and async/await are both tools to handle asynchronous operations. They help you avoid callback hell and write code that’s easier to read, debug, and maintain.</p><h4>Further Reading</h4><p>If you’d like to dive deeper into how Promises work under the hood — including states, chaining, and advanced patterns — check out the official <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN documentation on Promise</a>. It’s a goldmine for both beginners and seasoned developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=032434e2be75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Made Simple: How It Transforms App Development and Deployment]]></title>
            <link>https://bvsreyanth.medium.com/what-is-docker-e86afab9312f?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/e86afab9312f</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 18:44:54 GMT</pubDate>
            <atom:updated>2025-01-13T05:46:22.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*er3Kh7DjWDD9aRBC7Xc_Sw.jpeg" /></figure><h3>What is Docker?</h3><p>Docker is a tool that simplifies building, sharing, and running software in a consistent environment. Think of it as a container for your app, <strong>bundling everything it needs like code, libraries, and settings</strong> so it can run the same way on any computer with Docker installed.</p><p>Imagine you’re moving houses. Instead of packing each item individually, you pack everything into neatly organized boxes. These boxes can be moved anywhere, and their contents remain intact. Docker does the same for <strong>applications</strong>, ensuring they work the <strong>same way</strong>, no matter where they’re deployed.</p><h3>Why Use Docker?</h3><p>Key Benefits:</p><ul><li><strong>Portability</strong>: Applications run the same, regardless of where they are deployed.</li><li><strong>Scalability</strong>: Easily scale applications up or down based on demand.</li><li><strong>Isolation</strong>: Containers encapsulate an application and its dependencies, ensuring that they run independently of each other.</li></ul><h3>What Problems Does Docker Resolve? A Real-Life Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*VA_xOHMAbofHsnXIPNPwuA.jpeg" /></figure><p>As developers, we often face a frustrating issue: an application works perfectly on our local machine but fails when run on a colleague’s computer, a staging server, or in production. This inconsistency usually stems from differences in operating systems, software versions, or dependencies commonly referred to as <strong>environment inconsistency</strong>.</p><p>In one of our projects, we encountered this exact problem. We had thoroughly tested the application on our local machines, and it worked flawlessly. <strong><em>But once deployed to production, it failed</em></strong>. After hours of debugging, we discovered the issue was caused by subtle differences between our local and production environments, <strong>such as mismatched dependency versions and configurations</strong>.</p><p>That’s when we turned to Docker, and it solved the problem effortlessly. <strong>Docker lets you package an application along with everything it needs code, runtime, libraries, and configurations into a container</strong>. This container ensures the application runs consistently, regardless of where it is deployed, as long as Docker is installed.</p><p>By using Docker, <strong>we not only resolved our production issue but also saved significant time and effort</strong>. It provided a standardized, reliable solution that worked seamlessly across different environments truly a game-changer for modern application development.</p><h3><strong>What is </strong>CI/CD<strong>?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIss8qJ1o-rsa7CiJU3Fmw.png" /></figure><p>CI/CD in Azure DevOps stands for <strong>Continuous Integration (CI)</strong> and <strong>Continuous Deployment (CD)</strong>, which are practices to automate the process of building, testing, and deploying applications. In CI, developers frequently merge their code into a shared repository, where automated builds and tests ensure the new code works well with existing code. During this process, <strong>artifacts</strong> (files like build outputs or packages) are generated and stored, serving as deployable versions of the application. In CD, these artifacts are automatically deployed to production or other environments, ensuring fast, reliable delivery of updates. Azure DevOps provides tools like <strong>Pipelines</strong> to manage these workflows, enabling consistent and high-quality software delivery</p><h3><strong>CI/CD Pipeline with Docker?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0eYP_i0n_NXoEYC4UrVhAA.jpeg" /></figure><p>A CI/CD pipeline in Azure DevOps with Docker is like an automated factory for your app. In the <strong>CI</strong> phase, your app’s code is packed into a <strong>Docker image</strong> (a container with everything the app needs to run), tested, and stored in a <strong>container registry</strong> like Azure Container Registry (ACR) or Docker Hub, which acts like a warehouse. In the <strong>CD</strong> phase, this image is taken from the registry and deployed to platforms like <strong>Azure Kubernetes Service (AKS)</strong> or <strong>App Service</strong> to make it live for users. This process ensures smooth, consistent, and automated app delivery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pbFrwrlZK2gJrc_wJ4uMiA.png" /></figure><p><strong>Docker Image</strong>:</p><ul><li>Think of an image as a blueprint or recipe for creating containers. It includes the application code, system libraries, and dependencies. Images are immutable, meaning they don’t change once created.</li><li>Example: An image could contain a Python app or written in any programming language with all the required libraries pre-installed.</li></ul><p><strong>Docker Container</strong>:</p><ul><li>A container is a running instance of an image. It’s like baking a cake from a recipe — the image is the recipe, and the cake is the container.</li><li>Containers are lightweight, portable, and isolated from other containers</li></ul><p><strong>Example</strong>:</p><ul><li>You have a Docker image of a web server (like Nginx).</li><li>When you start the container, it runs the web server based on the image.</li></ul><h3>What is a Web Server? Examples of Web Servers</h3><p>A <strong>web server</strong> is software that delivers web pages to users over the internet. When you type a URL in your browser, the web server processes that request and sends back the website’s content.</p><p><strong>Common Web Servers:</strong></p><ul><li><strong>Apache HTTP Server</strong>: One of the oldest and most popular web servers.</li><li><strong>Nginx</strong>: Known for its speed and ability to handle many simultaneous requests.</li><li><strong>Microsoft IIS</strong>: A web server for Windows servers.</li><li><strong>LiteSpeed</strong>: A performance-focused web server.</li></ul><h3>Getting Started with Docker</h3><p>Let’s say you want to run a web server like Nginx using Docker. Here’s how you can do it:</p><p><strong>Install Docker</strong><br>Visit the <a href="https://www.docker.com/">official Docker website</a> and follow instructions for your operating system..<br>Make sure Docker is installed on your machine.<br>After installation, Verify Docker is running:</p><pre>docker — version</pre><p><strong>Check Docker Information</strong></p><p>View system-wide Docker details</p><pre>docker info</pre><p><strong>Running Your First Docker Container</strong></p><p><strong>Pull an Image</strong>: Use the command:</p><p>Download the Nginx image from <a href="https://hub.docker.com/">Docker Hub</a> (a public repository of pre-built images):<br>LINK: <a href="https://hub.docker.com/_/nginx">nginx — Official Image | Docker Hub</a></p><pre>docker pull nginx</pre><p><strong>List All Docker Images</strong></p><pre>docker images</pre><p>Create a Container: Run a container from the image</p><pre>docker run -d --name my-nginx nginx</pre><h3>How to Start the Container</h3><p>Once you’ve created a container, you can manage its lifecycle easily.</p><p>Use the docker start command:</p><pre>docker start my-nginx</pre><h4>Checking Running Containers:</h4><p>See all active containers with</p><pre>docker ps<br>docker ps -a      // List All Containers (Running and Stopped)</pre><h4>Stopping a Container:</h4><p>Stop a running container with</p><pre>docker stop my-nginx</pre><h4>Restarting a Container:</h4><p>Restart it using</p><pre>docker restart my-nginx</pre><h3>Docker in Action: Transforming Application Development</h3><p>Docker streamlines the development workflow, from coding to deployment. With its consistent and portable environment, it ensures your applications work the same way everywhere, solving the age-old problem of environment inconsistencies.</p><h3>Conclusion: Docker Is a Game-Changer</h3><p>Docker empowers developers and organizations by simplifying application deployment. Whether you’re running a simple web server or deploying a multi-service architecture, Docker’s flexibility, portability, and reliability make it an indispensable tool for modern software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e86afab9312f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[     . ]]></title>
            <link>https://bvsreyanth.medium.com/-fc6520305f49?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc6520305f49</guid>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 18:42:58 GMT</pubDate>
            <atom:updated>2024-11-09T18:42:58.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>𝐒𝐰𝐚𝐠𝐠𝐞𝐫 𝐢𝐬 𝐁𝐞𝐢𝐧𝐠 𝐑𝐞𝐦𝐨𝐯𝐞𝐝 𝐟𝐫𝐨𝐦 .𝐍𝐄𝐓 𝟗</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*SoUU-uqJY7QcSJqD1aNG9g.png" /></figure><blockquote>Why Is Swagger Going Away in .NET 9?</blockquote><p>For years, .NET developers have relied on Swagger, specifically the Swashbuckle.AspNetCore package, to make documenting and testing APIs easier. Swagger provided an interactive, convenient way to generate API documentation. But with .NET 9, Microsoft is moving away from Swagger and introducing its own built-in OpenAPI support. Here’s why ?</p><ol><li><strong>Maintenance Issues</strong>: Swashbuckle is no longer actively maintained, so it hasn’t kept up with updates for newer .NET versions, leading to bugs and compatibility issues. For a platform as fast-moving as .NET, relying on a third-party tool with uncertain support just isn’t sustainable.</li><li><strong>Better Control and Performance</strong>: By building OpenAPI support directly into .NET 9, Microsoft can provide faster, more reliable API documentation without external dependencies. This native approach means better performance, easier updates, and no more dependency headaches.</li><li><strong>Future-Proofing</strong>: With native OpenAPI support, .NET developers now have an official, built-in solution for API documentation that’s designed to work seamlessly with future .NET releases, making it a stable choice for the long haul.</li></ol><p>With this understanding, let’s go over how to transition from Swagger to the new OpenAPI support in .NET 9.</p><blockquote>How to Transition from Swagger to Built-In OpenAPI in .NET 9</blockquote><p>If you’re used to using Swagger in your .NET apps, this guide will walk you through how to use the new Microsoft.AspNetCore.OpenApi package for generating OpenAPI documentation. By the end, you’ll have a sleek, built-in way to create and customize API documentation.</p><h3>Step 1: Install the New OpenAPI Package</h3><p>The first step is to add the Microsoft.AspNetCore.OpenApi package to your project. This package is the foundation for generating OpenAPI documents in .NET 9.</p><pre>dotnet add package Microsoft.AspNetCore.OpenApi --prerelease</pre><blockquote>Note: The --prerelease flag is only necessary if you’re working with a prerelease version of .NET 9.</blockquote><h3>Step 2: Set Up OpenAPI in Your Project</h3><p>Now that you have the package, it’s time to set up OpenAPI in your ASP.NET Core project. This setup replaces the traditional Swagger configuration you may have used with Swashbuckle.</p><p>Open Program.cs and add the following lines:</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Add OpenAPI services<br>builder.Services.AddOpenApi();<br><br>var app = builder.Build();<br><br>// Map the OpenAPI endpoint<br>app.MapOpenApi();<br><br>// Define your endpoints<br>app.MapGet(&quot;/&quot;, () =&gt; &quot;Hello, World!&quot;);<br><br>app.Run();</pre><p>Here’s what’s happening:</p><ul><li><strong>Replace </strong>builder.Services.AddSwaggerGen()<strong> with </strong>builder.Services.AddOpenApi(): This registers OpenAPI services to generate your API documentation.</li><li><strong>Replace </strong>app.UseSwagger() <strong>with </strong>app.MapOpenApi(): This method exposes the OpenAPI document at a specific URL, making it accessible.</li></ul><p>That’s it! Now your OpenAPI documentation is ready to be served at the /openapi/v1.json endpoint.</p><h3>Step 3: Access Your New OpenAPI Document</h3><p>With the setup in place, it’s time to test it out. Run your application, then open your browser and go to:</p><pre>https://localhost:&lt;port&gt;/openapi/v1.json</pre><p>Replace &lt;port&gt; with the actual port number your app is running on. You should see a JSON file that represents your API documentation. This file follows the OpenAPI format, just like Swagger did, but now it’s generated entirely by .NET 9’s native support.</p><h3>Step 4: Customize Your OpenAPI Documentation</h3><p>The default OpenAPI document might look a bit basic, but you can easily add custom details like a title, version, and description. Here’s how to do it in Program.cs:</p><pre>builder.Services.AddOpenApi(options =&gt;<br>{<br>    options.AddDocumentTransformer((document, context, cancellationToken) =&gt;<br>    {<br>        document.Info = new()<br>        {<br>            Title = &quot;My API&quot;,<br>            Version = &quot;v1&quot;,<br>            Description = &quot;XYZ&quot;<br>        };<br>        return Task.CompletedTask;<br>    });<br>});</pre><p>This customization adds important context to your OpenAPI document, making it more informative for users.</p><h3>Limitations of .NET 9’s Built-In OpenAPI Support</h3><p>While .NET 9’s OpenAPI support covers the basics, it doesn’t include some of the interactive features you might be used to with Swagger, such as:</p><ul><li><strong>No Interactive UI</strong>: .NET 9’s built-in OpenAPI support doesn’t include an interactive UI for testing endpoints. You can still install and configure the Swagger UI package if you need it.</li><li><strong>No Client/Server Code Generation</strong>: The built-in OpenAPI support does not include automatic code generation based on the OpenAPI spec.</li><li><strong>No OpenAPI-Based Spec Testing</strong>: Unlike Swagger, .NET 9’s OpenAPI doesn’t support spec testing out of the box.</li></ul><h3>Conclusion<strong>:</strong></h3><p>Transitioning from Swagger to .NET 9’s built-in OpenAPI support marks a new chapter for ASP.NET Core developers. This native integration offers a streamlined, future-proof approach to API documentation, helping teams maintain compatibility with upcoming. NET releases and reduce reliance on external packages. While some Swagger-specific features like an interactive UI are absent, .NET 9’s OpenAPI still provides a solid foundation for clear, reliable documentation. For more insights, check out this <a href="https://steven-giesel.com/blogPost/777776a2-a13c-46bb-bf6b-89316d88508c">blog post</a> and stay updated on the ongoing developments in the <a href="https://github.com/dotnet/aspnetcore/issues/54599">.NET GitHub discussion</a>. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc6520305f49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Stop Using FirstOrDefault (And What to Use Instead)]]></title>
            <link>https://bvsreyanth.medium.com/why-you-should-stop-using-firstordefault-and-what-to-use-instead-a0c5c8a64ffd?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0c5c8a64ffd</guid>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 13:41:56 GMT</pubDate>
            <atom:updated>2024-10-26T13:41:56.800Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever written code with C# or any similar language, you may have come across the method FirstOrDefault. On the surface, it seems like a useful tool—but using it too often (or incorrectly) can lead to bugs that are difficult to spot. In this post, I&#39;ll walk you through why it&#39;s a problem and what alternatives you should consider.</p><blockquote><em>What is </em><em>FirstOrDefault?</em></blockquote><p>Let’s say you have a list of items and you want to grab the first one. The FirstOrDefault method seems to fit perfectly for that job. If it finds an item, it returns the <strong>first one</strong>. If not, it gives you a <strong>default value</strong>—usually null for objects, or 0 for numbers.</p><p>Example:</p><pre>List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 2, 3, 4 };<br>int firstNumber = numbers.FirstOrDefault(); // This will return 1.</pre><p>If the list is empty, it won’t crash — it just returns the default value of int, which is 0:</p><pre>List&lt;int&gt; emptyNumbers = new List&lt;int&gt;();<br>int firstNumber = emptyNumbers.FirstOrDefault(); // This returns 0.</pre><p>It looks safe at first. So, what’s the problem?</p><blockquote>Why is FirstOrDefault a Bad Idea?</blockquote><p>When FirstOrDefault returns a default value (like null), it may quietly hide problems that you should fix. For example, you might expect your list to always contain at least one item, but if it doesn’t, FirstOrDefault will just return null instead of crashing the program. This can make your program behave unpredictably, causing <strong>hard-to-detect bugs</strong>.</p><p>Often, developers feel the need to write extra code to check if the result of FirstOrDefault is null. This makes the code <strong>longer</strong> and <strong>messier</strong>.</p><pre>var user = users.FirstOrDefault();<br>if (user != null) <br>{<br>    Console.WriteLine(user.Name);<br>}<br>else <br>{<br>    Console.WriteLine(&quot;User not found.&quot;);<br>}</pre><h3>What Should You Use Instead?</h3><h4>1. Use First if You Expect a Result:</h4><p>If you expect your list or query to always contain an item, use First instead of FirstOrDefault. It will throw an exception if nothing is found, which helps you catch bugs earlier.</p><pre>var product = products.First(); // Throws an exception if the list is empty.</pre><h4><strong>2. Use </strong><strong>Single or </strong><strong>SingleOrDefault</strong></h4><p>If you expect <strong>only one</strong> item to match your query, use Single. This ensures there are no unexpected duplicates, and it will throw an exception if more than one match is found.</p><pre>var user = users.SingleOrDefault(u =&gt; u.Email == &quot;test@example.com&quot;);</pre><ul><li>Single: Throws an error if there are <strong>zero or more than one</strong> item.</li><li>SingleOrDefault: Returns the item if it exists, or <strong>null</strong> if it doesn’t, but throws an exception if there are multiple matches.</li></ul><h3><strong>My Suggestion is </strong><strong>FirstOrDefault Okay to Use?</strong></h3><p>Sometimes, FirstOrDefault can still be useful, especially when you <strong>don&#39;t care</strong> if there’s no result and just want a quick default. For example, if you’re fetching an optional value and it’s okay for it to be null or 0, you can use FirstOrDefault. Just be cautious—make sure you’re <strong>aware of the risks</strong> and handle the default value properly.</p><h3><strong>Conclusion</strong></h3><p>While FirstOrDefault may seem like a handy tool, it often does more harm than good. Its silent behavior—returning null or a default value—can lead to <strong>subtle bugs</strong>, making it harder to detect and fix issues early.</p><p>The good news? There are <strong>better alternatives</strong>! Methods like First, Single and ensure that your code fails fast if something unexpected happens. This helps you <strong>catch errors early</strong> and write <strong>cleaner, more predictable code</strong>.</p><p>So, the next time you find yourself reaching for FirstOrDefault, pause and ask yourself—<strong>Is this really the best choice?</strong> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0c5c8a64ffd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Request Pipeline with Entity Framework in ASP.NET Core]]></title>
            <link>https://bvsreyanth.medium.com/the-request-pipeline-with-entity-framework-in-asp-net-core-467778b45f42?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/467778b45f42</guid>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 12:22:15 GMT</pubDate>
            <atom:updated>2024-10-21T12:27:13.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Welcome! In this post, we’ll explore the <strong>Request Pipeline in ASP.NET Core</strong> and integrate <strong>Entity Framework (EF)</strong> into the mix. If you’re already familiar with how the request pipeline processes HTTP requests in ASP.NET Core, that’s awesome! But here, we’ll take it a step further to see how <strong>EF can interact within the pipeline</strong>, ensuring efficient communication between the application and the database.</p><p>We’ll break this down so that you can understand each step, and by the end of this post, you’ll know exactly where <strong>Entity Framework</strong> fits in the pipeline, why it matters, and how you can leverage it efficiently within your web application.</p><h3>The Request Pipeline: Quick Recap 🚀</h3><p>Every HTTP request in an ASP.NET Core application <strong>flows through a pipeline</strong> — a sequence of middleware components, each performing a specific task like routing, logging, or authentication. This pipeline controls both <strong>request processing</strong> and <strong>response generation</strong>.</p><p>Here’s a quick analogy:</p><ul><li><strong>HTTP Request</strong> = A box on a conveyor belt</li><li><strong>Request Pipeline</strong> = The conveyor belt moving the box</li><li><strong>Middleware Components</strong> = Workers standing along the belt, doing tasks in order (like inspecting, modifying, or discarding the box).</li></ul><p>Similarly, each HTTP request moves through middleware components in the pipeline. Some middleware may <strong>short-circuit the process</strong>, stopping the request before it reaches the end if certain conditions are not met.</p><h3>Where Does Entity Framework Fit in the Pipeline? 🛠️</h3><p><strong>Entity Framework (EF)</strong> is a powerful ORM (Object-Relational Mapper) that simplifies data access by allowing you to interact with your database through <strong>C# objects</strong> rather than raw SQL. But how does it work with the ASP.NET Core <strong>request pipeline</strong>?</p><h4>Key Roles of EF in the Request Pipeline:</h4><ol><li><strong>Dependency Injection (DI):</strong> EF’s DbContext is injected into your controllers or middleware as a <strong>service</strong>, allowing smooth access to the database.</li><li><strong>Database Operations:</strong> It handles <strong>query execution, updates, and database transactions</strong> during the request.</li><li><strong>Performance and Error Handling:</strong> Middleware using EF can monitor or modify requests, logging <strong>database-related issues</strong> or preventing inefficient queries from proceeding.</li></ol><p>Below, we’ll look at how to <strong>integrate EF</strong> properly into the pipeline by creating middleware components that use DbContext for logging and validation.</p><h3>Integrating Entity Framework into the Request Pipeline ⚙️</h3><p>Let’s walk through a practical example of building middleware that leverages <strong>EF Core</strong> to <strong>log incoming requests and their status</strong> in a database.</p><h4>Step 1: Define the RequestLog Entity</h4><p>First, create a class to represent the RequestLog entity. This class will define the structure of the data you want to log in the database, including properties that correspond to the details of each request.</p><pre>public class RequestLog<br>{<br>    public int Id { get; set; }<br>    public string HttpMethod { get; set; }<br>    public string Path { get; set; }<br>    public DateTime RequestTime { get; set; }<br>    public bool IsSuccessful { get; set; }<br>}<br></pre><h4>Setup 2: Your EF Core DbContext</h4><p>create a <strong>DbContext</strong> class to interact with the database.</p><pre>public class RequestLoggingContext : DbContext<br>{<br>    public RequestLoggingContext(DbContextOptions&lt;RequestLoggingContext&gt; options) : base(options) { }<br><br>    public DbSet&lt;RequestLog&gt; RequestLogs { get; set; }<br>}</pre><h4>Step 3: Register EF Core in Program.cs</h4><p>We need to <strong>add EF Core to the DI container</strong> in Program.cs to make our DbContext available throughout the application.</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>// Register the DbContext with a SQL Server database.<br>builder.Services.AddDbContext&lt;RequestLoggingContext&gt;(options =&gt;<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>var app = builder.Build();</pre><p>Make sure your <strong>DefaultConnection</strong> is properly configured in appsettings.json.</p><h4>Step 4: Configure Connection String in appsettings.json</h4><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=your_server_name;Database=your_database_name;User Id=your_username;Password=your_password;&quot;<br>  }<br>}</pre><h4>Step 5: Build Middleware Using EF Core</h4><p>Next, let’s create <strong>middleware</strong> that logs request details to the database.</p><pre>public class RequestLoggingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    private readonly RequestLoggingContext _dbContext;<br><br>    public RequestLoggingMiddleware(RequestDelegate next, RequestLoggingContext dbContext)<br>    {<br>        _next = next;<br>        _dbContext = dbContext;<br>    }<br><br>    public async Task InvokeAsync(HttpContext context)<br>    {<br>        var log = new RequestLog<br>        {<br>            HttpMethod = context.Request.Method,<br>            Path = context.Request.Path,<br>            RequestTime = DateTime.Now,<br>            IsSuccessful = false<br>        };<br><br>        try<br>        {<br>            await _next(context); // Call the next middleware component in the pipeline.<br>            log.IsSuccessful = context.Response.StatusCode &lt; 400;<br>        }<br>        catch<br>        {<br>            log.IsSuccessful = false;<br>            throw; // Ensure exceptions are propagated.<br>        }<br>        finally<br>        {<br>            _dbContext.RequestLogs.Add(log);<br>            await _dbContext.SaveChangesAsync();<br>        }<br>    }<br>}</pre><p>This middleware does the following:</p><ol><li><strong>Captures request information</strong> (method, path, etc.).</li><li><strong>Logs the request status</strong> after it passes through the rest of the pipeline.</li><li><strong>Handles exceptions</strong> to ensure failed requests are logged properly.</li><li><strong>Saves logs to the database</strong> using EF Core.</li></ol><h4>Step 6: Register Middleware in the Pipeline</h4><p>Now, we need to register our middleware in Program.cs.</p><pre>app.UseMiddleware&lt;RequestLoggingMiddleware&gt;();<br><br>app.UseHttpsRedirection();<br>app.UseStaticFiles();<br>app.UseRouting();<br>app.UseAuthorization();<br><br>app.MapControllers();<br><br>app.Run();</pre><p>The middleware is added <strong>at the beginning of the pipeline</strong>, so it captures information about every request that comes through, regardless of success or failure.</p><h3>Testing the Middleware 🔍</h3><ol><li><strong>Run the application.</strong></li><li><strong>Make a few requests</strong> by navigating through your site.</li><li><strong>Check the logs</strong> in the database to see the captured data.</li></ol><p>If everything is working correctly, each request will be logged with details like the HTTP method, path, and whether the request was successful.</p><h3>Conclusion 🎉</h3><p>In this post, we explored how to <strong>integrate EF Core into the ASP.NET Core request pipeline</strong>. We built a custom <strong>logging middleware</strong> that uses EF Core to log request information to a database. This approach not only provides <strong>centralized logging</strong> but also demonstrates how EF Core can enhance the pipeline by adding custom behavior.</p><p>Remember:</p><ul><li><strong>Middleware order matters</strong>, so place your middleware wisely.</li><li><strong>EF Core’s DbContext</strong> is injected using DI, making it simple to use in any part of the application.</li></ul><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467778b45f42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Developer’s Journey: Introduction to Microservices with dotnet]]></title>
            <link>https://bvsreyanth.medium.com/a-developers-journey-introduction-to-microservices-with-dotnet-288256c08261?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/288256c08261</guid>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 06:26:00 GMT</pubDate>
            <atom:updated>2024-10-03T06:26:00.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Developer’s Journey: Introduction to Microservices with .Net</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*42yVnpv6nLxCONSVJbNigg.png" /></figure><p>Imagine you’re part of a growing tech company. You’re building an application that started as a simple monolith — one big codebase managing everything from user authentication to payments to notifications. It worked fine at first, but as the company scaled, so did the application’s complexity. Suddenly, small changes started causing unpredictable bugs, deployments became stressful, and scaling was a nightmare. You realize something needs to change, and that’s when you stumble upon microservices.</p><h3>A New Path: Microservices and .NET 8</h3><p>Welcome to our blog on <strong>Microservices with .NET 8</strong>! This journey is about discovering how to break free from the confusion of monolithic applications and move toward the more flexible and scalable world of microservices. Whether you’re a developer who has been in the trenches of large-scale systems or someone just starting out, this series will provide you with practical insights, walking you through how to build, deploy, and manage microservices using .NET 8.</p><p>But first, what exactly are microservices, and why should we care?</p><h3>What is Clean Architecture?</h3><p>Let’s imagine building a house. You don’t want water pipes running next to electrical wires, right? In software, we need the same separation of concerns. This is where <strong>Clean Architecture</strong> steps in — it’s like the blueprint that ensures our house (or in this case, our software) is well-organized and easy to maintain.</p><p>Clean Architecture advocates breaking down an application into well-defined layers:</p><ol><li><strong>Domain Layer</strong> — represents the core business logic.</li><li><strong>Application Layer</strong> — contains the services that interact with the domain.</li><li><strong>Infrastructure Layer</strong> — manages data persistence and external services.</li><li><strong>Presentation Layer</strong> — the API.</li></ol><p>With Clean Architecture, we ensure our business logic isn’t tangled up with infrastructure or UI concerns. And this clear separation sets the stage perfectly for implementing microservices.</p><h3>So, what is a Microservice?</h3><p>Picture our monolith application — now think about chopping it into smaller, bite-sized pieces, each piece representing a specific function, like user authentication or payment processing. Each of these pieces is called a <strong>microservice</strong>. They operate independently and are responsible for doing one thing well. For instance, the payment service doesn’t care about user login details and vice versa.</p><p>Unlike monolithic systems, microservices can evolve, scale, and be deployed independently. This means if your user authentication service needs a feature update, you can deploy it without touching the payment service or bringing the entire application down.</p><h3>When Do We Need Microservices?</h3><p>It’s important to ask yourself, <em>when</em> should you move to microservices?</p><p>Let’s revisit our company story. As the company grew, the user base expanded, and the monolith began to crack under the pressure. Handling millions of users in a monolithic system made the whole application sluggish. If one part slowed down (like the reporting service), the entire application would suffer.</p><p>That’s where microservices come in handy. They allow us to focus on scaling the exact part of the system that’s struggling without impacting the rest of the application. But there are also cases where microservices aren’t the best solution, especially if your application is small or doesn’t need extreme scalability just yet. You’ll learn in this series when microservices make sense and when you might be overcomplicating things.</p><h3>Designing a Business Project Using Microservices</h3><p>Now, let’s say our company decides to split the monolithic application into microservices. We’ll take something like an <strong>e-commerce platform</strong> and break it into manageable microservices, such as:</p><ul><li><strong>Catalog Service</strong>: Manages the list of products.</li><li><strong>Order Service</strong>: Handles customer orders.</li><li><strong>Payment Service</strong>: Deals with payment processing.</li></ul><p>By breaking down the project, we allow each microservice to operate independently. If there’s a sudden spike in users browsing products, we can scale the catalog service without worrying about the order or payment services.</p><h3>Building the Microservices Project</h3><p>Before diving into code, we’ll set up our development environment. You’ll be using <strong>.NET 8</strong>, a powerful framework for building scalable APIs, and tools like <strong>Docker</strong> and <strong>Kubernetes</strong> for containerization and orchestration.</p><p>We’ll start by creating our first microservice — let’s say it’s the <strong>Order Service</strong>. You’ll follow a step-by-step guide:</p><ul><li>Defining endpoints for creating, reading, and updating orders.</li><li>Communicating with other services like the payment service using <strong>gRPC</strong>, <strong>HTTP</strong>, or messaging systems like <strong>RabbitMQ</strong>.</li><li>Deploying your microservice in a containerized environment for easy scalability and fault tolerance.</li></ul><h3>Scaling and Managing Microservices</h3><p>Once the services are built, we’ll explore how to scale them. Imagine a scenario where the <strong>Payment Service</strong> is handling an enormous number of transactions during Black Friday. We can scale that service independently without affecting the other parts of the application. We’ll also cover how to monitor performance using tools like <strong>Prometheus</strong> and how to ensure the system remains reliable even during failures.</p><h3>Security in Microservices</h3><p>One key topic is security. Imagine sensitive information like user payment details being transmitted between microservices. You’ll learn how to secure these communications and implement authentication and authorization across services.</p><h3>Microservices Patterns</h3><p>As you build more microservices, you’ll encounter common challenges like how to handle service failures gracefully. This is where design patterns come in, like:</p><ul><li><strong>Circuit Breaker</strong>: Prevents cascading failures when one service is down.</li><li><strong>API Gateway</strong>: Acts as a single entry point for all services, simplifying communication.</li></ul><h3>Why Microservices Matter in Modern Development</h3><p>In today’s fast-paced world of software development, microservices have become essential. They offer:</p><ul><li><strong>Scalability</strong>: By allowing each microservice to scale independently.</li><li><strong>Maintainability</strong>: Each service is small and focused, making it easier to update.</li><li><strong>Flexibility</strong>: You can use the best tool for the job in each microservice.</li><li><strong>Resilience</strong>: If one service fails, the rest of the system continues to run smoothly.</li><li><strong>Faster Deployment</strong>: Teams can deploy updates independently without disrupting the whole system.</li></ul><p><strong>Thank you for reading!</strong> I hope this introduction to microservices with .NET 8 has been insightful and provided a clear understanding of the foundational concepts. Stay tuned for the upcoming articles, where we’ll dive deeper into the practical implementation of microservices, explore advanced topics like inter-service communication, and tackle real-world scenarios. If you have any questions or need further clarification, feel free to leave a comment or reach out.</p><p><strong>Happy coding</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=288256c08261" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blazor Basics: Understanding Components, Hosting Models, and More]]></title>
            <link>https://bvsreyanth.medium.com/blazor-basics-understanding-components-hosting-models-and-more-cafa28c64853?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/cafa28c64853</guid>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 10:36:35 GMT</pubDate>
            <atom:updated>2024-08-12T07:28:59.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4q4hVU-m-QiIYgaf.png" /></figure><h3>What is Blazor?</h3><p>Blazor is a .NET front-end framework that allows you to build web applications using C# and Razor components. It’s a powerful tool that enables you to create fast, interactive, and scalable web applications. Unlike other JavaScript-based frameworks, Blazor allows you to write rich web applications entirely in C#, eliminating the need to switch between languages for backend and frontend development. It combines the power of .NET with the simplicity of modern web development, without relying on JavaScript.</p><blockquote><strong>Blazor’s Name</strong>: <br>A mix of “Browser” and “Razor,” reflecting its ability to run C# code in the browser replacing traditional server-side rendering with a client-side approach.</blockquote><h3>What are Blazor Components?</h3><p>In Blazor, a component is a piece of UI, such as a page, table, or form. Components are .NET C# classes built into .NET assemblies that:</p><ul><li>Define flexible UI rendering logic</li><li>Handle user events</li><li>It can be nested and reused</li><li>Can be shared and distributed as Razor class libraries or NuGet packages</li></ul><p>Components are usually written in Razor files (.razor extension), which allows you to combine HTML with C# code.</p><h3>Razor Syntax</h3><p>Razor syntax is a way to combine HTML with C# code in the same file. It might look unclear at first, but it’s quite simple. <br>Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvUoDoDPAUKn4cyzHGxGyg.png" /></figure><p>In this example, the @code block allows you to write C# code inside the HTML markup page.</p><h4>Supported Browsers</h4><p>Blazor supports the following browsers:</p><ul><li>Apple Safari</li><li>Google Chrome</li><li>Microsoft Edge</li><li>Mozilla Firefox</li></ul><h4>Blazor Hosting Models</h4><p>Blazor offers different hosting models, each suited for different application needs. Understanding these models is crucial for choosing the right one for your project.</p><h3>Blazor WebAssembly vs Blazor Hybrid</h3><p>There are two main types of Blazor applications:</p><h4>Blazor WebAssembly</h4><ul><li>Executes C# code directly in the browser using WebAssembly</li><li>Allows you to use the entire .NET ecosystem, including libraries and tools</li><li>Creates responsive web designs using Razor components</li><li>Cross-platform and doesn’t require server round trips</li></ul><h4>Blazor Hybrid</h4><ul><li>Combines the power of Blazor with native client frameworks</li><li>Allows you to build powerful cross-platform desktop and mobile applications using C# and Razor components</li><li>Used for desktop and mobile applications</li></ul><h3>How Does Blazor Work?</h3><p>To understand how Blazor works, it is important to know the two versions of Blazor: Blazor Server and Blazor WebAssembly.</p><h4>1. Blazor Server</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*vRzsN4NV1g9SNgq1.png" /></figure><p>Blazor Server is a hosting model that executes components on the server from within an ASP.NET Core app. Here’s how it works:</p><ul><li>UI updates, event handling, and JS calls are handled over a SignalR connection using the WebSockets protocol</li><li>The state on the server associated with each connected client is called a circuit</li><li>Circuits aren’t tied to a specific network connection and can tolerate temporary network interruptions</li></ul><blockquote>What is SignalR? SignalR is a powerful library developed by Microsoft that seamlessly incorporates real-time functionality into applications. It allows you to push content from the server to connected clients in real-time.</blockquote><p><strong>Benefits of using Blazor Server:</strong></p><ul><li>Download size is significantly smaller than Blazor WebAssembly</li><li>The app loads much faster</li><li>The app takes full advantage of server capabilities, including .NET Core APIs</li><li>.NET/C# code base isn’t served to clients</li></ul><p><strong>Limitations of Blazor Server:</strong></p><ul><li>Higher latency usually exists</li><li>No offline support</li><li>Scaling apps with many users requires server resources</li></ul><blockquote>Note : Latency still a major problem of Blazor Server. Client is tied to the server with a webSocket protocol which bring into question the scalability of Blazor server App (virtual DOM management for each client need importante CPU, Storage and Network resources)</blockquote><h3>2. Blazor WebAssembly Server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*JdrtdwQUpL-wnEFR.png" /></figure><p>Blazor WebAssembly Server runs components client-side in the browser on a WebAssembly-based .NET runtime. Here’s how it works:</p><ul><li>Razor components, their dependencies, and the .NET runtime are downloaded to the browser</li><li>Components are executed directly on the browser UI thread</li><li>UI updates and event handling occur within the same process</li><li>Assets are deployed as static files to a web server or service capable of serving static content to clients</li></ul><p><em>Blazor provides various hosting models tailored to different application requirements, making it essential to choose the right one for your project. You’ve already learned about the first model, Blazor WebAssembly. The second model is the Blazor Hybrid.</em></p><p><strong>Blazor Hybrid</strong>: This model combines the strengths of Blazor with native client frameworks, enabling the development of robust cross-platform desktop and mobile applications using C# and Razor components. It’s particularly well-suited for building applications that need to run on both desktop and mobile platforms.</p><h3>Where can I learn more?</h3><p>Here are some valuable resources to continue your Blazor journey:</p><ul><li><a href="https://docs.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-5.0">Official Microsoft Blazor Documentation</a></li><li><a href="https://www.youtube.com/watch?v=MR0uc3pJYf4&amp;list=PL4WEkbdagHIR0RBe_P4bai64UDqZEbQap&amp;index=3&amp;ab_channel=CuriousDrive%5D">Blazor Tutorial: Build your first Blazor App</a></li><li><a href="https://www.youtube.com/watch?v=KlngrOF6RPw&amp;list=PLdo4fOcmZ0oWlP1Qpzg7Dwzxr298ewdUQ&amp;ab_channel=dotNET">Official Dotnet channel on YouTube</a></li></ul><p><strong>Thank you for reading! </strong>I hope this introduction to Blazor has been helpful. Stay tuned for upcoming articles where we’ll dive deeper into Blazor WebAssembly and other related topics. If you have any questions or need further clarification, feel free to leave a comment or reach out. <br><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cafa28c64853" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“       …]]></title>
            <link>https://bvsreyanth.medium.com/-c825d2b4aa27?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/c825d2b4aa27</guid>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 07:51:34 GMT</pubDate>
            <atom:updated>2024-01-24T07:51:34.594Z</atom:updated>
            <content:encoded><![CDATA[<h3>“𝐃𝐨 𝐲𝐨𝐮 𝐤𝐧𝐨𝐰 𝐭𝐡𝐞 𝐞𝐱𝐚𝐜𝐭 𝐝𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞𝐬 𝐛𝐞𝐭𝐰𝐞𝐞𝐧 𝐋𝐈𝐍𝐐 𝐦𝐞𝐭𝐡𝐨𝐝𝐬 𝐥𝐢𝐤𝐞:<br>Single() and First() ? 🤔”</h3><blockquote>Introduction<strong>:</strong></blockquote><p>LINQ is one of the most loved functionalities by C# developers. It allows you to perform calculations and projections over a collection of items, making your code easy to build and, even more, easy to understand.</p><p>In this article, we’ll explore different aspects of the First() and Single()method variations, enabling you to select the most suitable one for your specific requirements.</p><ol><li><strong>Exploring First() Method :</strong></li></ol><p>First() is a method used to retrieve the first element from a sequence that satisfies a specified condition. It is commonly used with collections such as arrays, lists, or query results.</p><blockquote>Key points :</blockquote><ol><li>Retrieval of First Element</li><li>It throws an exception when no matching element is found in the sequence.</li><li>First() is a non-generic method.</li><li>Single Match Retrieval: It returns the first element that fulfills the specified condition. If multiple elements meet the condition, it retrieves the first among them.</li><li>No Predicate Overload: Unlike Single() or Where() methods, First() doesn’t include an overload accepting a predicate that checks for a specific condition.</li></ol><p>Understanding First&lt;TSource&gt;(IEnumerable&lt;TSource&gt;) and First&lt;TSource&gt;(IEnumerable&lt;TSource&gt;, Func&lt;TSource, Boolean&gt;):</p><p>Both of these methods are generic.</p><p>First&lt;TSource&gt;(IEnumerable&lt;TSource&gt;): Retrieves the first element of a sequence.</p><p>First&lt;TSource&gt;(IEnumerable&lt;TSource&gt;, Func&lt;TSource, Boolean&gt;): Retrieves the first element in a sequence that satisfies a specified condition.</p><h4>Type Parameters:</h4><ol><li>TSource: Represents the type of elements within the sequence or collection.</li></ol><ul><li>Usage: It indicates the specific element type expected in the sequence passed to First&lt;TSource&gt;(IEnumerable&lt;TSource&gt;).</li><li>There are no constraints specified on TSource, making it accept any type.</li><li>Example Using Method and Query Syntax :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*zX-79cWRhmi1DuRhXy7IIg.png" /></figure><p>In this example, int is provided explicitly as the type parameter TSource, indicating that the First() the method will work on a sequence of integers (IEnumerable&lt;int&gt;).</p><p>Before understanding Predicate, Func, and Action we need to understand what is delegate?<br>In simple words, we can say that the delegates in C# are the Type-Safe Function Pointer. It means they hold the reference of a method or function and then call that method for execution.</p><blockquote>Predicate:</blockquote><blockquote>A predicate delegate methods must take one input parameter and return a boolean — true or false.</blockquote><blockquote>Func:</blockquote><blockquote>The Func delegate that takes one input parameter and one out parameter is defined in the System namespace</blockquote><blockquote>Action:</blockquote><blockquote>An Action type delegate is the same as Func delegate except that the Action delegate doesn’t return a value</blockquote><p>we’ll explore three commonly used delegates — Predicate, Action, and Func demonstrate their practical usage with a Person class example.</p><p><strong>The Person Class:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*aq6OTwSVvAGKcNxTcJAZLQ.png" /></figure><p>Understanding delegates in C# is crucial for writing clean and maintainable code. Predicates, Actions, and Funcs are versatile tools that can enhance the expressiveness of your programs. Putting It All Together in below example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*5qt-F09LU-R7gvO79XoIlA.png" /></figure><p><strong>What Happens when we call the First Method on an Empty Data Source and the First Method Does not Return any Data?</strong></p><p>The LINQ First Method will throw an InvalidOperationException whenever the data source is empty. For a better understanding, please have a look at the following example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*FS8_M4XvSF0uyWUZELMv1Q.png" /></figure><p>If the specified condition does not return any data, the LINQ First Method will throw an <strong>InvalidOperationException</strong>. For a better understanding, please have a look at the following example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*xCDqo32khMaLRDxN6ig4fQ.png" /></figure><p>These distinctions provide a clear understanding of how First() behaves in different scenarios.</p><blockquote>Understanding Single() Method in LINQ:</blockquote><p>Single() is a method used to retrieve the only element from a sequence that satisfies a specified condition. This method is commonly used with collections like lists, arrays, or query results.</p><blockquote>Key points:</blockquote><ol><li>The single method does not take any parameter</li><li>This method returns the only element from a sequence.</li><li>In this case, if the data source is empty or if the data source contains more than one element, then it throws an exception.</li><li>It can be used in both method and query syntax while working with LINQ.</li></ol><p>Example of Single() method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*nlidB97Tb2znPh5NsQeZyg.png" /></figure><p><strong>Single Method with Empty Data Source:</strong></p><p>In this example, the data source is empty. When we apply the LINQ Single method on the empty data source, it will throw <strong>System.InvalidOperationException: ‘Sequence contains no elements’ </strong>exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YG-qGhiUHMkgB_RcRV30Dw.png" /></figure><p><strong>What happens when the Sequence Contains more than one element?</strong></p><p>If the Sequence contains more than one element and we apply the Single method to that sequence, we will get the <strong>System.InvalidOperationException: ‘Sequence contains more than one element’ </strong>Exception</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WSoOmqyCfIJSoetOlx5hQ.png" /></figure><p>In this case, the Single() method is used to find a number equal to 2 in the numbers list. However, there are multiple elements that match the condition (two occurrences of 10). As a result, Single() throws an InvalidOperationException because it expects precisely one matching element and multiple matches violate this condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vL0Jmk3_3OVnoUZu3CGsiQ.png" /></figure><p>These distinctions provide a clear understanding of how Single() behaves in different scenarios.</p><h3>Conclusion</h3><p>In this article, we learned about two LINQ methods that are used to retrieve a single element from a sequence: Single() and First(). We hope this article was helpful and informative for you. If you have any questions or feedback, please leave a comment below.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c825d2b4aa27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison of RS256 and HS256 Algorithms for Token Signing in Cryptography]]></title>
            <link>https://bvsreyanth.medium.com/comparison-of-rs256-and-hs256-algorithms-for-token-signing-in-cryptography-bd21e9e7a54d?source=rss-93ad39721849------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd21e9e7a54d</guid>
            <dc:creator><![CDATA[Sreyanth]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 07:42:33 GMT</pubDate>
            <atom:updated>2024-01-12T07:42:33.876Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital world, secure communication and data integrity are paramount. Cryptographic algorithms play a pivotal role in ensuring the confidentiality, integrity, and authenticity of information. Among these algorithms, RS256 and HS256 are widely used for securing data and in also JWT(Json-web-token). Let’s delve deeper into these techniques.</p><blockquote><strong>Understanding RS256</strong></blockquote><p>RS256 operates on RSA asymmetric encryption coupled with SHA-256 hashing. This method involves a public-private key pair, where data is signed with the private key and verified with the corresponding public key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*oh2ZdkONMgwW89uh5D7kJA.png" /></figure><blockquote>Use Cases</blockquote><p>RS256 finds extensive usage in token-based authentication, such as JSON Web Tokens (JWT). It ensures secure transmission and validation of tokens, providing robust authentication mechanisms.</p><h4>Exploring HS256</h4><p>HS256 (HMAC with SHA-256) is a symmetric keyed hashing algorithm that uses one secret key. Symmetric means two parties share the secret key. The key is used for both generating the signature and validating it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*6p_XJKgZqYi0HEjbKSEN3A.png" /></figure><blockquote><strong>Be mindful</strong></blockquote><p>when using a shared key; it can open potential vulnerabilities if the verifiers(multiple applications) are not appropriately secured.</p><blockquote><strong>NOTE:</strong></blockquote><p>In both cases, a third party could potentially find your secret key and generate a JWT that would be considered valid for your application. In the case of the HS256 algorithm, verifiers (applications) of tokens have the same key that signs a JWT, which increases the risk of being exposed to a third party. You would need to take caution to protect the key from being compromised, such as putting the secret in a secure store, limiting access to it, etc.</p><h3>Which Should You Use?</h3><p>RS256 for high-security scenarios requiring public verification and flexibility, while HS256 offers simplicity and efficiency for scenarios prioritizing ease of implementation and message integrity without the need for public verification. Tailor your choice based on your application’s specific security and operational needs.</p><h3>Summary</h3><p>The key takeaways regarding the strengths, considerations, and considerations for choosing between RS256 and HS256 cryptographic algorithms.</p><ul><li>HS256 is a symmetric algorithm that shares one secret key between the identity provider and your application. The same key is used to sign a JWT and verify that signature.</li><li>RS256 algorithm is an asymmetric algorithm that uses a private key to sign a JWT and a public key to verify that signature.</li><li>RS256 is the recommended algorithm when signing your JWTs. It is more secure, and you can rotate keys quickly if they are compromised. (Auth0 signs JWTs with RS256 by default).</li></ul><p><em>Remember, choosing the right cryptographic algorithm depends on the specific security requirements of your application.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd21e9e7a54d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>