<?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 Kavishka Nimsara on Medium]]></title>
        <description><![CDATA[Stories by Kavishka Nimsara on Medium]]></description>
        <link>https://medium.com/@kavishkanimsara9919?source=rss-2113ecffc4d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7IKR64_ggxh2mFvL0bmgMw.png</url>
            <title>Stories by Kavishka Nimsara on Medium</title>
            <link>https://medium.com/@kavishkanimsara9919?source=rss-2113ecffc4d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:55:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kavishkanimsara9919/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[ Why Every SaaS Needs a Referral System to Boost Sales]]></title>
            <link>https://medium.com/@kavishkanimsara9919/why-every-saas-needs-a-referral-system-to-boost-sales-69a1909c2c00?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/69a1909c2c00</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[refferals]]></category>
            <category><![CDATA[marketing-strategies]]></category>
            <category><![CDATA[referral-marketing]]></category>
            <category><![CDATA[rewards]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Fri, 04 Jul 2025 15:49:19 GMT</pubDate>
            <atom:updated>2025-07-04T15:49:19.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*pVpYxyml8kYTOFsyFQ1OIA.png" /></figure><p>🚀 You’ve built a really useful SaaS product. Your users are happy, and things are working well, but growth feels a little slow. You’re putting in the work, but word isn’t spreading fast enough. That’s where a <strong>referral system</strong> comes in. Think of it as your secret weapon, a smart, friendly way to grow your user base through the people who already love what you do.</p><h3>What Is a Referral System?</h3><p>A referral system is a simple, win-win setup that encourages your current users to invite others to try your product. In return, both sides usually get something nice — a discount, a reward, or even just a “thank you” credit.</p><p>It’s like saying, “Hey 👋, if you tell your friend about us and they join, we’ll reward both of you 🎁.”</p><p>Referral marketing isn’t a new concept. Long before the internet, businesses thrived on <strong>word-of-mouth</strong> recommendations — whether it was a local tailor, a neighbourhood café, or a trusted auto mechanic. People naturally shared great experiences with others, and that trust was more powerful than any billboard or newspaper ad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*DTsCWi000BwOGghAjLb4eA.png" /><figcaption>Word-of-mouth marketing</figcaption></figure><p>As the digital world evolved, so did <strong>referral marketing</strong>. Today, it’s no longer just informal chatter; it’s a structured, strategic system — especially powerful in the SaaS space. With data, automation, and built-in tracking, modern referral systems allow companies to reward users for spreading the word and track results with precision.</p><h3>How It Works</h3><p>Let’s say <strong>Lisa</strong> is using your SaaS product and finds it super helpful. She refers her friend <strong>Mark</strong> using her unique referral link. <strong>Mark</strong> signs up, and boom — <strong>Mark</strong> gets 20% off his first month, and <strong>Lisa</strong> earns a $10 credit toward her next bill.</p><p>Now Mark is happy 😊. Lisa is happy 🎉. And you just got a high-quality new customer for a fraction of the cost of a paid ad 💰.</p><p>But it doesn’t stop there. If Mark also enjoys the product and refers a few of his friends, the cycle continues 🔁. Those friends might bring in even more users. What started as one happy customer turns into a chain reaction of trusted recommendations — each one helping you grow your sales, expand your user base, and build lasting loyalty 🔗.</p><h3>Why Referral Systems Matter for SaaS</h3><p>Referral marketing is more than just “nice to have.” It’s a powerful, efficient strategy that leverages satisfied users to bring in new ones, directly boosting your bottom line. Here’s how:</p><h3>1. Trust &amp; Credibility</h3><p>Think about the last software tool you adopted. Chances are, someone you trust recommended it. People naturally rely on peers, friends, or industry colleagues rather than advertisements. A referral system uses this inherent trust factor, making new users more comfortable saying “yes.”</p><h3>2. Cost-Efficient Growth</h3><p>Compared to other channels like paid ads, referrals significantly cut down on customer acquisition costs. You’re essentially turning your happiest users into your best marketers — without the heavy price tag.</p><h3>3. Higher Quality Users</h3><p>Referrals usually deliver customers who are already pre-qualified. They know what they’re getting into, reducing onboarding friction and increasing retention rates. Higher retention directly translates into increased customer lifetime value (LTV).</p><h3>4. Organic, Viral Growth</h3><p><strong>Word-of-mouth</strong> (or mouth-to-mouth) marketing is powerful, and referral systems amplify this effect. One user can lead to two, two can lead to four, creating exponential, sustainable growth without constantly increasing marketing budgets.</p><h3>5. Enhanced Customer Loyalty</h3><p>Offering incentives not only motivates users to refer others but also deepens their engagement with your product. Rewards like subscription discounts, premium features, or exclusive content create a sense of belonging and appreciation among existing users.</p><h3>How Referral Systems Compare to Other Marketing Strategies</h3><ul><li><strong>Paid Ads vs. Referrals:</strong> Running ads can bring quick traffic, but they’re expensive and results aren’t always guaranteed. With referrals, growth may start slower, but the users you gain tend to stick around and cost far less to acquire.</li><li><strong>Content Marketing vs. Referrals:</strong> Creating blogs, videos, or guides takes a lot of time and planning. Referrals, on the other hand, use your current users’ positive experiences to bring in new ones right away.</li><li><strong>Cold Outreach vs. Referrals:</strong> Reaching out to strangers through emails or messages often feels pushy and gets ignored. But when someone hears about your product from a friend, they’re much more likely to trust and try it</li></ul><h3>🛠️ Getting Started with Your Referral System</h3><p>Implementing a referral system doesn’t have to be complicated:</p><ul><li>Clearly define the rewards for both referrers and referees.</li><li>Ensure the referral process is simple and easy.</li><li>Promote your referral programme across your product, website, emails, and social media.</li></ul><p>If you’re not leveraging referrals, you’re leaving money on the table. Referral marketing isn’t just smart — it’s essential for SaaS businesses aiming for meaningful, sustainable growth.</p><p>Ready to turn your best users into your best salespeople? Start implementing your referral system today, and watch your SaaS product grow exponentially!</p><p>🙏 Thanks for reading! In the next article, I’ll walk you through how to implement your own referral system — from tools to code and everything in between. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69a1909c2c00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Stop Integrating APIs Manually — Let MCP Handle It All]]></title>
            <link>https://medium.com/@kavishkanimsara9919/stop-integrating-apis-manually-let-mcp-handle-it-all-7bb657850690?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb657850690</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 11:15:23 GMT</pubDate>
            <atom:updated>2025-06-03T13:02:56.995Z</atom:updated>
            <content:encoded><![CDATA[<h3>🛑 Stop Integrating APIs Manually — Let MCP Handle It All</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-W5JoDLPXGbbJvL11ue-gg.png" /></figure><h3>😩<strong>Tired of Complex API Integrations?</strong></h3><p>Manually connecting APIs is time-consuming, error-prone, and requires ongoing maintenance. Every new endpoint feels like a mini project, and even small changes can break things.</p><p>What if you could automate the entire process — <strong>without writing boilerplate code</strong> or<strong> managing request logic</strong>?</p><p>In this article, we’ll break down what <strong>MCP</strong> is, walk through an employee management example, and show how it makes it easier for apps to work with AI.</p><h3><strong>🚀 What Is MCP?</strong></h3><p><strong>MCP (</strong>Model Context Protocol<strong>)</strong> is an open protocol that standardizes how applications provide context to large language models (LLMs).</p><blockquote><em>📦 Think of MCP as the </em><strong><em>USB-C of AI applications</em></strong><em>.<br> “Just like USB-C connects devices to accessories with a single, universal interface, MCP connects apps to AI tools and data — </em><strong><em>seamlessly and reliably</em></strong><em>.” </em><a href="https://modelcontextprotocol.io/introduction">– <em>MCP Documentation</em></a></blockquote><p><strong>In simpler terms:</strong></p><p>MCP is a <strong>common language between your app and AI</strong>. It lets your AI tools (like ChatGPT or Claude) access the information they need — <strong>automatically</strong>, and without custom API calls every time.</p><h3><strong>🧱 MCP Architecture</strong></h3><p>Here’s how a typical MCP-based setup looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JSNNl8lFnRBFCkgs6da5A.png" /></figure><ul><li><strong>MCP Hosts</strong> — Apps like Claude or AI tools that want to get data or do tasks using MCP.</li><li><strong>MCP Clients</strong> — Helpers that connect the host to the right server</li><li><strong>MCP Servers</strong> — Small programs that know how to do specific jobs and follow MCP rules.</li><li><strong>Local Data Sources</strong> — Things on your computer, like files or databases the server can use.</li><li><strong>Remote Services</strong> — Online tools (like APIs) the server can talk to for more data.</li></ul><h3>🤖 How MCP Works</h3><p>MCP helps your AI apps talk to your data and tools, like Google Drive or Slack. Here’s how it works.</p><ul><li><strong>MCP servers</strong> connect to your files, tools, or services</li><li><strong>MCP clients</strong> run inside AI apps (like Claude) to link them to those servers.</li><li>When you give permission, your AI app finds the available servers.</li><li>The AI can then <strong>get data or take action</strong>, like reading a file or sending a message.</li><li>You can <strong>add new tools anytime</strong> — no need to change the AI app, just plug in a new MCP server.</li></ul><blockquote><em>It’s like plugging a new device into your computer — it just works.</em></blockquote><p>To make it easier to understand, let’s say you’re building an <strong>employee management system</strong> as an example.</p><h3>🧾 Traditional API Integration Example</h3><p>In a traditional setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUGXZq3dGyz9UXVAv5q9UA.png" /></figure><p><strong>📦 Traditional API Workflow (Without MCP)</strong></p><ol><li>The user opens the app</li><li>The app sends a request, e.g., GET /api/employee/e12345</li><li>The backend processes the request and returns a response</li><li>The UI displays the result</li></ol><p>While this works, it has some drawbacks:</p><ul><li>You need to <strong>build and maintain every endpoint</strong></li><li>Users or developers must <strong>know the exact API call to make</strong></li><li>You have to <strong>manually handle request and response logic</strong></li></ul><h3>🤖 MCP-Based Model Example</h3><p>Now, let’s imagine the same app, but powered by MCP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upqa6acJcFK8gg7OivW0aA.png" /></figure><p>🧠<strong> With MCP, the User Simply Asks the LLM:</strong></p><ul><li><em>“Give me the employee details for e12345”</em></li><li><em>“What’s the salary and position of e5021?”</em></li><li><em>“Show all employees hired in the last 6 months.”</em></li></ul><p><strong>MCP acts as the translator between the LLM and your app.</strong> It interprets the user’s natural language request, routes it to the appropriate backend logic, and then formats the response in a structured way that the LLM can understand and use effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*bq3RXYMkr5t6bbvLoOPMcQ.png" /><figcaption>Example of an LLM interacting with an MCP-powered application</figcaption></figure><h3>✅ Benefits of MCP</h3><p><strong>✔ AI-native interfaces</strong><br> Build natural, chat-style interfaces instead of rigid UIs.</p><p><strong>✔ Fewer endpoints, less code</strong><br> Your MCP server handles the routing, not your frontend.</p><p><strong>✔ Fast prototyping</strong><br> Connect tools and data to LLMs in minutes, not weeks.</p><h3>⚠️ Tradeoffs to Consider</h3><ul><li><strong>You still need to structure your data access layer</strong>.</li><li><strong>MCP is new</strong>, so documentation and community support are still growing.</li><li><strong>Not every app suits an LLM-style interface</strong>, especially when precision or speed is critical.</li></ul><h3>🛠 Build Your First MCP App</h3><p>This article is already getting long, so I’ll stop here for now.</p><p>In my next post, I’ll walk you through a <strong>step-by-step guide</strong> to building your own MCP-powered application — simply and effectively.</p><p>In the meantime, feel free to explore the <a href="https://modelcontextprotocol.io/quickstart/server"><strong>Official MCP Quickstart guide</strong></a> to get a head start.</p><p><strong>Stay tuned — exciting things are on the way!</strong></p><h3>✨ Final Thoughts</h3><p>MCP is changing the way we think about app integration. Instead of building rigid APIs, you can now let your AI tools <em>talk</em> directly to your data and services — with less effort and more flexibility.</p><p>Thanks for reading! 🙌<br> If you found this helpful, feel free to share, comment, or follow for more articles on LLMs, automation, and next-gen development tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb657850690" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make Your Localhost Accessible Globally Using ngrok: Just One Command!]]></title>
            <link>https://medium.com/@kavishkanimsara9919/how-to-make-your-localhost-accessible-globally-using-ngrok-just-one-command-312da037ae11?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/312da037ae11</guid>
            <category><![CDATA[tunnel]]></category>
            <category><![CDATA[ngrok]]></category>
            <category><![CDATA[localhost]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 14:36:29 GMT</pubDate>
            <atom:updated>2025-03-16T14:36:29.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ro42-lmDdC7EWaVxKDY23w.png" /></figure><p>Need to share a local web app, API, or service with teammates, clients, or testers worldwide? Ngrok is your solution. This guide explains how to securely expose your localhost to the internet in minutes—no complex setup or configurations needed. Just use a single command!</p><h3>What Is Ngrok? 🤔</h3><p>Ngrok (pronounced “en-grok”) is a tool that allows you to share a local web app or server with anyone on the internet. It creates a secure tunnel from your machine to a public URL, making it easy to showcase, test, or collaborate on projects without dealing with complex network setups or configurations.</p><h3>How Ngrok Works 🛠️</h3><p>When you run ngrok, it creates a secure tunnel between your local machine and ngrok’s cloud servers. These servers generate a unique public URL (e.g., https://abc123.ngrok-free.dev), which allows anyone on the internet to access your locally hosted application.</p><p><strong>Here’s how it works:</strong></p><ol><li><strong>Ngrok connects to its cloud servers</strong> and requests a public URL.</li><li><strong>The public URL is assigned</strong> and mapped to your local server’s port (e.g., <a href="http://localhost:3000).">http://localhost:3000).</a></li><li><strong>When someone accesses the public URL</strong>, ngrok securely forwards the request to your local machine.</li><li><strong>Your application responds</strong>, and ngrok routes the response back to the user through the tunnel.</li></ol><p>This process allows you to test, share, or demo your local projects without deploying them online or configuring complex network settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5vFVqqzGkREdHUwD5q_gQ.png" /></figure><h3>Step-by-Step Setup Guide 🚀</h3><h4>1. Install Ngrok</h4><ul><li>Visit <a href="https://ngrok.com/download">ngrok.com/download</a> and download the appropriate version for your OS.</li><li>Extract the file and add Ngrok to your system’s PATH (for easy terminal access).</li></ul><h4>2. Authenticate Your Account</h4><ul><li>Sign up for a free account at <a href="https://ngrok.com/">ngrok.com</a>.</li><li>Retrieve your authtoken from the dashboard, then run:</li></ul><pre>ngrok config add-authtoken &lt;YOUR_AUTH_TOKEN&gt;  </pre><p>This links Ngrok to your account, enabling persistent tunnels and usage analytics.</p><h4>3. Start the Tunnel</h4><p>Run this command in your terminal:</p><pre>ngrok http &lt;LOCAL_PORT&gt;  </pre><p>The &lt;LOCAL_PORT&gt; is the port number on which your local web server or application is running. When you start a web server on your machine, it usually runs on a specific port (e.g., 3000, 8000, or 5000). Ngrok uses this port to create a secure tunnel and provide a public URL that others can use to access your local server.</p><h4>Example:</h4><p>If you’re running a Node.js app on port <strong>3000</strong>, use:</p><pre>ngrok http 3000  # For a Node.js app on port 3000  </pre><h4><strong>4. Viewing the ngrok Console Output</strong></h4><p>After running the ngrok http &lt;LOCAL_PORT&gt; command, you’ll see output similar to this in your terminal:</p><pre>ngrok                                                                   (Ctrl+C to quit)<br><br>Session Status                online<br>Account                       inconshreveable (Plan: Free)<br>Version                       3.0.0<br>Region                        United States (us)<br>Latency                       78ms<br>Web Interface                 http://127.0.0.1:4040<br>Forwarding                    https://84c5df474.ngrok-free.dev -&gt; http://localhost:8080<br><br>Connections                   ttl     opn     rt1     rt5     p50     p90<br>                              0       0       0.00    0.00    0.00    0.00</pre><h3>Accessing Your Local App🚀</h3><p>Open the <strong>Forwarding URL </strong><em>(e.g., https://84c5df474.ngrok-free.dev)</em> in a browser, and you’ll see your locally hosted web application live on the internet!</p><p>💡 <strong>Share this URL</strong> with teammates, clients, or testers so they can access your project from anywhere. 🚀</p><h3>Use Cases and Benefits💡</h3><ol><li><strong>Demo Day Ready</strong> <br>Share live prototypes with stakeholders without deploying to a staging server.</li><li><strong>Webhook Testing</strong> <br>Test integrations with services like Stripe, Slack, or GitHub by exposing your local endpoint.</li><li><strong>Mobile Development</strong> <br>Let mobile apps (physical devices or emulators) interact with APIs running on your laptop.</li><li><strong>Collaborative Debugging</strong> <br>Share the Ngrok URL with teammates to troubleshoot issues in real time.</li><li><strong>IoT &amp; Hardware Projects</strong> 🤖<br>Connect sensors or IoT devices to a local server for remote monitoring.</li><li><strong>Secure Access</strong> 🔒<br>Ngrok’s HTTPS ensures data privacy, even for sensitive applications.</li></ol><h3>Conclusion 🎯</h3><p>Ngrok democratizes access to local development environments, enabling seamless collaboration, testing, and demos. Whether you’re a solo developer, part of a team, or working with clients, Ngrok eliminates the friction of sharing local work.</p><p>The internet is now your testing playground — no deployment required. Happy coding! 🌐✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=312da037ae11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Replace a GitHub Repository’s Branch with Code from Another Repository: Safe Guide]]></title>
            <link>https://medium.com/@kavishkanimsara9919/how-to-replace-a-github-repositorys-branch-with-code-from-another-repository-safe-guide-c24f6e61e4fd?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c24f6e61e4fd</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[how-to-replace]]></category>
            <category><![CDATA[branch]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 13:28:30 GMT</pubDate>
            <atom:updated>2025-02-19T13:28:30.255Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrX_5y0RX0YGJFLs8upkFA.png" /></figure><p>Have you ever needed to replace the main branch of one repository with code from another, without affecting other branches like dev or features? 🚀 This guide walks you through the process step-by-step, ensuring your workflow stays clean and efficient.</p><p>💡 Stay tuned until the end for a <strong>bonus tip</strong> on how to replace any branch from any repository branch!</p><h3>📌 Scenario</h3><ul><li><strong>Source Repository</strong>: my-source-repository (contains the code you want to keep in its main branch).</li><li><strong>Target Repository</strong>: my-target-repository (needs its main branch overwritten, while branches like dev and feature must remain untouched).</li></ul><p>🎯 <strong>Goal</strong>: Override the main branch of my-target-repository with the main branch of my-source-repository, preserving other branches.</p><h3>🛠️ Step-by-Step Guide</h3><h3>1️⃣ Step 1: Clone &amp; Navigate to Your Source Repository</h3><p>Ensure you’re working in the <strong>source repository</strong> (my-source-repository):</p><pre>cd path/to/my-source-repository  <br>git checkout main  # Ensure you&#39;re on the main branch  </pre><h3>2️⃣ Step 2: Add the Target Repository as a Remote</h3><p>Link the target repository as a <strong>new remote</strong> (we’ll name it template for clarity):</p><pre>git remote add template https://github.com/your-username/my-target-repository.git  </pre><p>Verify the remotes:</p><pre>git remote -v  <br># Output should show:  <br># origin  https://github.com/your-username/my-source-repository.git (fetch/push)  <br># template https://github.com/your-username/my-target-repository.git (fetch/push)  </pre><h3>3️⃣ Step 3: Backup the Target’s Original Main Branch (Optional)</h3><p>Before overwriting, create a backup branch in the target repository:</p><pre>git fetch template  # Fetch all branches from the target repo  <br>git checkout template/main  # Checkout the target&#39;s main branch  <br>git checkout -b backup-main  # Create a local backup branch  <br>git push template backup-main  # Push the backup to the target repo  </pre><p>This creates a backup-main branch in my-target-repository, preserving its original state.</p><h3>4️⃣ Step 4: Force-Push to Override the Target’s Main Branch</h3><p>From the <strong>source repository’s </strong><strong>main branch</strong>, force-push to the target:</p><p><strong>🚨 Reminder: You’re Still in the Source Repository!</strong></p><pre>git checkout main  # Stay on the source&#39;s main branch  <br>git push --force template main:main  </pre><p>This replaces the target’s main branch with your source’s main branch.</p><h3>5️⃣ Step 5: Verify the Result</h3><p>Check the target repository on GitHub. Its main branch should now match your source repository. Other branches (dev, feature/login) remain unchanged.</p><h3>💡 Bonus Tip: Override Any Target Branch from Any Source Branch</h3><p>Want to replace any branch in the target repository with code from any branch in the source repository? Here’s how you can do it safely and efficiently:</p><ol><li>Switch to the branch you want to use as the source</li></ol><pre>git checkout source-branch-name </pre><p>2. Force Push to Target Branch</p><pre>git push --force template source-branch-name:target-branch-name  # Override the target branch with the source branch</pre><h3>🔥 Example:</h3><p>If you want to override the dev branch in your target repository with the feature branch from your source:</p><pre>git checkout feature/new-ui  # Switch to the source branch<br>git push --force target-remote feature:dev  # Force push to override the dev branch</pre><h3>⚠️ Important Notes</h3><ul><li>Be cautious with --force, as it overwrites the target branch history.</li><li>Always double-check the branch names and remotes to avoid accidental data loss.</li><li>Backups save lives: Use Step 3 if the target’s original branch has valuable history.</li></ul><h3>🎉 Congratulations, You Did It!</h3><p>You’ve successfully mastered the art of replacing GitHub branches across repositories without impacting other branches. By following this secure approach, you can maintain a clean and organized workflow, effortlessly syncing code between projects.</p><p>With this powerful technique in your toolkit, you’re now ready to handle any branch management challenge with confidence. Keep experimenting, stay organized, and keep pushing your code to new heights! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c24f6e61e4fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oops, Did I Just Commit a Secret?!” A Guide to Removing Secrets from Git History with BFG]]></title>
            <link>https://medium.com/@kavishkanimsara9919/oops-did-i-just-commit-a-secret-a-guide-to-removing-secrets-from-git-history-with-bfg-51186976897a?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/51186976897a</guid>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 13:35:26 GMT</pubDate>
            <atom:updated>2025-02-18T13:36:04.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgLqNmC3114QSbzo0-fe7w.png" /></figure><p>😱 So, you’ve accidentally committed a secret to GitHub. Maybe it’s an API key, a password, or sensitive information? Don’t panic! The BFG Repo-Cleaner is here to save the day. Think of it as a digital cleanup crew for sensitive data, ensuring your secrets stay secret.</p><p>In this guide, we’ll walk through using BFG Repo-Cleaner to remove secrets step by step. By the end, you’ll have the confidence to safeguard your Git history and ensure your sensitive data is secure. Let’s dive in!</p><h3>Why Can’t I Just Delete or Change the File? 🤔</h3><p>Deleting or changing a file that contains a secret doesn’t make it disappear from Git history. Git stores every commit, so even if you update or delete the file, the previous versions of it (and the secret) are still accessible through your history.</p><p>🔍 <em>Example:</em> Here’s what it looks like when a file is updated but the old commit still contains the secret:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NZydulBFlIViR4VRL062A.png" /><figcaption>Screenshot: It looks like when the file is updated.</figcaption></figure><h3>🛠️ The Solution: BFG Repo-Cleaner</h3><p>BFG Repo-Cleaner surgically removes sensitive data from your entire Git history. It’s fast, efficient, and simple to use compared to traditional Git commands.</p><h3>🤔 How BFG Works</h3><ol><li>It scans your Git history for files or text patterns you specify.</li><li>It removes or replaces the sensitive data while keeping everything else intact.</li><li>It rewrites your repository’s history so the sensitive data is no longer accessible.</li></ol><h3>🛠️ Before You Start</h3><p>Before you start, make sure you have the following:</p><ol><li><strong>BFG Repo-Cleaner:</strong> Download from the <a href="https://rtyley.github.io/bfg-repo-cleaner/">official site</a>.</li><li><strong>Java Installed:</strong> Check if Java is installed by running 🚀</li></ol><h3>🚀 Step-by-Step Guide</h3><h3>1️⃣ Step 1: Clone a Fresh Copy of Your Repository</h3><p>BFG works best with a mirrored clone of your repository</p><pre>git clone --mirror https://github.com/yourusername/yourrepo.git<br>cd yourrepo.git</pre><p>🔍 <strong>Sample Output:</strong></p><pre>C:~/demo$ git clone --mirror git@github.com:kavishkanimsara/git-secret.git<br>Cloning into bare repository &#39;git-secret.git&#39;...<br>remote: Enumerating objects: 9, done.<br>remote: Counting objects: 100% (9/9), done.<br>remote: Compressing objects: 100% (4/4), done.<br>remote: Total 9 (delta 0), reused 9 (delta 0), pack-reused 0 (from 0)<br>Receiving objects: 100% (9/9), done.</pre><p>💡 <em>Why a mirrored clone?</em> It contains all references and branches, making it easier to clean the entire repository history.</p><h3>2️⃣ Step 2: Create a File Listing Secrets</h3><p>Make a secrets.txt file with each secret on a new line:</p><pre>PASSWORD : 12345678</pre><p>🔑 <em>Tip:</em> Add all keys, passwords, API tokens, or any other sensitive information you want to remove from your Git history. If you committed multiple secrets over different commits, make sure to include all of them in this file.</p><p>This file acts as a guide for BFG to identify and remove the sensitive information across all commits.</p><h3>3️⃣ Step 3: Run BFG to Remove Secrets</h3><pre>java -jar bfg-1.15.0.jar --replace-text secrets.txt yourrepo.git</pre><p>🔍 <strong>Expected Output:</strong></p><pre>C:~/demo$ java -jar bfg-1.15.0.jar --replace-text secrets.txt git-secret.git</pre><pre>Using repo : /home/kavishka-nimsara/demo/git-secret.git</pre><pre>Found 3 objects to protect<br>Found 2 commit-pointing refs : HEAD, refs/heads/main</pre><pre>Protected commits<br>-----------------</pre><pre>These are your protected commits, and so their contents will NOT be altered:</pre><pre> * commit 515705a6 (protected by &#39;HEAD&#39;)</pre><pre>Cleaning<br>--------</pre><pre>Found 3 commits<br>Cleaning commits:       100% (3/3)<br>Cleaning commits completed in 46 ms.</pre><pre>Updating 1 Ref<br>--------------</pre><pre> Ref               Before     After   <br> -------------------------------------<br> refs/heads/main | 515705a6 | ba2c54ac</pre><pre>Updating references:    100% (1/1)<br>...Ref update completed in 7 ms.</pre><pre>Commit Tree-Dirt History<br>------------------------</pre><pre> Earliest      Latest<br> |                  |<br>    D     m      m   </pre><pre> D = dirty commits (file tree fixed)<br> m = modified commits (commit message or parents changed)<br> . = clean commits (no changes to file tree)</pre><pre>                         Before     After   <br> -------------------------------------------<br> First modified commit | b0be22c6 | b0e2cde0<br> Last dirty commit     | b0be22c6 | b0e2cde0</pre><pre>Changed files<br>-------------<br> Filename    Before &amp; After     <br> -------------------------------<br> index.txt | b833c7e6 ⇒ 81b5dbfc</pre><pre>In total, 4 object ids were changed. Full details are logged here:</pre><pre> /home/kavishka-nimsara/demo/git-secret.git.bfg-report/2025-02-18/16-22-39</pre><pre>BFG run is complete! When ready, run: git reflog expire --expire=now --all &amp;&amp; git gc --prune=now --aggressive</pre><h3>4️⃣ Step 4: Clean Up Remaining References</h3><p>Run these commands to remove any leftover traces:</p><pre>git reflog expire --expire=now --all<br>git gc --prune=now --aggressive</pre><h3>Step 5️⃣:Push the Cleaned Repository</h3><p>Force push the cleaned repository to GitHub:</p><pre>git push --force</pre><p>⚠️ <em>Note:</em> Anyone with an existing clone must re-clone the repository to get the cleaned history.</p><h3>🎉 Congratulations, You Did It!</h3><p>Your secrets have been successfully removed from your Git history! 🛡️ You can now rest easy knowing your sensitive information is no longer accessible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZow3-JWCFKkFPI7c4YbaQ.png" /><figcaption>Secrets successfully removed from history</figcaption></figure><h3>Tips &amp; Final Thoughts 💡</h3><ul><li><strong>Re-clone Required:</strong> Anyone with a local clone must re-clone after force-pushing.</li><li><strong>Backups:</strong> Always make a backup before using BFG.</li><li><strong>Clean Your Latest Commit:</strong> Ensure your latest commit is clean before running BFG.</li></ul><p>By following these steps, you can confidently remove secrets from your Git history and keep your sensitive data safe! 🔒 Happy cleaning! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51186976897a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ A Step-by-Step Guide: Creating Your Own Command Line Tool (CLI) with Node.js]]></title>
            <link>https://medium.com/@kavishkanimsara9919/a-step-by-step-guide-creating-your-own-command-line-tool-cli-with-node-js-0d16b21bea61?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d16b21bea61</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[custom-tools]]></category>
            <category><![CDATA[command-line-interface]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 06:17:52 GMT</pubDate>
            <atom:updated>2025-02-17T06:17:52.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyrKDxDhviegaNYVK--CEA.png" /></figure><h3>🤔 What Exactly is a CLI Tool?</h3><p>Imagine you have a kitchen robot that follows your voice commands to prepare meals. A <strong>CLI (Command Line Interface)</strong> works similarly but for coding tasks. Instead of clicking buttons in an app, you type text-based commands in your terminal to automate workflows, run scripts, or manage files.</p><p>For example, if you’re creating lots of apps that all need the same basic features, like <strong>user authentication</strong> or <strong>database connections</strong>, you don’t need to set those up manually each time. With a CLI tool, you can automate the process and include those features with a single command, saving time and effort. ⏳</p><h3>🎯 Why Use a CLI Tool?</h3><p>✅ <strong>Reduces Repetition and Increases Reusability: </strong>No need to rewrite the same code over and over.</p><p>✅ <strong>Faster Development: </strong>Only update environment variables and unique parts while everything else is handled automatically.</p><p>✅ <strong>Custom Commands: </strong>Create commands tailored to your needs for ultimate flexibility.</p><p>✅ <strong>Faster Than GUIs: </strong>Typing commands is often quicker than navigating graphical interfaces.</p><h3>🏗️ What We’ll Build</h3><p>Today, we’ll create a <strong>CLI tool</strong> that automatically sets up a <strong>React application</strong> and adds a component that fetches data from a public API using Axios. Once completed, you’ll have a working foundation to easily extend and modify for your projects</p><h3>🛠️ Before You Start</h3><h4>You’ll Need:</h4><p>📌 <strong>Node.js (v18+ recommended)</strong> — Think of this as the engine for your CLI 📌 <strong>A Code Editor (VS Code, Sublime, etc.)</strong> — We recommend <strong>VS Code</strong> for its terminal integration.</p><h3>1️⃣ Step 1: Create Your CLI’s Home Base</h3><p>First, create a new folder for your CLI tool and initialize a Node.js project:</p><pre>mkdir my-cli-tool &amp;&amp; cd my-cli-tool<br>npm init -y</pre><p>This creates a <strong>package.json</strong> file, which stores project metadata and dependencies.</p><h3>2️⃣ Step 2: Install Required Packages</h3><pre>npm install commander chalk</pre><h4>What We’re Adding and Why:</h4><p>✅ <strong>Commander.js: </strong>Handles commands like create my-app and routes them to the right code.</p><p>✅ <strong>Chalk: </strong>Provides colored output to enhance the user experience.</p><h3>3️⃣ Step 3: Create the CLI Tool File</h3><p>Create a new file named index.js in your project root. This file will define the commands for our CLI tool.</p><h4>Add this code to index.js :</h4><pre>#!/usr/bin/env node<br>import { Command } from &#39;commander&#39;;<br>import chalk from &#39;chalk&#39;;<br>import { createReactApp } from &#39;./reactSetup.js&#39;;<br><br>// Initialize the CLI tool<br>const program = new Command();<br><br>// Define the &quot;create&quot; command<br>program<br>  .command(&#39;create &lt;projectName&gt;&#39;)<br>  .description(&#39;Start a new React Vite project&#39;)<br>  .action((projectName) =&gt; {<br>    console.log(chalk.blue(`🚀 Launching ${projectName}...`));<br>    createReactApp(projectName); // Handles project setup<br>  });<br><br>// Process the CLI commands<br>program.parse(process.argv);</pre><h3>🧐 Explanation</h3><p>📌 <strong>Shebang Line (</strong><strong>#!/usr/bin/env node)</strong> :Ensures the file runs as a Node.js script.</p><p>📌 <strong>Imports:</strong> Brings in required libraries (commander, chalk) and our createReactApp function.</p><p>📌 <strong>Defining a CLI Command:</strong> program.command(&#39;create &lt;projectName&gt;&#39;) defines the <strong>create</strong> command.</p><p>📌 <strong>Command Execution:</strong> program.parse(process.argv) processes and executes the command.</p><h3>4️⃣ Step 4: Create the React Setup Function</h3><p>Now, let’s complete reactSetup.js. This file will:</p><p>✔️ Create the React Vite app</p><p>✔️ Generate essential components</p><p>✔️ Install dependencies</p><p>✔️ Fetch data from an API</p><h4>Add This Code to reactSetup.js</h4><pre>import { execSync } from &#39;child_process&#39;;<br>import { writeFileSync, mkdirSync, unlinkSync } from &#39;fs&#39;;<br>import chalk from &#39;chalk&#39;;<br><br>// Utility function for error handling<br>const handleError = (error, message) =&gt; {<br>  console.error(chalk.red(message));<br>  console.error(error);<br>  process.exit(1);<br>};<br><br>export const createReactApp = async (projectName) =&gt; {<br>  try {<br>    // 1. Create Vite React App<br>    console.log(chalk.blue(&#39;Setting up React Vite project...&#39;));<br>    execSync(`npm create vite@latest ${projectName} -- --template react`, {<br>      stdio: &#39;inherit&#39;<br>    });<br><br>    // 2. Navigate to project directory<br>    process.chdir(projectName);<br><br>    // 3. Install axios<br>    console.log(chalk.blue(&#39;Installing axios...&#39;));<br>    execSync(&#39;npm install axios&#39;, { stdio: &#39;inherit&#39; });<br><br>    // 4. Create components directory<br>    const componentsDir = &#39;./src/components&#39;;<br>    mkdirSync(componentsDir, { recursive: true });<br><br>    // 5. Create FetchData component<br>    createFetchComponent(componentsDir);<br><br>    // 6. Modify App.jsx<br>    modifyAppJsx();<br><br>    console.log(chalk.green(&#39;\n✅ Project setup completed successfully!&#39;));<br>    console.log(chalk.yellow(`\ncd ${projectName} &amp;&amp; npm run dev`));<br>  } catch (error) {<br>    handleError(error, &#39;❌ Error during project setup:&#39;);<br>  }<br>};<br>  try {<br>    writeFileSync(`${componentsDir}/FetchData.jsx`, fetchComponentCode);<br>    console.log(chalk.blue(&#39;📁 Created FetchData component&#39;));<br>  } catch (error) {<br>    handleError(error, &#39;❌ Error creating FetchData component:&#39;);<br>  }<br>};</pre><p>The createReactApp function sets up a Vite-based React project, installs axios, creates a components folder, adds a FetchData.jsx component, and updates App.jsx to use it.</p><pre>// Helper function to create FetchData component<br>const createFetchComponent = (componentsDir) =&gt; {<br>  const fetchComponentCode = `import React, { useState, useEffect } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>const FetchData = ({ apiUrl }) =&gt; {<br>  const [data, setData] = useState([]);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        const response = await axios.get(apiUrl);<br>        setData(response.data);<br>      } catch (err) {<br>        setError(err.message);<br>      } finally {<br>        setLoading(false);<br>      }<br>    };<br>    fetchData();<br>  }, [apiUrl]);<br><br>  if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error}&lt;/div&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Fetched Data&lt;/h2&gt;<br>      &lt;pre&gt;{JSON.stringify(data, null, 2)}&lt;/pre&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default FetchData;<br>`;</pre><p>The createFetchComponent function generates FetchData.jsx, which fetches API data using axios, manages state, and displays loading, error, or fetched data.</p><pre>// Helper function to modify App.jsx<br>const modifyAppJsx = () =&gt; {<br>  const appJsxCode = `import FetchData from &#39;./components/FetchData&#39;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;My Auto-Generated React App&lt;/h1&gt;<br>      &lt;FetchData apiUrl=&quot;https://jsonplaceholder.typicode.com/users&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;<br>`;<br><br>  try {<br>    // Remove existing content in App.jsx<br>    writeFileSync(&#39;./src/App.jsx&#39;, appJsxCode);<br>    console.log(chalk.blue(&#39;🔄 Updated App.jsx&#39;));<br>  } catch (error) {<br>    handleError(error, &#39;❌ Error updating App.jsx:&#39;);<br>  }<br>};</pre><p>The modifyAppJsx function updates App.jsx to import and render FetchData, ensuring the app starts with a working API call. 🚀</p><h3>Step 5️⃣: Make Your CLI Tool Executable</h3><p>To make your CLI tool executable, add the following to your package.json:</p><pre>{<br>  &quot;bin&quot;: {<br>    &quot;my-react-app&quot;: &quot;./index.js&quot;<br>  },<br>  &quot;type&quot;: &quot;module&quot;<br>}</pre><ul><li><strong>binField:</strong> Defines the name of your CLI command (react-automator) and points to the entry file (index.js).</li><li><strong>type&quot;module&quot;:</strong> Specifies that the project uses ECMAScript (ES) modules, allowing you to use import and export syntax.</li><li>You can change “my-react-app” to any name you prefer for your CLI tool.</li></ul><h3>Step 6️⃣: Install Your CLI Globally</h3><p>Run the following command to link your CLI tool globally:</p><pre>npm link</pre><p>This creates a symbolic link between your project and the global npm directory, making your CLI tool available system-wide.</p><h3>Step 7️⃣: Test Your CLI Tool</h3><p>Woohoo! 🎉 Your CLI tool is now ready to go! 🚀 You can test it by running the following command:</p><pre>my-react-app create my-demo-app</pre><p>This will generate a brand-new React app named my-demo-app for you. Go ahead and try it out—you’re just a command away from building something awesome! 💻✨</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAGfVSy8KNs%2FZtFrdXzIu1x_ly6uw0c8Gg%2Fwatch%3Futm_content%3DDAGfVSy8KNs%26utm_campaign%3Ddesignshare%26utm_medium%3Dlink2%26utm_source%3Duniquelinks%26utlId%3Dh75356f7c02&amp;type=text%2Fhtml&amp;schema=canva&amp;display_name=Canva&amp;src=https%3A%2F%2Fwww.canva.com%2Fdesign%2FDAGfVSy8KNs%2FZtFrdXzIu1x_ly6uw0c8Gg%2Fwatch%3Fembed%26meta" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/855e203087be4886ed54de2bdec89e63/href">https://medium.com/media/855e203087be4886ed54de2bdec89e63/href</a></iframe><h3>🏗️ How to Add Your Own Components</h3><p>We created a React.js app with data fetching. Now, let’s <strong>add your own components</strong>! 🎨</p><h3>1️⃣ Step 1: Create a Component File</h3><p>Add a helper function in reactSetup.js:</p><pre>const createCustomComponent = (componentsDir) =&gt; {<br>  const componentCode = `// Your component code here`;<br>  writeFileSync(`${componentsDir}/NewComponent.js`, componentCode);<br>  console.log(chalk.blue(&#39;📁 Created NewComponent&#39;));<br>};</pre><h3>2️⃣ Step 2: Add It to the Setup Process</h3><p>Modify createReactApp:</p><pre>export const createReactApp = async (projectName) =&gt; {<br>  // ...existing code...<br>  createCustomComponent(componentsDir);<br>  // ...rest of code...<br>};</pre><h3>3️⃣ Step 3: Modify App.js</h3><p>Update the App template:</p><pre>const appJsCode = `import NewComponent from &#39;./components/NewComponent&#39;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;NewComponent /&gt;<br>    &lt;/div&gt;<br>  );<br>}`;</pre><h3><strong>🚀GitHub Repository</strong></h3><p>Check out the full code here:</p><p><a href="https://github.com/kavishkanimsara/Custom-CLI-Tool_NodeJS"><em>https://github.com/kavishkanimsara/Custom-CLI-Tool_NodeJS</em></a></p><h3>🎯 Conclusion</h3><p>Congratulations! 🎉 You’ve built a <strong>CLI tool</strong> that: ✅ Automates <strong>React Vite app creation</strong> 🚀 ✅ Installs dependencies <strong>automatically</strong> 📦 ✅ Adds a <strong>data-fetching component</strong> from an API 🌍 ✅ Allows you to <strong>extend functionality with new components</strong> 🎨</p><p>Now, you can further customize it to fit your workflow.</p><p>💬 If you have any questions or feedback, feel free to inbox me at <a href="/service/mailto:kavishkanimsara.official@gmail.com"><em>kavishkanimsara.official@gmail.com</em></a> ! 😊 Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d16b21bea61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding useEffect’s Dependency Array in React: A Complete Guide]]></title>
            <link>https://medium.com/@kavishkanimsara9919/understanding-useeffects-dependency-array-in-react-a-complete-guide-c9c2f71059fb?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9c2f71059fb</guid>
            <category><![CDATA[dependancy-array]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[useeffect-hook]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 21:00:41 GMT</pubDate>
            <atom:updated>2025-02-06T21:00:41.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGf2P8wG2P4o6NvkArxMnQ.png" /></figure><p>Welcome to today’s blog! In this article, I’ll help you understand what the <strong>dependency array</strong> in useEffect is and how to use it effectively in your React or Next.js projects. Moreover, if you’re preparing for an interview, understanding this concept could give you an edge. Let’s dive in!</p><h3>What is useEffect?</h3><p>useEffectis a React Hook that allows us to perform <strong>side effects</strong> in functional components. Side effects can include fetching data, updating the DOM, or handling timers.</p><p><strong>What are Side Effects?</strong></p><p>A <strong>side effect</strong> is when a function does something that affects the outside world, like fetching data from an API or modifying a variable outside its scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mHb57D-QfCv3MQ6TJLjMfg.png" /><figcaption>Basic structure of the useEffect</figcaption></figure><h3>What is the Dependency Array?</h3><p>The <strong>dependency array</strong> in useEffect determines when the effect should run.It controls when the effect executes based on the values inside the array.</p><p>We can use different types in the dependency array depending on what values we want to track for changes</p><p>Here’s how to use it:</p><h3>1. Empty Dependency Array</h3><p>When you pass an <strong>empty array (</strong><strong>[])</strong>, the effect runs <strong>only once </strong>after the initial render.</p><p><strong>Why use an Empty Array?</strong></p><p>✔ Run code only once when the component mounts.</p><p>✔ Prevent unnecessary re-executions on re-renders.</p><p><strong>Example :</strong></p><pre>import { useEffect } from &quot;react&quot;;<br><br>function App() {<br>  useEffect(() =&gt; {<br>    console.log(&quot;Hello world!&quot;);<br>  }, []); // Empty array<br><br>  return &lt;h1&gt;Hello, World!&lt;/h1&gt;;<br>}<br><br>export default App;</pre><p>You will see the output “Hello world!” only once, during the initial render (when the page is loaded), in your console.</p><pre>Hello world!</pre><p><strong>Common Use Cases for an Empty Array:</strong></p><p>✔ Fetching data (API calls on mount)</p><p>✔ Initializing values</p><p>✔ Setting up event listeners</p><h3>2. Specific Dependencies [value]</h3><p>When you include specific values inside the dependency array, the effect runs <strong>only when those values change</strong>.</p><p><strong>When to Use It?</strong></p><p>✔ Updating the UI based on state/prop changes.</p><p>✔ Avoiding unnecessary effect executions.</p><p>✔ Fetching data when a state variable updates.</p><p><strong>Example:</strong></p><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;Effect ran because count changed:&quot;, count);<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>You will see the output “Effect ran because count changed: 0” only once during the initial render (when the page loads) in your console.</p><p>However, when you click the increment button, the side effect will run again, and you will see the output like: “Effect ran because count changed: 1”, “Effect ran because count changed: 2”, “Effect ran because count changed: 3”, and so on, as the count value changes.</p><p><strong>Ouput:</strong></p><pre>Effect ran because count changed: 0<br>Effect ran because count changed: 1<br>Effect ran because count changed: 2</pre><p><strong>Multiple Dependencies </strong><strong>[count1, count2]</strong></p><p>You can include <strong>multiple dependencies</strong> in the array, and the effect runs whenever <strong>any of them</strong> change.</p><p><strong>Example:</strong></p><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>function MultipleCounters() {<br>  const [count1, setCount1] = useState(0);<br>  const [count2, setCount2] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(`Effect ran because count1 or count2 changed: ${count1}, ${count2}`);<br>  }, [count1, count2]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count1: {count1}&lt;/p&gt;<br>      &lt;p&gt;Count2: {count2}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount1(count1 + 1)}&gt;Increment Count1&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCount2(count2 + 1)}&gt;Increment Count2&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MultipleCounters;</pre><p><strong>How It Works:</strong></p><p>You can see in your console:</p><ol><li><strong>Initial Render</strong> → The effect runs once:</li></ol><pre>Effect ran because count1 or count2 changed: 0, 0</pre><p><strong>2. Click “Increment Count1”</strong> (count1 increases):</p><pre>Effect ran because count1 or count2 changed: 1, 0</pre><p><strong>3. Click “Increment Count2”</strong> (count2 increases):</p><pre>Effect ran because count1 or count2 changed: 1, 1</pre><p>The effect only runs when either count1 or count2 changes, not on every render.</p><p><strong>When to Use Multiple Dependencies?</strong></p><p>✔ <strong>Reacting to Multiple State Changes</strong><br>Example: Updating the UI when either count1 or count2 changes.</p><p>✔ <strong>Fetching New Data When Different Filters Change</strong><br>Example: Fetching new products when category or priceRange changes.</p><p>✔ <strong>Listening to Multiple Values in an Event Listener</strong><br>Example: Watching for changes in both screenWidth and themePreference.</p><h3>3. Omitted Dependency Array (No Dependency Array)</h3><p>If you <strong>don’t provide a dependency array</strong>, the effect runs <strong>after every render.</strong></p><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>function Example() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;Effect ran after every render&quot;);<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCount(count - 1)}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Example;</pre><p>Each time you click the “Increment” or “Decrement” buttons, the state count changes, triggering a re-render of the component.</p><pre>Effect ran after every render</pre><p>You can see The effect runs every time the component re-renders.</p><p><strong>When to Use </strong><strong>useEffect Without Dependencies?</strong></p><p>✔ Logging/debugging</p><p>✔ Animations after every render</p><p>✔ Dynamic UI recalculations</p><p>🚨 However, Running effects on every render can cause performance issues</p><h3>Conclusion</h3><p>The useEffect dependency array <strong>controls when the effect runs</strong>, making it a powerful tool in React. Here&#39;s a quick recap:</p><p>✔ <strong>useEffect(fn, [])</strong> → Runs <strong>only once</strong> (on mount)</p><p>✔ <strong>useEffect(fn, [state])</strong> → Runs when <strong>state changes</strong>.</p><p>✔ <strong>useEffect(fn, [state1, state2])</strong> Runs when <strong>any state changes</strong>.</p><p>✔<strong>useEffect(fn) (no array)</strong> → Runs <strong>on every render</strong> (⚠ avoid overuse!).</p><p>Mastering these patterns will help you write better, more optimized React applications.</p><h3>Thanks for Reading!</h3><p>Hope this guide helped you understand how to use the useEffect dependency array effectively! Have any questions? Drop them in the comments below. Happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9c2f71059fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your ASP.NET Core Skills with Dependency Injection!]]></title>
            <link>https://medium.com/@kavishkanimsara9919/a-simple-guide-to-dependency-injection-in-asp-net-core-ea108b5f32e8?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea108b5f32e8</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[a-simple-guide]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[id]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 12:24:07 GMT</pubDate>
            <atom:updated>2024-11-04T12:26:06.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEO2_R3c7XtsBsUWpFn8Yw.png" /></figure><p>Dependency Injection (DI) is a design pattern used in software development to make code more flexible, testable, and maintainable.</p><p>It involves injecting the dependencies a class needs from the outside rather than allowing the class to create these dependencies itself. This approach helps to achieve <strong><em>loose coupling</em>,</strong> making it easier to change and maintain code over time.</p><p>In this article, we’ll explore what Dependency Injection is, the differences between loose and tight coupling, how to implement DI in ASP.NET Core 8, and the advantages of using DI in your projects.</p><h3>What is Dependency Injection?</h3><p>In DI, a <em>dependency</em> is any object that a class relies on to function. For example, if a class called UserController needs an EmailService to send notifications, the EmailService is considered a dependency of UserController.</p><p>By providing dependencies from outside the class, we reduce the need for classes to know about each other directly. This design improves <em>testability, maintainability, and scalability</em>, which are essential for modern software development.</p><p>The primary goal of Dependency Injection is to achieve <strong><em>loose coupling</em></strong>, making the components of a system more modular and adaptable to change.</p><h3>Tight Coupling vs. Loose Coupling</h3><h3>Tight Coupling</h3><p>Tight coupling means components within a system are <strong>highly dependent</strong> on each other. For instance, if UserController directly creates an instance of EmailService, then any changes to EmailService might require changes to UserController as well. Tight coupling makes it hard to modify or replace one part of the system without affecting others, which can lead to issues with maintenance and testing.</p><h3>Loose Coupling</h3><p>Loose coupling, on the other hand, allows components to function independently. With DI, UserController does not create EmailService; instead, it receives it from an external source. This makes it easier to change EmailService without modifying UserController, as long as they both follow the same interface or contract. Loose coupling improves modularity, flexibility, and makes the system easier to test.</p><h3>Implementing Dependency Injection in ASP.NET Core 8: A Step-by-Step Guide</h3><p>Let’s walk through the process of implementing Dependency Injection in an ASP.NET Core 8 application.</p><ol><li><strong>Create the </strong>EmailService<strong> Class</strong></li></ol><p>Start by creating a service class, EmailService, that has a method to send emails.</p><pre>public class EmailService : IEmailService<br>{<br>    public void SendEmail(string to, string subject, string body)<br>    {<br>        // Logic to send email<br>        Console.WriteLine($&quot;Sending email to {to}: {subject} - {body}&quot;);<br>    }<br>}</pre><p><strong>2. Implement the </strong>IEmailService<strong> Interface</strong></p><p>To make EmailService more flexible, we use an interface, IEmailService, which defines the contract for sending emails.</p><pre>public interface IEmailService<br>{<br>    void SendEmail(string to, string subject, string body);<br>}</pre><p><em>With </em>IEmailService<em>, we can switch out </em>EmailService<em> for any other class that implements the same method signature without affecting other parts of the application.</em></p><p><strong>3. Inject the Dependency in the</strong> UserController<strong> Class</strong></p><p>Now, we inject IEmailService into a controller, UserController, to use it for sending emails.</p><pre>public class UserController : ControllerBase<br>{<br>    private readonly IEmailService _emailService;<br><br>    public UserController(IEmailService emailService)<br>    {<br>        _emailService = emailService;<br>    }<br><br>    public IActionResult NotifyUser(string email)<br>    {<br>        _emailService.SendEmail(email, &quot;Welcome&quot;, &quot;Thank you for joining us!&quot;);<br>        <br>        return Ok(&quot;Notification sent.&quot;);<br>    }<br>}</pre><p>In the UserController constructor, we use <em>constructor injection</em> to receive an instance of IEmailService. ASP.NET Core&#39;s DI system provides this instance at runtime.</p><p><strong>4. Register Services in Dependency Injection</strong></p><p>The final step is to register EmailService with the IoC (Inversion of Control) container so that ASP.NET Core knows how to provide it when needed. This registration is done in Program.cs:</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddScoped&lt;IEmailService, EmailService&gt;();<br><br>var app = builder.Build();</pre><p>Here, we use AddScoped, which determines the lifetime of the dependency. There are three main options for defining service lifetimes in ASP.NET Core:</p><ul><li><strong>Transient</strong>: A new instance is created every time it’s requested. Use this for lightweight, stateless services.</li><li><strong>Scoped</strong>: A new instance is created for each HTTP request. This is useful for services with a limited lifespan.</li><li><strong>Singleton</strong>: A single instance is created and shared across the entire application. Use this for services that should retain state across requests.</li></ul><h3><strong>What is Inversion of Control (IoC)?</strong></h3><p>Inversion of Control (IoC) is a principle where the control over creating and managing dependencies is<strong> shifted away</strong> from the class itself to an external container or framework. Instead of each class managing its dependencies, the IoC container (ASP.NET Core’s built-in DI container) does this work.</p><p>Dependency Injection is one way to implement IoC, allowing external injection of dependencies into classes that need them. This setup reduces the complexity and tight coupling within the codebase.</p><h3>Conclusion</h3><p>Dependency Injection is a valuable design pattern that promotes loose coupling, making applications more flexible, testable, and maintainable. ASP.NET Core provides built-in support for DI, simplifying dependency management for developers. By leveraging DI, you can create modular, adaptable applications that are easier to test and maintain over time.</p><p>Thank you for reading!</p><h3>Further Reading</h3><ul><li><a href="https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection">Dependency Injection in .NET Documentation (Microsoft)</a></li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection">ASP.NET Core Dependency Injection (Official Microsoft Docs)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea108b5f32e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide: File Operations in Azure Blob Storage with ASP.NET Core]]></title>
            <link>https://medium.com/@kavishkanimsara9919/complete-guide-file-operations-in-azure-blob-storage-with-asp-net-core-79e9cfcd4638?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/79e9cfcd4638</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[image-upload]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[blob-storage]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 10:49:14 GMT</pubDate>
            <atom:updated>2024-06-09T10:49:14.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*An3DyWcdbfkj4SR0vS8W1w.png" /></figure><p>In today’s article, I will discuss how to upload, download, and delete files in the cloud using <strong>Azure Blob Storage</strong> with <strong>ASP.NET Core 7.0 Web API.</strong></p><p><strong>Introduction to Azure Blob Storage</strong></p><p>Azure Blob Storage is a scalable and cost-effective cloud storage solution provided by Microsoft Azure. It is designed to store and manage unstructured data, such as images, videos, documents, backups, and logs, in the cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*STvwSZzn3SeI1SZ7vCbD1w.png" /><figcaption>Azure Blob Storage</figcaption></figure><h4><strong>1. Storage Account</strong></h4><p>A storage account in Azure serves as a unique namespace for organizing and accessing your data. Each object stored in Azure Storage is associated with an address that includes your storage account name. This combination of the account name and the Blob Storage endpoint forms the base address for accessing objects within your storage account.</p><p>For instance, if your storage account is named “mystorageaccount,” the default endpoint for Blob Storage would be:</p><p>http://mystorageaccount.blob.core.windows.net</p><h4>2. Container</h4><p>A container in Azure Blob Storage is like a <strong>folder</strong> in a computer’s file system. It helps organize blobs (files) within a storage account. You can create as many containers as you need, and each container can hold an unlimited number of blobs.</p><h4>3. Blobs</h4><p>Blobs are the actual files stored within Azure Blob Storage. They can store a wide range of data types, including text, images, videos, and more. Blobs offer flexibility and scalability, making them suitable for various use cases.</p><p>Now that we have a basic understanding of Blob Storage, let’s dive into the step-by-step process of creating Blob Storage. Let’s get started!</p><h3>Creating Azure Blob Storage</h3><p><strong>Step 1</strong></p><p><strong>Sign in to the Azure Portal</strong>: Access portal.azure.com and sign in with your Azure account credentials.</p><p><strong>Step 2</strong></p><p>After signing in to the Azure portal, you’ll be greeted with the dashboard. From here, locate and click on the “Storage Accounts” option .</p><p>If you cannot see ‘storage account’ like this, you can search it on the search bar and select it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*aiu47HV-yBGHN7LrhOeVMw.png" /><figcaption>Storage account</figcaption></figure><p><strong>Step 3</strong></p><p>On the <strong>Storage accounts </strong>page, select <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*bClk6j7lTzzpSyCaLryEdA.png" /></figure><p>Fill out the form and create a storage account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*r2iCOX6jN9UE2oiAGqABYA.png" /></figure><p>The name you choose must be distinct from all other storage account names within Azure. It should consist of 3 to 24 characters, comprising only lowercase letters and numbers</p><p>After completing the form, you can put the remaining options as default values or change those options by clicking the <strong>‘Next: Advanced’</strong> button. Thereby, you can change options according to your preference.</p><p>But here I’m not going to change the remaining options, and I’m clicking the <strong>‘Review + create’ </strong>button.</p><p><strong>Step 4</strong></p><p>Then it will validate our options. After completing validation, we can click ‘Create’ button to create the Storage account.</p><p>After completing the process, you will be able to see this kind of window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*Cl3ea8zywEuEJtASM0Jt7Q.png" /></figure><p>Then press the ‘<strong>Go to resource’</strong> button, and you will redirect to the storage account dashboard. Then you can see a left sidebar, and it has various options. From that, select the ‘<strong>containers’</strong> option which at under the <strong>Data Storage</strong> category</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*lRmW3dTUaaWU_pwZyme1lg.png" /></figure><p>To fill out the form for creating a container in a storage account, provide a name for the container and <strong>select a public access level</strong>. You can create any number of containers under a single storage account. The public access levels you can choose from include:</p><ol><li><strong>Private</strong>: No anonymous access. Only the account owner can access the container and its blobs.</li><li><strong>Blob (Public Read Access for Blobs Only)</strong>: Anonymous clients can read the blobs within the container but cannot list the container’s contents.</li><li><strong>Container (Public Read Access for Container and Blobs)</strong>: Anonymous clients can read the blobs and list the contents of the container.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*WEli1yAjLkx_ddgRosoVPw.png" /><figcaption>Blob container</figcaption></figure><p>After completing the form, click the <strong>Create</strong> button.</p><p>Great 😍! We have set up our Azure Blob Storage. Now, we need to connect our ASP.NET 7 application to the Blob Storage. Let’s get started with that.</p><h3>Creating ASP.NET Core 7 Application</h3><p>To create an ASP.NET Core 7 application, ensure <strong>Visual Studio</strong> is installed. If not, download and install it from the <a href="https://visualstudio.microsoft.com/downloads/">Visual Studio website</a>. Once you have Visual Studio, follow these steps:</p><ol><li><strong>Open Visual Studio</strong> and click on <strong>Create a new project</strong>.</li><li>Select <strong>ASP.NET Core Web Application</strong>, then click <strong>Next</strong>.</li><li>Enter the project name and location, and click <strong>Create</strong>.</li><li>Choose <strong>ASP.NET Core 7.0</strong> and select the <strong>ASP.NET Core Web API</strong> project template.</li><li>Click <strong>Create</strong>.</li></ol><p>After creating the project, click the <strong>Run</strong> button in Visual Studio to start the application. It will open in your browser, confirming the setup</p><p>Now, you should install the Azure.Storage.Blobs NuGet package.</p><p>Right-click your project in <strong>Solution Explorer</strong>, go to <strong>Manage NuGet Packages</strong>, and then browse for Azure.Storage.Blobs as shown in the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*GbNJjGt8k1gK15o5c1Qf6Q.png" /></figure><h3>Get Connection String</h3><p>To authorize requests to Azure storage, you’ll need a connection string. Azure provides two keys, and each key has a connection string. Follow these steps to get and use a connection string:</p><ul><li>In the Azure portal, navigate to your storage account.</li><li>Go to the <strong>Access keys</strong> section under the <strong>Security + networking</strong> category in the left menu.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*7oXf04lEHxAYQCLM1s5YsQ.png" /></figure><ul><li>Click on <strong>Show keys</strong> to reveal the keys.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*TzH9oRK1lX1-NSxfZF_yJw.png" /></figure><p>Copy one of the connection string values</p><h3>Set Up Connection String</h3><ul><li>Open the `appsettings.json` file in your project’s root directory.</li><li>Add a new variable under the <strong>ConnectionStrings</strong> section and paste the connection string you copied.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*ReeCNPtji9vL3u8Yki0stw.png" /><figcaption>appsettings.json</figcaption></figure><p>To connect your ASP.NET Core 7 application to Azure Blob Storage, add the connection string to the `program.cs` file.</p><pre>builder.Services.AddScoped(_ =&gt;<br>{<br> return new BlobServiceClient(builder.Configuration.GetConnectionString(&quot;AzureBlobStorage&quot;));<br>});</pre><h3>Creating File Services</h3><p>Create a new folder in your project named `Services`.</p><p>In the Services folder, create a new class named `FileService.cs` and implement the `IFileService.cs` interface</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*0uXJ18stIdBNcgxy5OmXrQ.png" /><figcaption>FileServices.cs</figcaption></figure><p>In the FileService class, declare a private readonly variable _blobServiceClient of type BlobServiceClient. This variable will be used to interact with Azure Blob Storage.</p><p><strong>Create a constructor</strong> for the FileService class that accepts a parameter of type BlobServiceClient. Inside the constructor, assign the provided BlobServiceClient instance to the _blobServiceClient variable using the assignment statement _blobServiceClient = blobServiceClient;</p><p>Then open your program.cs file. Add the service registration.</p><pre>builder.Services.AddScoped&lt;IFileService, FileService&gt;();</pre><h3>Creating the File Controller</h3><p>In your Controllers folder, create a new controller file named FileController.cs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*pD8Trh5xgIjdx0P96ArUUg.png" /><figcaption>fileController.cs</figcaption></figure><p>The FileController class has a private readonly variable _fileService which is injected via the constructor. This setup allows you to use the methods defined in IFileService within your controller actions.</p><h3>Creating the File Model</h3><p>In your project, create a new folder named Models. Inside the folder, create a new file named FileModel.cs.</p><pre>namespace AzureBlobStorage.Models<br>{<br> public class FileModel<br> {<br>  public IFormFile ImageFile { get; set; }<br> }<br>}</pre><p>IFormFile is an interface in ASP.NET Core for file uploads. The ImageFile property in the FileModel class uses IFormFile to represent the uploaded image</p><p><strong>Now, we are going to implement file upload logic.</strong></p><h3>Create Upload Operation</h3><p>In the FileService.cs, add a method for uploading files</p><pre>  public async Task Upload(FileModel fileModel, string containerName)<br>  {<br>   _containerName = containerName;<br>   //create container instance<br>   var containerInstance = _blobServiceClient.GetBlobContainerClient(_containerName);<br><br>   //generate UUID for the file name<br>   string newFileName = $&quot;{Guid.NewGuid().ToString()}_{fileModel.ImageFile.FileName}&quot;;<br><br>   //create blob instance<br>   var blobInstance = containerInstance.GetBlobClient(newFileName);<br><br>   //file save in storage<br>   await blobInstance.UploadAsync(fileModel.ImageFile.OpenReadStream());<br>  }</pre><p>· <strong>Get Container Instance:</strong></p><ul><li>Obtain an instance of the Azure Blob Storage container specified by containerName using the _blobServiceClient.GetBlobContainerClient() method.</li></ul><p>· <strong>Generate Unique File Name:</strong></p><ul><li>Generate a unique file name for the uploaded file to prevent overwriting existing files. This is done by appending a UUID (Universally Unique Identifier) to the original file name.</li></ul><p>· <strong>Get Blob Instance:</strong></p><ul><li>Get a reference to the blob (file) within the container by creating a BlobClient instance using containerInstance.GetBlobClient(newFileName).</li></ul><p>· <strong>Upload File to Storage:</strong></p><ul><li>Use the UploadAsync() method of the BlobClient to upload the file content asynchronously. The content of the file is obtained by opening a read stream to the uploaded file (fileModel.ImageFile.OpenReadStream()).</li></ul><h4><strong>Importance of UUID</strong></h4><ul><li>Using a<strong> UUID</strong> ensures that each uploaded file has a <strong>unique</strong> name, preventing the accidental overwriting of existing files in the Azure Blob Storage container.</li><li>If files were uploaded with the <strong>same name</strong>, the previous file would be overwritten, leading to potential data loss.</li></ul><p>Don’t forget to add the Upload function to your IFileService interface as well</p><pre>using AzureBlobStorage.Models;<br><br>namespace AzureBlobStorage.Services<br>{<br> public interface IFileService<br> {<br>  Task Upload(FileModel fileModel, string containerName);<br><br> }<br>}</pre><h4>Create an endpoint for Upload</h4><p>Before creating the endpoint in the FileController, make sure to declare a constant string AzureContainerName and assign it your specific container name. Here’s the sentence:</p><pre>private const string AzureContainerName = &quot;image-blob&quot;;</pre><p>To create an endpoint in the FileController that utilizes the Upload function from the IFileService interface, follow these steps.</p><p>In fileController.cs,</p><pre>  [HttpPost]<br>  [Route(&quot;upload&quot;)]<br>  public async Task&lt;IActionResult&gt; Upload([FromForm] FileModel fileModel)<br>  {<br>   await _fileService.Upload(fileModel ,AzureContainerName);<br>   return Ok(fileModel);<br><br>  }</pre><p>Great job! 🎉 Now that we’ve implemented the upload operation, you can simply click the “Run” button and explore the Swagger UI to interact with the API endpoint effortlessly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*72nAWWyQXCMNbEfXLnwcrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*WvDQlS3yCtgsyQl71RxFpQ.png" /></figure><p>To upload your image, select it using the provided file input field and click the “Upload” button. After uploading, refresh the container in your Azure Blob Storage account.</p><p>You will notice that your image has been successfully uploaded with a unique identifier added to its filename.🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*iBqENrLnYKrU5JVY3L3IKw.png" /></figure><h3>Create an operation for downloading a file</h3><p>In the FileService.cs, add a method for downloading files</p><pre>  public async Task&lt;Stream&gt; Get(String name, string containerName)<br>        {<br>   //create container instance<br>   var containerInstance = _blobServiceClient.GetBlobContainerClient(containerName);<br><br>   //create blob instance<br>   var blobInstance = containerInstance.GetBlobClient(name);<br><br>            var downloadContent = await blobInstance.DownloadAsync();<br><br>            return downloadContent.Value.Content;<br><br>  }</pre><p>Add the Upload function to your IFileService interface as well</p><pre>namespace AzureBlobStorage.Services<br>{<br> public interface IFileService<br> {<br>  Task Upload(FileModel fileModel, string containerName);<br>  Task&lt;Stream&gt; Get(String name, string containerName);<br> <br> }<br>}</pre><p>Here is the endpoint for downloading files in the FileController</p><pre>  [HttpGet]<br>  [Route(&quot;download&quot;)]<br>  public async Task&lt;IActionResult&gt; Download(String name)<br>  {<br>   var imageFileStream = await _fileService.Get(name ,AzureContainerName);<br>   string fileType = &quot;jpeg&quot;;<br>   if (name.Contains(&quot;png&quot;))<br>   {<br>    fileType = &quot;png&quot;;<br>   }<br>   return File(imageFileStream, $&quot;image/{fileType}&quot;, $&quot;blobfile.{fileType}&quot;);<br>  }</pre><p>You can run the project and test the Swagger UI to ensure that the download method is functioning correctly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*VNkbpjOzXeD2WSKVmoU-Jw.png" /></figure><p>Awesome!😎 Let’s proceed with adding the endpoint for deleting files.</p><h3>Create an operation for deleting a file</h3><p>Here’s the code for the Delete method in the FileService class.</p><pre>  public async Task Delete(String name, string containerName)<br>        {<br>            _containerName=containerName;<br>            //create container instance<br>            var containerInstance = _blobServiceClient.GetBlobContainerClient(_containerName);<br>            //create blob instance<br>            var blobInstance = containerInstance.GetBlobClient(name);<br>            await blobInstance.DeleteAsync();<br>  }</pre><p>Here is the endpoint for deleting files in the FileController</p><pre>[HttpDelete]<br>  [Route(&quot;delete&quot;)]<br>  public async Task&lt;IActionResult&gt; DeleteFile(String fileName)<br>  {<br>   await _fileService.Delete(fileName, AzureContainerName);<br>   return Ok(&quot;Successfully deleted&quot;);<br><br>  }</pre><p>Finally, we’ve successfully implemented file operations in Azure Blob Storage using ASP.NET Core 😍</p><p>In this blog, we learned how to handle files in Azure Blob Storage using ASP.NET Core. By combining Azure’s storage features with ASP.NET Core, we made uploading, downloading, and deleting files easy. With this knowledge, we can improve our applications, making them more user-friendly and efficient in the cloud age.</p><h3>Thanks for reading! ❤️</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79e9cfcd4638" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Purposes and Advantages of OOP Concepts]]></title>
            <link>https://medium.com/@kavishkanimsara9919/purposes-and-advantages-of-inheritance-encapsulation-abstraction-and-polymorphism-in-oop-ec60ff5e3a0a?source=rss-2113ecffc4d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec60ff5e3a0a</guid>
            <category><![CDATA[oop-concepts-in-java]]></category>
            <category><![CDATA[advantages-of-oop]]></category>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[purposes-of-inheritance]]></category>
            <dc:creator><![CDATA[Kavishka Nimsara]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 09:50:56 GMT</pubDate>
            <atom:updated>2024-05-17T18:06:10.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advantages of OOP Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1Q0O6rwakop9MSsK8LY1w.png" /></figure><p>Object-Oriented Programming (OOP) is a way of organizing and building programs that work well with traditional programming elements like control structures and data management. In Java’s OOP, there are four key principles: A<strong><em>bstraction, Encapsulation, Inheritance, and Polymorphism.</em></strong></p><p>These principles help create code that is modular, easy to reuse, and efficient. By following OOP, developers can better separate different parts of their code, making it easier to understand, maintain, and scale.</p><p>Let’s focus on each of the purposes and advantage one by one.</p><h3><strong>Inheritance</strong></h3><p>The main purpose is inheritance to promote code reusability by allowing children classes to inherit properties and behaviors from the parent class.</p><p><strong><em>Advantages-</em></strong></p><p>- Reduce duplicate codes.</p><p>- Modification can be done in one place.</p><p>-Classes can be arranged in a hierarchy based on their relationships, making the code more understandable and maintainable.</p><h3><strong>Encapsulation</strong></h3><p>The main purpose of encapsulation is to control the access to data by hiding internal implementation.</p><p><strong><em>Advantages-</em></strong></p><p>- By hiding the internal implementation details of an object, encapsulation enhances security</p><p>- It makes it easier to understand, maintain, and modify specific components of the code without affecting other</p><p>-Promotes code reusability.</p><h3><strong>Abstraction</strong></h3><p>The main purpose is a simplified complex system<strong> </strong>focuses on essential features while ignoring unnecessary details.</p><p><strong><em>Advantages</em></strong></p><p>- Simplifies complex systems by focusing on essential features.</p><p>- By hiding unnecessary details, improves code readability, making it easier for developers to understand and maintain.</p><p>-Makes it easier to adapt to changes in requirements by allowing modifications to be made at the abstract level without affecting the entire system.</p><h3><strong>Polymorphism</strong></h3><p>The main purpose is to enable a single interface to represent different types of objects.</p><p><strong><em>Advantages</em></strong></p><p>- Promotes code reusability by allowing a single interface to represent multiple types of objects, reducing the need for redundant code.</p><p>- Polymorphism reduces the complexity of code, making it easier to maintain and update without impacting existing code.</p><p>- Abstracts complex behaviors into a common interface, improving overall readability</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec60ff5e3a0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>