<?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 Rajdeep Das on Medium]]></title>
        <description><![CDATA[Stories by Rajdeep Das on Medium]]></description>
        <link>https://medium.com/@rajdeep-das?source=rss-faef5f8eef5c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*45Rwedn38AExzIL5gkB4rw.png</url>
            <title>Stories by Rajdeep Das on Medium</title>
            <link>https://medium.com/@rajdeep-das?source=rss-faef5f8eef5c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:36:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajdeep-das/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[The Magic of C# Attributes: Hidden Decorators That Transform Your Code]]></title>
            <link>https://rajdeep-das.medium.com/the-magic-of-c-attributes-hidden-decorators-that-transform-your-code-9d41f9f0e9c6?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d41f9f0e9c6</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 17:09:46 GMT</pubDate>
            <atom:updated>2025-03-26T17:09:46.000Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how those little square brackets in C# silently enhance your code? Let’s peek behind the curtain of C# attributes — those invisible workers that add superpowers to your classes and methods without changing a single line of your implementation.</p><h3>Attributes: The Secret Notes in Your Code’s Margins</h3><p>Imagine you’re reading a well-loved paperback novel. You notice the previous reader left small sticky notes throughout — “This character is important later,” or “This foreshadows the ending.” Those notes don’t change the story, but they provide valuable context.</p><p>That’s exactly what attributes do in C#.</p><p>When I first discovered attributes, I wondered how something so small could be so powerful. Take this simple example:</p><pre>[Obsolete(&quot;This method will be removed next version&quot;)]<br>public void OldMethod() <br>{<br>    // Method code here<br>}</pre><p>That little [Obsolete] tag doesn&#39;t change what the method does, but it transforms how other developers interact with it. Visual Studio immediately warns them when they try to use it – all without me having to change the actual implementation.</p><h3>How Attributes Work Their Magic</h3><p>Behind their simple syntax, attributes perform quite an elaborate dance:</p><ol><li><strong>Creation</strong>: An attribute is actually a class that inherits from System.Attribute</li><li><strong>Attachment</strong>: You decorate your code with the attribute using square brackets</li><li><strong>Storage</strong>: The compiler embeds this information into your assembly’s metadata</li><li><strong>Discovery</strong>: At runtime, your application finds these attributes through reflection</li></ol><p>It’s like leaving secret instructions that only get revealed when someone knows where to look.</p><h3>Real-World Attribute Magic I Use Every Day</h3><p>As a developer, I rely on attributes constantly without even thinking about it:</p><p><strong>Making Web APIs Feel Effortless</strong></p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class ProductsController : ControllerBase<br>{<br>    [HttpGet]<br>    public IEnumerable&lt;Product&gt; GetAll()<br>    {<br>        // Return products<br>    }<br>}</pre><blockquote>With just three <strong><em>attributes</em></strong>, I’ve transformed a regular class into a fully-functional web API. <strong><em>Behind the scenes, ASP.NET Core is scanning my assembly for these attributes and building an entire routing system based on them</em></strong>.</blockquote><h3>Form Validation Without the Hassle</h3><p>Remember the days of writing custom validation code for every single form field? Attributes changed everything:</p><pre>public class SignupForm<br>{<br>    [Required(ErrorMessage = &quot;Please enter your name&quot;)]<br>    [StringLength(50)]<br>    public string Name { get; set; }<br><br>    [Required]<br>    [EmailAddress]<br>    public string Email { get; set; }<br>}</pre><p>Each attribute acts like a tiny validator, checking user input without me having to write repetitive if-statements.</p><h3>Creating Your Own Attribute Magic</h3><p>The true power of attributes comes when you create your own. I recently built a custom logging system where I wanted to track certain methods:</p><pre>[AttributeUsage(AttributeTargets.Method)]<br>public class AuditLogAttribute : Attribute<br>{<br>    public string Operation { get; }<br><br>    public AuditLogAttribute(string operation)<br>    {<br>        Operation = operation;<br>    }<br>}</pre><p>Then I could use it throughout my code:</p><pre>[AuditLog(&quot;User password change&quot;)]<br>public void ChangePassword(string newPassword)<br>{<br>    // Method implementation<br>}</pre><p>Our logging framework now automatically tracks these method calls, who made them, and when — all without cluttering the actual method implementation.</p><h3>The Hidden Costs (That Most Tutorials Don’t Mention)</h3><p>While attributes are powerful, they’re not free magic. Since they work through <strong><em>reflection</em></strong>, excessive use can impact <strong><em>performance</em></strong>. I learned this lesson the hard way when our validation system slowed to a crawl after checking hundreds of attributes on every request.</p><p>The solution isn’t to avoid attributes but to use them strategically — like spices in cooking, they’re best when applied thoughtfully.</p><h3>Conclusion: The Invisible Enhancers</h3><p>Attributes represent one of C#’s most elegant features — they separate what code does from how it should be treated. They’re the silent workers that transform ordinary classes into serializable objects, simple methods into web endpoints, and basic properties into self-validating fields.</p><p>Next time you type those square brackets, take a moment to appreciate the invisible magic happening behind the scenes. In the quiet corners of your codebase, attributes are working tirelessly to make your code more powerful without adding complexity.</p><p>What attributes do you use most often in your C# projects? Have you created any custom ones? I’d love to hear about your experiences in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d41f9f0e9c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a simple fileserver in 1 line using go]]></title>
            <link>https://rajdeep-das.medium.com/build-a-simple-fileserver-in-1-line-using-go-6f771c333dbf?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f771c333dbf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 13:14:51 GMT</pubDate>
            <atom:updated>2024-01-21T13:14:51.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_-g25_-ZR76jyONj" /><figcaption>Photo by <a href="https://unsplash.com/@imgix?utm_source=medium&amp;utm_medium=referral">imgix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You have probably heard that Go is fantastic for building web applications of all shapes and sizes. This is partly due to the fantastic work that has been put into making the standard library clean, consistent, and easy to use.</p><p>If you’re just starting with web development in Go, the net/http package is super important. It helps you create servers for the web using simple and powerful building blocks.</p><h3>The http.Handler Interface</h3><p>As you become more familiar with Go, you will notice how much of an impact <em>interfaces</em> make in the design of your programs. The net/http interface encapsulates the request-response pattern in one method:</p><pre>type Handler interface {<br>    ServeHTTP(ResponseWriter, *Request)<br>}</pre><p>Implementors of this interface are expected to inspect and process data coming from the http.Request object and write out a response to the http.ResponseWriter object.</p><p>The http.ResponseWriter interface looks like this:</p><pre>type ResponseWriter interface {<br>    Header() Header<br>    Write([]byte) (int, error)<br>    WriteHeader(int)<br>}</pre><p>Often, you just want to share simple web pages with pictures and styles. Imagine you have a basic webpage with text, images, and design, and you just want to show it to others on the internet. That’s where serving static files comes in handy.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br>)<br><br>func main() {<br> fmt.Println(&quot;FileServer Stared on Port : 8080&quot;)<br> // &quot;.&quot; - current directory where the progam is running<br> http.ListenAndServe(&quot;:8080&quot;, http.FileServer(http.Dir(&quot;.&quot;))) <br>}</pre><p>The http.ListenAndServe function is used to start the server, it will bind to the address we gave it (:8080) and when it receives an HTTP request, it will hand it off to the http.Handler that we supply as the second argument. In our case, it is the built-in http.FileServer.</p><p>The http.FileServer function builds an http.Handler that will serve an entire directory of files and figure out which file to serve based on the request path. We told the FileServer to serve the current working directory with http.Dir(&quot;.&quot;).</p><p>If we go to <em>localhost:8080/main.go</em> in our web browser, we’ll see what’s inside our main.go file. With just one line of Go code, we can run this program from any folder and turn our computer into a simple server that shares files, like a tree of files, with others.</p><p>Checkout the project — <a href="https://github.com/Rajdeep-Das/go-networking">Rajdeep-Das/go-networking: Go Lang Networking Stand Lib &amp; Cloud Native Networking Projects (github.com)</a></p><p>Happy reading 📖. 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f771c333dbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run C# REPL in Terminal]]></title>
            <link>https://rajdeep-das.medium.com/run-c-repl-in-terminal-9c937a65b2f1?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c937a65b2f1</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 16:54:48 GMT</pubDate>
            <atom:updated>2023-07-10T16:54:48.079Z</atom:updated>
            <content:encoded><![CDATA[<p>A command line C# REPL with syntax highlighting — interactively explore the language, libraries, and Nuget packages.</p><h3>C# REPL</h3><p>A cross-platform command line <a href="https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop">REPL</a> for the rapid experimentation and exploration of C#. It supports IntelliSense, installing NuGet packages, and referencing local .NET projects and assemblies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANiPyLXGlIKbUEsmjsqnaA.png" /><figcaption>Demo</figcaption></figure><h3>Installation</h3><p>C# REPL is a .NET 7 global tool and runs on Windows, Mac OS, and Linux. It can be installed via:</p><pre>dotnet tool install -g csharprepl</pre><p>If you’re running on Mac OS Catalina (10.15) or later, follow any additional directions on the screen. You may need to update your PATH variable to use .NET global tools.</p><p>After installation is complete, run csharprepl to begin. C# REPL can be updated via dotnet tool update -g csharprepl.</p><h3>Usage</h3><p>Type some C# into the prompt and press Enter to run it. The result, if any, will be printed:</p><pre>&gt; Console.WriteLine(&quot;Hello World&quot;)<br>Hello World</pre><pre>&gt; DateTime.Now.AddDays(8)<br>[6/7/2021 5:13:00 PM]</pre><p>To evaluate multiple lines of code, use Shift+Enter to insert a new line:</p><pre>&gt; var x = 5;<br>  var y = 8;<br>  x * y</pre><p>Additionally, if the statement is not a “complete statement” a newline will automatically be inserted when Enter is pressed. For example, in the below code, the first line is not a syntactically complete statement, so when we press enter we’ll go down to a new line:</p><pre>&gt; if (x == 5)<br>  | // caret position, after we press Enter on Line 1</pre><p>Finally, pressing Ctrl+Enter will show a “detailed view” of the result. For example, for the DateTime.Now the expression below, on the first line we pressed Enter, and on the second line we pressed Ctrl+Enter to view the more detailed output:</p><pre>&gt; DateTime.Now // Pressing Enter shows a reasonable representation<br>[5/30/2021 5:13:00 PM]</pre><pre>&gt; DateTime.Now // Pressing Ctrl+Enter shows a detailed representation<br>[5/30/2021 5:13:00 PM] {<br>  Date: [5/30/2021 12:00:00 AM],<br>  Day: 30,<br>  DayOfWeek: Sunday,<br>  DayOfYear: 150,<br>  Hour: 17,<br>  InternalKind: 9223372036854775808,<br>  InternalTicks: 637579915804530992,<br>  Kind: Local,<br>  Millisecond: 453,<br>  Minute: 13,<br>  Month: 5,<br>  Second: 0,<br>  Ticks: 637579915804530992,<br>  TimeOfDay: [17:13:00.4530992],<br>  Year: 2021,<br>  _dateData: 9860951952659306800<br>}</pre><p>A note on semicolons: C# expressions do not require semicolons, but <a href="https://stackoverflow.com/questions/19132/expression-versus-statement">statements</a> do. If a statement is missing a required semicolon, a newline will be added instead of trying to run the syntactically incomplete statement; simply type the semicolon to complete the statement.</p><pre>&gt; var now = DateTime.Now; // assignment statement, semicolon required</pre><pre>&gt; DateTime.Now.AddDays(8) // expression, we don&#39;t need a semicolon<br>[6/7/2021 5:03:05 PM]</pre><p>When you’re done with your session, you can type exit or press Ctrl+D to exit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c937a65b2f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Project Planning For Small Teams]]></title>
            <link>https://rajdeep-das.medium.com/effective-project-planning-for-small-teams-dd244586c560?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd244586c560</guid>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Fri, 12 May 2023 17:19:58 GMT</pubDate>
            <atom:updated>2023-05-12T17:19:58.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zXZw43mAieOt6sHM" /><figcaption>Photo by <a href="https://unsplash.com/@alvarordesign?utm_source=medium&amp;utm_medium=referral">Alvaro Reyes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Big or small, every project deserves a plan! Here’s how even the smallest teams can achieve great results with effective project planning…</p><p>Project planning for very small teams can be a unique challenge, as there may be limited resources and personnel to allocate to the project. However, even small teams can benefit from effective project planning to ensure that tasks are completed efficiently and on time.</p><p>When planning a project for a small team, it’s important to focus on the essentials. Start by defining the project goals and scope, and identifying the tasks that need to be completed to achieve those goals.</p><p>Next, estimate the time and resources required for each task and determine a realistic timeline for completion.</p><blockquote>Don’t do optimistic eager, unrealistic time estimation. This is for your own team not for your client. remember that.</blockquote><p>One key advantage of working with a small team is the ability to communicate and collaborate more easily. Regular check-ins and meetings can help ensure everyone is on the same page and can help identify and address any potential issues early on.</p><p>It’s also important to be flexible and adaptable in project planning for small teams. This may mean adjusting timelines or reprioritizing tasks as needed to account for unexpected challenges or changing circumstances.</p><p>Ultimately, effective project planning for small teams is all about being organized, focused, and collaborative. By leveraging the right tools and strategies, even the smallest teams can achieve great results and deliver successful projects.</p><p>In Summary</p><p><strong>Do:</strong></p><p>1. Define clear project goals and scope<br>2. Identify and prioritize tasks required to achieve those goals<br>3. Estimate the time and resources needed for each task<br>4. Communicate and collaborate regularly with team members<br>5. Stay flexible and adaptable as needed<br>6. Celebrate milestones and successes to keep the team motivated</p><p><strong>Don’t:</strong></p><p>1. Overcomplicate the planning process with unnecessary details<br>2 Neglect to communicate regularly with team members<br>3. Assume that everything will go according to plan — be prepared to adjust as needed<br>4. Fail to celebrate milestones and successes<br>5. Get too caught up in minor details at the expense of the big picture</p><p>I have attached a simple Google sheet for project planning. You Can Try For Personal Projects or For Small Teams.</p><p><a href="https://rajdeepdasindia.gumroad.com/l/simpe-project-plan-sheet">Simple Project Plan Template - Google Sheet</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd244586c560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js app dir and Route handlers http basic auth]]></title>
            <link>https://rajdeep-das.medium.com/next-js-app-dir-and-route-handlers-http-basic-auth-e0d0edb1851?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0d0edb1851</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Thu, 11 May 2023 17:36:23 GMT</pubDate>
            <atom:updated>2023-05-11T17:36:23.261Z</atom:updated>
            <content:encoded><![CDATA[<p>How to add HTTP basic auth in next.js 13.4 app dir and using route handlers, middleware.</p><p>Basic Authentication should be distinct from conventional username and password authentication based solely on its name. It is, in fact, a component of the HTTP protocol as defined by the <a href="https://www.rfc-editor.org/rfc/rfc7617.html"><strong>RFC7617</strong></a>, which provides comprehensive information about its workings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urousx8DqfiIrkffJL87Pw.png" /><figcaption>HTTP Basic Auth Native Support</figcaption></figure><p>All the browsers have native support for <strong>HTTP Basic Authentication</strong>.</p><p>When the browser first requests the server, the server tries to check the availability of the Authorization header in the request. Because it is the first request, no Authorization header is found in the request. So the server responds with the 401 Unauthorized response code and also sends the WWW-Authenticate header with the value set to Basic, which tells the browser that it needs to trigger the basic authentication flow.</p><pre>export async function GET(request: Request) {<br>  return new Response(&quot;Authentication Required!&quot;, {<br>    status: 401,<br>    headers: {<br>      &quot;WWW-Authenticate&quot;: &quot;Basic realm=&#39;private_pages&#39;&quot;,<br>    },<br>  });<br>}</pre><p>First, create a middleware.ts file to intercept all HTTP Requests to perform authentication checks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDCypZcKE7h6pUyDzZ1-Xw.png" /><figcaption>Middleware File</figcaption></figure><pre>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br><br>export const config = {<br>  matcher: [&quot;/&quot;, &quot;/index&quot;],<br>};<br><br>export function middleware(req: NextRequest) {<br>  const basicAuth = req.headers.get(&quot;authorization&quot;);<br>  const url = req.nextUrl;<br><br>  if (basicAuth) {<br>    const authValue = basicAuth.split(&quot; &quot;)[1];<br>    const [user, pwd] = atob(authValue).split(&quot;:&quot;);<br><br>    const validUser = process.env.BASIC_AUTH_USER;<br>    const validPassWord = process.env.BASIC_AUTH_PASSWORD;<br><br>    if (user === validUser &amp;&amp; pwd === validPassWord) {<br>      return NextResponse.next();<br>    }<br>  }<br><br>  url.pathname = &quot;/api/auth&quot;;<br><br>  return NextResponse.rewrite(url);<br>}</pre><p>Then create a directory in <strong><em>app/api/auth </em></strong>like the below screenshot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ut7CietFDqUWxNOU8GuxUw.png" /><figcaption>Api route to handle auth error</figcaption></figure><pre>export async function GET(request: Request) {<br>  return new Response(&quot;Authentication Required!&quot;, {<br>    status: 401,<br>    headers: {<br>      &quot;WWW-Authenticate&quot;: &quot;Basic realm=&#39;private_pages&#39;&quot;,<br>    },<br>  });<br>}</pre><p>I’m reading auth valid credentials from the <em>.env</em> file</p><pre>#Basic Auth<br>BASIC_AUTH_USER=admin@1<br>BASIC_AUTH_PASSWORD=admin@!224</pre><p>That’s it. You are done. Now Run the app and enjoy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0d0edb1851" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Architecture for Full-Stack Engineer — Part 1]]></title>
            <link>https://rajdeep-das.medium.com/software-architecture-for-full-stack-engineer-part-1-e2cc81c2a8ba?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2cc81c2a8ba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 16:50:18 GMT</pubDate>
            <atom:updated>2023-04-30T16:50:18.239Z</atom:updated>
            <content:encoded><![CDATA[<h3>Software Architecture for Full-Stack Engineer — Part 1</h3><p>Software architecture for full-stack engineers or independent consultants who build an end to end solutions for business.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kzk0EUw_6wmSIeLY2OdGmw.png" /><figcaption>Architecture</figcaption></figure><p>I’m going to start with Architecture Tradeoff Analysis Method because everything in software architecture is a <em>trade-off</em>. If we think we have discovered something that isn’t a trade-off, we have more likely not identified the trade-off.</p><p><strong>ATAM </strong>helps software architects assess both some generic and specific concerns by assessing design choices against software <strong><em>quality</em></strong> attributes to meet some quality goals.</p><blockquote>Quality in software = fit for purpose + fit for use</blockquote><p><strong>fit for purpose </strong>means that what was developed resembles the functional requirements, while <strong>fit for use </strong>means that what was developed works reliably.</p><p><em>Example</em>: if you buy a smartphone 📱, you expect its basic functionality like calls can be done reliably, Indeed, a phone that would call optimally without noise or network issues but encounters breakdown every 1 week. That would be disappointing. That is why quality is the combination of these two things<strong> fit for purpose &amp; fit for use</strong>.</p><p><strong>Sensitivity points </strong>and <strong>trade-off points </strong>suggest to software architects where to focus their attention.</p><ul><li><strong>Scalability</strong>: The level of parallelism <em>might be sensitive </em>to the number of queues and/or partitions defined in the message broker.</li><li><strong>Performance</strong>: Latency <em>might be sensitive </em>to the application protocol we choose (for example, <strong>HyperText Transfer Protocol 1 </strong>(<strong>HTTP/1</strong>) or HTTP/2).</li><li><strong>Security</strong>: The risk of data leakage <em>might be sensitive </em>to the level of encryption applied to data at rest.</li><li><strong>Availability</strong>: Backends <em>might be sensitive </em>to the application protocol we choose (for example, HTTP/1 or HTTP/2).</li></ul><p><strong>Trade-off points: </strong>We have two different quality attributes (<em>performance</em> and <em>availability</em>) that could be significantly impacted by the choice of the protocol we make. That is a <em>trade-off point </em>because opting for HTTP/2 has a positive impact on performance (improved latency) but a potentially negative one on availability. (Assume our backend load balancer is layer 4 and not aware of the HTTP protocol, that can’t be reliable in our case)</p><blockquote><strong>Layer 4 load balancing</strong> uses information defined at the networking <em>transport</em> layer (Layer 4 — <strong>TCP</strong> &amp; <strong>UDP</strong>) as the basis for deciding how to distribute client requests across a group of servers. For Internet traffic specifically, a Layer 4 load balancer bases the load-balancing decision on the source and destination IP addresses and ports recorded in the packet header, without considering the contents of the packet.</blockquote><p>The reason behind this is that most load balancers are still layer-4 (<strong>Transmission Control Protocol/Internet Protocol </strong>(<strong>TCP/IP</strong>)) and do not understand layer-7 (in our case, HTTP/1 or HTTP/2), meaning that they will fail to properly load-balance HTTP/2 (used under the hood by the popular <strong>Google remote procedure call </strong>(<strong>gRPC</strong>)) because existing clients will keep sending their requests to the same backend, irrespective of whether that backend is healthy or on the verge of becoming unhealthy.</p><p>So, to make a proper design decision, in this case, we would need to also consider our load balancers and make sure they are compatible with such a decision. If they are not, we might reconsider the protocol we want to use. If we keep using HTTP/2 despite our old-school load balancers, we end up with a <strong>risk</strong>.</p><p>ATAM(<strong>Architecture Tradeoff Analysis Method) </strong>defines risks as potentially problematic design decisions.</p><p>When building an application or a system, you always encounter <strong>functional requirements </strong>(<strong>FRs</strong>) and <strong>non-functional requirements </strong>(<strong>NFRs</strong>). FRs are described by business users and business analysts, and they describe the features that must be developed or made available. NFRs are usually expected, but not directly expressed by the business.</p><p>Every user wants a performant, reliable, and always-available application. Similarly, every user assumes that the application/system is secure and appreciates their privacy, but all of this comes at a price, and the extent to which you want to respond to these NFRs will impact the cost and time. The systems you integrate with, the cloud, the hosting platform you choose to host the asset, and many other factors could make it hard to achieve the NFRs.</p><p>Let’s talk about SLAs(<strong>Service-level agreements).</strong>In big organizations, such SLAs are mainstream, even for internal customers.</p><blockquote>SLA — <strong>Recovery Time Objective </strong>(<strong>RTO</strong>) + <strong>Recovery Point Objective </strong>(<strong>RPO</strong>)</blockquote><p>These two attributes say a lot about the expected availability and level of resilience.</p><p>With an RTO of 3 business days, we clearly understand that the business is not too concerned by a system outage. Conversely, an RTO of 10 minutes directly sets a high priority on the availability quality attribute. Read more about <a href="https://www.cio.com/article/274740/outsourcing-sla-definitions-and-solutions.html">SLA</a>.</p><p>TL;DR</p><ul><li>Software architecture involves trade-offs between various quality attributes such as scalability, performance, security, and availability.</li><li><strong>The architecture Tradeoff Analysis Method (ATAM)</strong> helps assess these trade-offs by evaluating design choices against quality goals.</li><li><strong>Non-functional requirements (NFRs)</strong> such as performance, reliability, security, and availability are important, but achieving them comes at a cost.</li><li><strong>Service-level agreements (SLAs)</strong> set expectations for availability and resilience, with attributes like Recovery Time Objective (RTO) and Recovery Point Objective (RPO) indicating the level of priority for availability.</li><li>Proper consideration of all these factors is necessary for effective software architecture design.</li></ul><p>The next Part Will be Coming Soon .. Stay Tuned Thank you 😊 .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2cc81c2a8ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microeconomics for general people - 1]]></title>
            <link>https://rajdeep-das.medium.com/microeconomics-for-general-people-1-d1dc3b7a8870?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1dc3b7a8870</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 12:03:20 GMT</pubDate>
            <atom:updated>2023-04-29T12:03:20.692Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how the personal, household, business economic &amp; finance works.</em></p><p>I think everyone should learn the basic concept of microeconomics to manage and understand their household, finance, and business, or just for general knowledge and love of learning.</p><p>Microeconomics focuses on how individuals, households, and firms make those decisions.</p><p>Economic resources are scarce. Faced with this scarcity, we must choose how to allocate our resources.</p><p>Economics is the study of how societies choose to do that.</p><p><strong>Scarcity: </strong>The fact is that there is a limited amount of resources to satisfy unlimited wants — e.g. limited amount of land to build houses 🏠 .</p><p><strong>Economics resources: </strong>The main 4 things we need to produce goods and services. For example — land, labor, capital, and technology.</p><p>Here <strong>Land</strong> means raw materials like — fish, soil, minerals, and energy resources.</p><p><strong>Labor</strong> means the effort put out by workers in the creation of goods and services. The number of employees and hours worked etc.</p><p><strong>Capital</strong> Physical goods that are produced and used to produce other goods.</p><p>Examples of <em>capital</em> would be machinery, technology, tools, etc</p><p>Here<strong> Technology </strong>(<strong>entrepreneurship</strong>) means — The ability to combine other productive resources into goods and services.</p><h3><strong>Economic Model</strong></h3><p>Economic models are a way of taking complicated ideas and events, and then breaking them down into their most important characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kijGcQvC2aqpa3BNs-MC_g.png" /><figcaption>Economic Model</figcaption></figure><p>Economists rely on models because it’s impossible to capture the full complexity of human interaction.</p><p>A <strong>model</strong> is a simplification of a concept or process that is used to better understand that process. Like assuming and neglecting other variables, real-world entity to simplify things.</p><p>For example, a map is a model of how roads are laid out and where they intersect. There are lots of things we removed to develop the map. Only our intention information (like direction ) that is required is present.</p><p><strong>TL;DR</strong></p><ol><li><strong>Microeconomics: </strong>focuses on how individuals, households, and firms make resource allocation decisions.</li><li><strong>Economics resources: </strong>Land, Labor, Capital, and Technology.</li><li><strong>Scarcity</strong>: Limited number of resources that has unlimited want. That’s Why proper resource allocation is required.</li><li><strong>Economic Models</strong>: simplification of a concept or process that is used to better understand the resource allocation process.</li></ol><p>If you enjoy the article, please follow and give a clap 👏 . Thank you 😊 .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1dc3b7a8870" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vite 4.0 Takes Development to a Whole New Level: Faster, Smarter, and More Efficient]]></title>
            <link>https://rajdeep-das.medium.com/vite-4-0-takes-development-to-a-whole-new-level-faster-smarter-and-more-efficient-42bb58109ad4?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/42bb58109ad4</guid>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 08:26:35 GMT</pubDate>
            <atom:updated>2023-01-11T08:26:35.339Z</atom:updated>
            <content:encoded><![CDATA[<p>Experience Lightning-Fast Development with Vite 4.0 and React: The Perfect Match</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4d3XNLeulg9X8lOR" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Vite is a new front-end development tool that addresses the performance issues associated with current JavaScript-based toolings like webpack, Rollup, and Parcel. By leveraging the availability of native ES modules in the browser and utilizing JavaScript tools written in compile-to-native languages.</p><p>Vite aims to improve developers’ productivity and happiness by reducing the wait times associated with spinning up a dev server and reflecting file edits in the browser, often seen in large-scale projects with thousands of modules.</p><p>Vite, the front-end development tool, saw tremendous growth and adoption over the past five months. The number of npm downloads per week has doubled from 1 million to 2.5 million and usage among the community in the Jamstack Conf survey jumped from 14% to 32% with a high satisfaction score of 9.7.</p><p>Vite-powered frameworks such as <strong>Astro 1.0</strong>, <strong>Nuxt 3</strong>, <strong>SvelteKit</strong>, <strong>Solid Start</strong>, and <strong>Qwik </strong>are also growing and collaborating. Storybook, Deno, and <strong>Nx</strong> also announced first-class support and investment in the Vite ecosystem. This upward trend is set to continue with <strong>Vitest</strong> adoption also rising, it’s expected to represent half of Vite’s npm downloads soon.</p><p><strong>Let&#39;s Start experimenting with Vite 4.</strong></p><pre>pnpm create vite</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfOPx9ZXJp390TIuUVSyiQ.png" /><figcaption>React Vite Template</figcaption></figure><h3>New React plugin using SWC during development<a href="https://vitejs.dev/blog/announcing-vite4.html#new-react-plugin-using-swc-during-development">#</a></h3><p><a href="https://swc.rs/">SWC</a> is now a mature replacement for <a href="https://babeljs.io/">Babel</a>, especially in the context of React projects. SWC’s React Fast Refresh implementation is a lot faster than Babel, and for some projects, it is now a better alternative. From Vite 4, two plugins are available for React projects with different tradeoffs. We believe that both approaches are worth supporting at this point, and we’ll continue to explore improvements to both plugins in the future.</p><p>Learn more about SWC at <a href="https://swc.rs/">https://swc.rs/</a></p><h3>@vitejs/plugin-react<a href="https://vitejs.dev/blog/announcing-vite4.html#vitejs-plugin-react">#</a></h3><p><a href="https://github.com/vitejs/vite-plugin-react">@vitejs/plugin-react</a> is a plugin that uses esbuild and Babel, achieving fast HMR with a small package footprint and the flexibility of being able to use the Babel transform pipeline.</p><h3>@vitejs/plugin-react-swc (new)<a href="https://vitejs.dev/blog/announcing-vite4.html#vitejs-plugin-react-swc-new">#</a></h3><p><a href="https://github.com/vitejs/vite-plugin-react-swc">@vitejs/plugin-react-swc</a> is a new plugin that uses esbuild during build but replaces Babel with SWC during development. For big projects that don’t require non-standard React extensions, cold start and Hot Module Replacement (HMR) can be significantly faster.</p><p>Let’s switch our project to use SWC (plugin-react-swc)</p><pre>pnpm i -D @vitejs/plugin-react-swc</pre><p>Change import in vite.config.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AogzILUL25eVd2Nc_8ko2w.png" /><figcaption>vite.config.js</figcaption></figure><pre>import { defineConfig } from &#39;vite&#39;<br>//import react from &#39;@vitejs/plugin-react&#39;<br>import react from &quot;@vitejs/plugin-react-swc&quot;;<br><br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>  plugins: [react()],<br>})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kY-Sv6AUyxrFDrr-NppKw.png" /><figcaption>React Vite SWC Project</figcaption></figure><h3>Official Caveats (From Github)</h3><p><a href="https://github.com/vitejs/vite-plugin-react-swc">https://github.com/vitejs/vite-plugin-react-swc</a></p><p>This plugin has limited options to enable good performances and be transpiler agnostic. Here is the list of non-configurable options that impact runtime behavior:</p><ul><li><a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier">useDefineForClassFields</a> is always activated, as this matches the current ECMAScript spec</li><li>jsx runtime is always automatic</li><li>In development:</li><li>esbuild is disabled, so the <a href="https://vitejs.dev/config/shared-options.html#esbuild">esbuild configuration</a> has no effect</li><li>target is es2020</li><li>JS files are not transformed</li><li>tsconfig is not resolved, so properties other than the ones listed above behave like TS defaults</li></ul><h3>Importing CSS as a String (From Official Website)</h3><p>In Vite 3, importing the default export of a .css file could introduce a double loading of CSS.</p><pre>import cssString from &#39;./global.css&#39;</pre><p>This double loading could occur since a .css file will be emitted and it&#39;s likely that the CSS string will also be used by the application code — for example, injected by the framework runtime. From Vite 4, the .css default export <a href="https://github.com/vitejs/vite/issues/11094">has been deprecated</a>. The ?inline query suffix modifier needs to be used in this case, as that doesn&#39;t emit the imported .css styles.</p><pre>import stuff from &#39;./global.css?inline&#39;</pre><h3>Environment Variables (From Official Website)</h3><p>Vite now uses dotenv 16 and dotenv-expand 9 (previously dotenv 14 and dotenv-expand 5). If you have a value including # or `, you will need to wrap them with quotes.</p><pre>-VITE_APP=ab#cd`ef<br>+VITE_APP=&quot;ab#cd`ef&quot;</pre><p>For more details, see the <a href="https://github.com/motdotla/dotenv/blob/master/CHANGELOG.md">dotenv</a> and <a href="https://github.com/motdotla/dotenv-expand/blob/master/CHANGELOG.md">dotenv-expand changelog</a>.</p><h4>Summary</h4><p>Vite is a lightweight development server that is designed to be fast and easy to use. The latest version, Vite 4.0, brings a number of new features and improvements that make it an even more powerful tool for building web applications. Here are a few reasons why developers might want to give Vite 4.0 a try:</p><ul><li><strong>Speed</strong>: Vite is incredibly fast, thanks to its native ES module support and its ability to perform hot module replacement (HMR) without a webpack configuration. This makes development faster and more efficient, as you don’t have to wait for long build times or manually refresh the page to see your changes.</li><li><strong>Simplicity</strong>: Vite is easy to set up and use, with minimal configuration required. This means developers can get up and running quickly, without having to spend a lot of time on setup. Additionally, since it’s built on top of native ES modules, it requires minimal configuration and dependencies.</li><li><strong>Flexibility</strong>: Vite is highly customizable, with a range of options and plugins available. This allows developers to tailor their workflow to their specific needs. Additionally, Vite 4.0 has introduced a rollup and webpack plugin for even more flexibility.</li><li><strong>Great Community</strong>: Vite has a growing community of developers who contribute to the project and also provides a lot of plugins that you can use to enhance your development experience.</li></ul><p>Given these benefits, developers who are looking for a fast, easy-to-use, and flexible development server should definitely give Vite 4.0 a try.</p><p><strong>Reference:</strong></p><ol><li><a href="https://vitejs.dev/blog/announcing-vite4.html">https://vitejs.dev/blog/announcing-vite4.html</a></li><li><a href="https://swc.rs/">https://swc.rs/</a></li></ol><p><a href="https://www.linkedin.com/in/rajdeep-das-india/">Rajdeep Das | LinkedIn</a></p><p><a href="https://rajdeep-das.com/">Software Developer | Rajdeep Software Engineering &amp; Consulting Services</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42bb58109ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Stack for Cost-Effective Architecture on AWS]]></title>
            <link>https://rajdeep-das.medium.com/serverless-stack-for-cost-effective-architecture-on-aws-52b31c5f49e?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b31c5f49e</guid>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 09:36:39 GMT</pubDate>
            <atom:updated>2023-01-02T09:36:39.393Z</atom:updated>
            <content:encoded><![CDATA[<p>Considering serverless stack for simplified cost-effective app development</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4wXDp7HqdKZpLX2V" /></figure><p>Serverless computing is a cloud computing model that allows developers to build and deploy applications more quickly and cost-effectively than traditional approaches. Serverless Stack is a combination of cloud-native technologies and best practices that enable developers to take advantage of the scalability, security, and cost benefits offered by cloud platforms such as Amazon Web Services (AWS). In this blog, we’ll discuss the benefits of using Serverless Stack on AWS and offer tips for SMEs and entrepreneurs building cloud-native applications.</p><h3>Introduction</h3><p>Serverless Stack is a combination of cloud-native technologies and best practices that enable developers to build and deploy applications more quickly and cost-effectively than traditional approaches. It leverages serverless computing, which is a cloud computing model that allows developers to build and deploy applications without managing servers or infrastructure. With serverless computing, developers only pay for the resources they use, making it a more cost-effective approach than traditional server-based architectures.</p><p>The benefits of using a Serverless Stack include:</p><ul><li>Low cost — Serverless Stack can significantly reduce the cost of deploying and running applications as compared to traditional approaches.</li><li>Easy to scale — Serverless Stack makes it easy to scale applications quickly and easily without the need for additional hardware or software.</li><li>Flexible — Serverless Stack allows developers to quickly adjust their architecture to meet changing needs without having to make costly changes to their existing code.</li><li>Automation — Serverless Stack automates many of the tedious tasks involved in deploying and maintaining applications, allowing developers to focus on building new features instead.</li></ul><h3>Solution Architecture</h3><p>AWS provides a variety of services, including computing, storage, databases, analytics, and machine learning, which are all available to leverage when creating a cost-effective architecture on AWS. To take advantage of these services, developers can utilize AWS services such as Lambda, DynamoDB, and API Gateway to create a serverless architecture that is cost-effective and can scale with demand. Additionally, developers can leverage AWS services such as CloudFormation to automate the deployment of their applications. Finally, developers can also utilize AWS services such as CloudWatch for monitoring and alerting.</p><h3>Development</h3><p>When building cloud-native applications, it’s important to understand the advantages of using microservices. Microservices are small, independently deployable components that can be combined to create larger, more complex applications. The advantages of using microservices include:</p><ul><li>Faster development — Microservices allow teams to develop and deploy code more quickly than traditional monolithic architectures.</li><li>Easier maintenance — Microservices also make it easier to maintain and update code over time, since each microservice can be updated independently of other services.</li></ul><p>To ensure secure access to APIs hosted on AWS, developers can utilize Amazon API Gateway. API Gateway is a service that provides secure access to APIs hosted on AWS. It allows developers to control who has access to their APIs and how they can access them.</p><h3>Conclusion</h3><p>In conclusion, Serverless Stack is a combination of cloud-native technologies and best practices that enable developers to build and deploy applications more quickly and cost-effectively than traditional approaches. The benefits of using a Serverless Stack include low cost, easy scalability, flexibility, and automation. To create a cost-effective architecture on AWS, developers should utilize AWS services such as Lambda, DynamoDB, API Gateway, CloudFormation, and CloudWatch; use microservices; take advantage of the scalability, security, and cost benefits offered by cloud platforms; and automate the deployment of their application with tools such as CloudFormation. SMEs and entrepreneurs building cloud-native applications should keep these tips in mind when designing their architecture.</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/serverless-stack-cost-effective-architecture-aws-rajdeep-das"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b31c5f49e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filters in ASP.NET Core]]></title>
            <link>https://rajdeep-das.medium.com/filters-in-asp-net-core-4010e656c28a?source=rss-faef5f8eef5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4010e656c28a</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rajdeep Das]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 19:18:26 GMT</pubDate>
            <atom:updated>2022-12-14T19:18:26.604Z</atom:updated>
            <content:encoded><![CDATA[<p>How To Create Custom Action Filter In ASP.NET 6 &amp; Above</p><p><em>Filters</em> in ASP.NET Core allow code to run before or after specific stages in the request processing pipeline.</p><p><strong>Inbuild Filters</strong></p><ul><li>Authorization prevents access to resources a user isn’t authorized for.</li><li>Response caching, short-circuiting the request pipeline to return a cached response.</li></ul><p><strong>Custom Filters</strong></p><p>Custom filters can be created to handle cross-cutting concerns. Examples of cross-cutting concerns include error handling, caching, configuration, authorization, and logging. Filters avoid duplicating code. For example, an error-handling exception filter could consolidate error handling.</p><p>There are many filters in ASP.NET Core, but we will focus on Action Filters</p><p><a href="https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-7.0#action-filters">Action filters</a>:</p><ul><li>Run immediately before and after an action method is called.</li><li>Can change the arguments passed into action.</li><li>Can change the result returned from the action.</li></ul><p><strong>How Filters Works</strong></p><p>Filters run within the ASP.NET Core action invocation pipeline, sometimes referred to as the filter pipeline. The filter pipeline runs after ASP.NET Core selects the action to execute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*S-NXC-_8zmtOeyhsk2FW7w.png" /><figcaption>ASP.NET Filters</figcaption></figure><p>We can implement Action Filters as synchronous and asynchronous through different interface definitions</p><p>We are going to build a SingleDeviceSessionCheck Filter for example</p><pre>using System;<br>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.AspNetCore.Mvc.Filters;<br>using Microsoft.AspNetCore.Mvc.Infrastructure;<br>using Microsoft.Extensions.Configuration;<br>using Microsoft.Extensions.Logging;<br><br>namespace MyService.UserApi.Filters<br>{<br>  public class SingleDeviceCheck : IActionFilter<br>  {<br>      private readonly IDeviceAccessRepository deviceAccessRepository;<br>      private readonly ILogger&lt;SingleDeviceCheck&gt; logger;<br>      private readonly IConfiguration configuration;<br>    <br>      /* Constructor for DI */ <br>      public SingleDeviceCheck(<br>      /* This Respository Containts logic for checking session in DB */<br>          IDeviceAccessRepository deviceAccessRepository,<br>          ILogger&lt;SingleDeviceCheck&gt; logger,<br>          IConfiguration configuration)<br>      {<br>          this.deviceAccessRepository = deviceAccessRepository;<br>          this.logger = logger;<br>          this.configuration = configuration;<br>      }<br>  }<br>   // our code before action executes<br>   public void OnActionExecuting(ActionExecutingContext context){}<br>   // our code after action executes<br>   public void OnActionExecuted(ActionExecutedContext context){}<br>}<br></pre><p>We need to implement our logic in these two methods, for my use case I required the onActionExecuting method.</p><pre>public void OnActionExecuting(ActionExecutingContext context)<br>{<br>  // Checking single device access ON or OFF (Feature Flag For Dev/Prod Test<br>  if (this.configuration[&quot;SD_ON_OFF&quot;].Equals(&quot;OFF&quot;)) { return; }<br><br>  // our code before action executes<br>  var deviceId = context.HttpContext.Request?.Headers[&quot;Device-Id&quot;];<br>  if (string.IsNullOrEmpty(deviceId.ToString()))<br>  {<br>      context.Result = new BadRequestObjectResult(&quot;Device-Id is empty&quot;);<br>      return;<br>  }<br>  // if same device login then permission granted<br>  // Read USER INFO From JWT Claims<br>  var email = context.HttpContext.User.FindFirst(&quot;https://xyz.com/email&quot;)?.Value;<br>  var deviceAccessData = deviceAccessRepository.GetActiveDeviceByEmailAsync(email).Result;<br>  if (deviceAccessData == null)<br>  {<br>      context.Result = new UnauthorizedObjectResult(new { status = false, message = &quot;Couldn&#39;t Find Your Device. Please Logout &amp; Login Again.&quot; })<br>      {<br>          StatusCode = 403<br>      };<br>      return;<br>  }<br>  if (!(deviceAccessData.DeviceId == deviceId.ToString() &amp;&amp; deviceAccessData?.IsActive == true))<br>  {<br>      logger.LogInformation(&quot;Device Failed To Pass {device} and {email}&quot;, deviceId, email);<br>      context.Result = new UnauthorizedObjectResult(new { status = false, message = &quot;You have already active in another device.\n Access Denied.&quot; })<br>      {<br>          StatusCode = 403<br>      };<br>      return;<br>  }<br>  else<br>  {<br>      logger.LogInformation(&quot;Device Pass {device} and {email}&quot;, deviceId, email);<br>  }<br>}</pre><p>Now we will register our Action Filter in Program. cs or Startup.cs</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>  services.AddDbContext&lt;MovieContext&gt;(options =&gt;<br>   options.UseSqlServer(Configuration.GetConnectionString(&quot;sqlConString&quot;)));<br>  //Filters <br>  services.AddScoped&lt;SingleDeviceCheck&gt;();<br>  services.AddControllers();<br>}</pre><p>Now we will use This Filter In Our Controller</p><pre>//Dev Test Only<br>[HttpGet(&quot;device&quot;)]<br>//Filter Code Run in Request Pipeline<br>[ServiceFilter(typeof(SingleDeviceCheck))]<br>public IActionResult CheckDevieID() {<br>    return Ok(&quot;Single Device ID Endpint Check&quot;);<br>}</pre><p><strong>Summary</strong></p><ol><li>Action Filter helps us to reuse code.</li><li>Run Some Common Logic In SPecific Controller or Methods In the Request Pipeline</li><li>A middleware can run for all requests while filters will only run for requests that reach the EndpointMiddleware</li><li>filters will only run on specified actions and controllers unless you register the filter globally in the startup. Since you have full access to the context you can also access the controller and action itself.</li></ol><p>I always recommend using Action Filters because they give us reusability in our code and cleaner code in our actions as well.</p><p><a href="https://rajdeep-das.com/">Software Developer | Rajdeep Software Engineering &amp; Consulting Services</a></p><p><a href="https://www.linkedin.com/in/rajdeep-das-india/">Rajdeep Das | LinkedIn</a></p><p>Thank You, happy reading 📖 , 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4010e656c28a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>