<?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 Isuru Jayalath on Medium]]></title>
        <description><![CDATA[Stories by Isuru Jayalath on Medium]]></description>
        <link>https://medium.com/@isuru99?source=rss-e02258aed3a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xAVWR7FV8Q3bBgIN7B9U0g.jpeg</url>
            <title>Stories by Isuru Jayalath on Medium</title>
            <link>https://medium.com/@isuru99?source=rss-e02258aed3a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:19:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isuru99/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[Working With SSH]]></title>
            <link>https://medium.com/@isuru99/working-with-ssh-7e22974b650c?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e22974b650c</guid>
            <category><![CDATA[ssh-keys]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Tue, 26 May 2026 05:39:41 GMT</pubDate>
            <atom:updated>2026-05-26T05:39:41.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*94YiTQQUFqUUkppw" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Problem: Insecure Remote Access</h3><p>In the early days of networked computing, system administrators and developers needed ways to access remote computers and servers. The internet was growing rapidly, and managing distributed systems required remote login capabilities. However, the tools available at the time posed significant security risks.</p><h3>The Era of Unencrypted Protocols</h3><p>Before SSH, the most common protocols for remote access were:</p><p><strong>Telnet</strong> — Introduced in 1969, Telnet became the standard for remote terminal access. However, it had a critical flaw: everything was transmitted in plain text. Usernames, passwords, and commands could be intercepted by anyone monitoring network traffic.</p><p><strong>FTP</strong> — File Transfer Protocol, while useful for transferring files, also sent credentials in clear text, making it vulnerable to password sniffing attacks.</p><h3>The Security Crisis</h3><p>As the internet expanded in the 1990s, these vulnerabilities became increasingly dangerous. Network sniffing tools made it trivially easy for malicious actors to:</p><ul><li>Capture login credentials</li><li>Monitor sensitive communications</li><li>Hijack active sessions</li><li>Perform man-in-the-middle attacks</li></ul><h3>The Solution: SSH is Born</h3><p>In 1995, Tatu Ylönen, a researcher at Helsinki University of Technology in Finland, experienced a password-sniffing attack on his university network. Frustrated by the lack of secure alternatives, he developed the first version of SSH (Secure Shell) protocol.</p><h3>What Made SSH Revolutionary</h3><p>SSH addressed the fundamental security flaws of its predecessors by introducing:</p><ol><li><strong>Strong Encryption</strong> — All data transmitted over SSH is encrypted using sophisticated cryptographic algorithms, making it virtually impossible for attackers to read intercepted traffic.</li><li><strong>Secure Authentication</strong> — SSH supports multiple authentication methods, including public-key cryptography, which is far more secure than password-based systems.</li><li><strong>Data Integrity</strong> — SSH ensures that data hasn’t been tampered with during transmission using cryptographic hashing.</li><li><strong>Host Verification</strong> — SSH verifies the identity of servers to prevent man-in-the-middle attacks.</li></ol><p>Today, SSH is the universal standard for secure remote access, used by millions of systems worldwide. From managing web servers to accessing cloud infrastructure, SSH has become an indispensable tool in modern computing.</p><h3>Understanding SSH Today</h3><p>SSH (Secure Shell) is a cryptographic network protocol that provides a secure channel over an unsecured network. It completely replaced the insecure protocols of the past, offering encrypted communication for remote login, command execution, and file transfers.</p><p>When you connect to a server via SSH, all traffic between your local machine and the remote server is encrypted, protecting sensitive information from eavesdropping, tampering, and interception.</p><h3>SSH Key Generation</h3><p>Building on the lessons learned from password vulnerabilities, SSH introduced public-key cryptography as the preferred authentication method. SSH keys provide a more secure alternative to password authentication through asymmetric encryption.</p><h3>How SSH Keys Work</h3><p>SSH keys consist of a pair of cryptographic keys:</p><ul><li><strong>Private key</strong>: Kept secret on your local machine (like a physical key you never share)</li><li><strong>Public key</strong>: Shared with servers you want to access (like giving out copies of a lock)</li></ul><p>When you try to connect, the server uses your public key to create a challenge that only your private key can solve, proving your identity without ever transmitting the key itself.</p><h3>Generating SSH Keys</h3><p>To generate a new SSH key pair, use the ssh-keygen command:</p><p>bash</p><pre>ssh-keygen -t rsa -b 4096 -C &quot;your_email@example.com&quot;</pre><p>During generation, you’ll be prompted to:</p><ol><li>Choose a file location</li><li>Enter a passphrase (optional but recommended for additional security)</li></ol><h3>Understanding the Generated Files</h3><p>After generation, you’ll have two files:</p><ul><li><strong>Private key</strong>: ~/.ssh/id_rsa (never share this!)</li><li><strong>Public key</strong>: ~/.ssh/id_rsa.pub (safe to share)</li></ul><h3>Copying Your Public Key to a Server</h3><p>To use your SSH key for authentication, copy the public key to the remote server:</p><p>bash</p><pre>ssh-copy-id username@remote_host</pre><p>This command appends your public key to the ~/.ssh/authorized_keys file on the remote server.</p><h3>Connecting to Server with SSH Keys</h3><p>Once you’ve copied your public key to the server, connecting is simple and password-free:</p><p>bash</p><pre>ssh username@remote_host</pre><p>For example:</p><p>bash</p><pre>ssh john@192.168.1.100</pre><p>SSH will automatically look for your private key in the default location (~/.ssh/id_rsa) and use it for authentication. You won&#39;t be prompted for a password (unless you set a passphrase on your private key, in which case you&#39;ll enter that instead).</p><p><strong>If you have multiple SSH keys</strong> or your key is in a non-default location, specify which key to use with the -i flag:</p><p>bash</p><pre>ssh -i ~/.ssh/my_custom_key username@remote_host</pre><p><strong>Example with a custom key:</strong></p><p>bash</p><pre>ssh -i ~/.ssh/work_rsa john@work-server.com</pre><p>The connection will be established using your SSH key, providing secure, encrypted access without transmitting any passwords over the network.</p><h3>Connecting with Username and Password</h3><p>While SSH keys are the recommended approach, password authentication remains supported for backward compatibility and initial setup scenarios. Unlike the plain-text passwords of Telnet, SSH encrypts password authentication, making it significantly more secure.</p><h3>Basic SSH Connection</h3><p>The simplest SSH connection uses username and password:</p><p>bash</p><pre>ssh username@hostname_or_ip</pre><p>For example:</p><p>bash</p><pre>ssh john@192.168.1.100</pre><p>Or using a domain name:</p><p>bash</p><pre>ssh john@example.com</pre><h3>Specifying a Custom Port</h3><p>If your SSH server runs on a non-standard port (default is 22):</p><p>bash</p><pre>ssh -p 2222 username@hostname</pre><h3>First-Time Connection</h3><p>The first time you connect to a server, you’ll see a message about the host’s authenticity:</p><pre>The authenticity of host &#39;example.com (192.168.1.100)&#39; can&#39;t be established.<br>ECDSA key fingerprint is SHA256:xxx...<br>Are you sure you want to continue connecting (yes/no)?</pre><p>Type yes to continue. This adds the server&#39;s fingerprint to your ~/.ssh/known_hosts file, protecting against future man-in-the-middle attacks.</p><h3>SSH with PEM Keys (AWS EC2 Instances)</h3><p>As cloud computing emerged in the 2000s, SSH became the foundation for secure access to cloud infrastructure. Amazon Web Services (AWS) built its EC2 service with SSH as the primary access method, using PEM format keys for authentication.</p><h3>Understanding PEM Keys</h3><p>PEM (Privacy Enhanced Mail) is a general-purpose encoding format that uses Base64 encoding with header and footer markers. While the name originates from an early email security standard, the format is widely used across many cryptographic contexts — including SSH private keys. AWS uses this format for EC2 key pairs due to its broad compatibility with SSH clients.</p><p>When you launch an EC2 instance, AWS generates a key pair and provides you with the private key file. This file must be downloaded immediately, as AWS does not store a copy of it. This is an intentional security measure — if the key is lost, you cannot recover it and will need to create a new key pair and reassign it to your instance.</p><h3>Connecting to EC2 with PEM Keys</h3><p>To connect to an EC2 instance using a PEM key:</p><p>bash</p><pre>ssh -i /path/to/your-key.pem ec2-user@ec2-public-ip</pre><p>For example:</p><p>bash</p><pre>ssh -i ~/Downloads/my-ec2-key.pem ec2-user@54.123.45.67</pre><h3>Common EC2 Default Usernames</h3><p>Different AMIs (Amazon Machine Images) use different default usernames:</p><ul><li>Amazon Linux 2: ec2-user</li><li>Ubuntu: ubuntu</li><li>Debian: admin or debian</li><li>RHEL: ec2-user or root</li><li>CentOS: centos</li></ul><h3>Setting Correct Permissions</h3><p>SSH requires strict permissions on private key files. If your permissions are too open, you’ll get an error:</p><pre>Permissions 0644 for &#39;my-key.pem&#39; are too open.</pre><p>Fix this with:</p><p>bash</p><pre>chmod 400 /path/to/your-key.pem</pre><p>This makes the file readable only by you, preventing other users on your system from accessing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e22974b650c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the React Virtual DOM]]></title>
            <link>https://medium.com/@isuru99/understanding-the-react-virtual-dom-3de1f62aa8fd?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3de1f62aa8fd</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[virtual-dom]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 11:01:22 GMT</pubDate>
            <atom:updated>2024-06-14T11:01:22.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjHspXHOtgwMAdffhIpPmg.png" /></figure><p>As we know React is a popular JavaScript library for building user interfaces, particularly single-page applications where UI updates frequently. One of React’s key features that enhances its performance and developer experience is the Virtual DOM. Lets discuss what is this Virtual DOM and how it actually works.</p><h3><strong>What is DOM</strong></h3><p>Before moving into Virtual DOM we need to know about what the actual DOM Is. Actual DOM is a tree-like structure the browser uses to represent a webpage’s content. Every element you see on the page (headings, paragraphs, buttons, etc.) has a corresponding node in the DOM tree. This DOM allows JavaScript to interact with and modify the content, structure, and style of a web page dynamically. For example, JavaScript can change the text inside a paragraph, update an image source, or add new elements to the page. Since each change can cause the browser to re-render the page, manipulating the DOM directly can be slow and resource-intensive, especially when dealing with many elements or frequent updates. That&#39;s where the virtual DOM comes in handy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4g9UhWgjT9AtU6cMDJzhQ.png" /></figure><h3><strong>Virtual DOM</strong></h3><p>The Virtual DOM (VDOM) is an in-memory representation of the real DOM elements generated by React components. It is a lightweight copy of the actual DOM, allowing React to manage and update the UI efficiently. This VDOM tree mirrors the structure and elements of the real DOM, but it lives in memory and isn’t directly displayed on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfiNM-2tshrdca3V36lByQ.png" /></figure><h4>How Does the Virtual DOM Work?</h4><ol><li><strong>Initial Rendering</strong></li></ol><p>When you start a React application, All components render for the first time, creating the initial structure and content of your web page. After that React generates the Virtual DOM.</p><p>2. <strong>Reconciliation</strong></p><p>When users interacting with the web page, components may need to update. Here’s how React handles it;</p><p>First react gets a snapshot of the current virtual DOM. When a component’s state changes (like when you click a button or type in a form), React updates the Virtual DOM. Then React compares the new Virtual DOM with the previously created snapshot. This comparison process is called reconciliation. To determine what has changed, React uses a “diffing” algorithm. The diffing algorithm quickly identifies differences between the old and new Virtual DOM trees.</p><p>3. <strong>Updating the Real DOM</strong></p><p>After figuring out the most efficient way to update the real DOM, React updates only the parts of the real DOM that have changed. This minimizes the performance cost associated with DOM manipulations. Then the browser re-renders only the updated parts of the web page, So this is much faster than re-rendering the entire page.</p><h3>Benefits of the Virtual DOM</h3><p><strong>Performance Improvement:</strong></p><p>By acting as an intermediary between your application’s state and the real DOM, the virtual DOM avoids directly manipulating the real DOM for every change. This is because directly updating the real DOM can be slow, especially for complex UIs.</p><p><strong>Simpler Development:</strong></p><p>The virtual DOM abstracts away the complexities of directly manipulating the DOM. This allows developers to focus on describing the UI using a declarative style, specifying what the UI should look like based on the state. React handles the efficient updates behind the scenes</p><p><strong>Easier Testing:</strong></p><p>Since the virtual DOM is a lightweight in-memory representation, it’s easier to test and reason about UI components in isolation. This simplifies the testing process for React applications.</p><p>In conclusion, the Virtual DOM is a powerful tool that contributes to React’s popularity and effectiveness. It abstracts the complexities of direct DOM manipulation, offering a smoother and more efficient way to manage dynamic UIs, ultimately leading to faster applications and a better developer experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3de1f62aa8fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Clean Code: Understanding and Applying SOLID Principles]]></title>
            <link>https://medium.com/@isuru99/mastering-clean-code-understanding-and-applying-solid-principles-58d68a6624e1?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/58d68a6624e1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 17:38:09 GMT</pubDate>
            <atom:updated>2024-06-11T17:38:09.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtKBq7ELGiQ8yr5lJoOPfw.png" /></figure><p>Have you ever spent hours debugging a piece of code only to realize that the real problem was how it was structured in the first place? Or found yourself frustrated with a codebase that’s nearly impossible to understand or ready to collapse with a single change? We’ve all been there, and it’s not a fun place to be.</p><p>But fear not! There’s a set of guiding principles that can help us write cleaner, more maintainable, and more robust code. They’re called the SOLID principles, and they’re like a roadmap to sanity in the world of software development.</p><p>Today, we’ll break down each of the SOLID principles, explain what they are, why they matter, and how you can apply them in your own projects. We’ll use simple examples to illustrate these concepts, making them easy to grasp and implement. By the end of this post, you’ll have a solid foundation for writing code that’s not just functional, but elegant and resilient.</p><p>First Lets see what are those principles and then see each of them.</p><ol><li><strong>Single Responsibility Principle (SRP)</strong></li><li><strong>Open/Closed Principle (OCP)</strong></li><li><strong>Liskov Substitution Principle (LSP)</strong></li><li><strong>Interface Segregation Principle (ISP)</strong></li><li><strong>Dependency Inversion Principle (DIP)</strong></li></ol><h3><strong>1. Single Responsibility Principle (SRP)</strong></h3><p>This means what ever the classes we create should only have a single responsibility and that responsibility only should be followed by that particular class.</p><p><strong>Why it matters:</strong> By ensuring that a class is only responsible for one thing, you make your code easier to understand and maintain. Changes in one part of your application will have minimal impact on other parts.</p><pre>public class AccountOperations {<br>   <br>    public void addAccount(Account account) {<br>    }<br><br>    public  void updateAccount(Account account) {<br>    }<br><br>    public Account getAccount(int accountNumber) { <br>    }<br><br>    public void deposit(int amount , int accountNumber){<br>    }<br>}</pre><p>In this example <strong><em>AccountOperations</em></strong> class do operations related to Account like <strong><em>addAccount</em></strong>(), <strong><em>updateAccount</em></strong>(), <strong><em>getAccount</em></strong>(). However deposit is something called as transaction which eventually not responsible by account. Adding this method violates Single Responsibility principle. To ensure Single Responsibility we have to Create new class which actually does Transaction Operations.</p><pre>public class AccountOperations {<br>    <br>    public void addAccount(Account account) {<br>    }<br><br>    public  void updateAccount(Account account) {<br>    }<br><br>    public Account getAccount(int accountNumber) {<br>    }<br>}</pre><pre>public class TransactionOperations {<br><br>    public void deposit(BigDecimal amount , int accountNumber){<br>    }<br><br>    public void withdraw(BigDecimal amount , int accountNumber){<br>    }<br>}</pre><p>Here we have isolated all the Account operations in a single class and create a new class for Transaction Operations like deposit and withdraw. By separating these responsibilities, each class has a single reason to change, adhering to the Single Responsibility Principle. This separation makes the code easier to understand, maintain, and extend.</p><h3>2.<strong>Open/Closed Principle (OCP)</strong></h3><p>This means, any class or interface we create should be opened for extension closed for modification.</p><p><strong>Why it matters:</strong> By designing your classes to be extendable without modifying their existing code, you protect your existing codebase from changes and reduce the risk of introducing bugs.</p><p>Lets see an example.</p><pre>public class Calculator {<br>    public int calculateNumber(int number1 , int number2 , String type){<br>        int result=0;<br>        switch (type){<br>            case &quot;sum&quot;:<br>                result = number1 + number2;<br>            case &quot;sub&quot;:<br>                result = number1 - number2;<br>        }<br>        return  result;<br>    }<br>}</pre><p>Suppose that this is the class we created for a calculator. If we want to add more operations like division or multiplication we have to modify this existing class. Doing this violates the opened/closed principle. Because we should not be allowed to modify the existing class. We are only allowed to extend the classes.</p><p>Lets see how we can follow opened/closed principle.</p><pre>public interface Operation {<br>    public int perform(int number1 , int number2);<br>}</pre><pre>public class AddOperation implements Operation{<br>    @Override<br>    public int perform(int number1, int number2) {<br>        return number1 + number2;<br>    }<br>}</pre><pre>public class SubstractOperation implements Operation{<br>    @Override<br>    public int perform(int number1, int number2) {<br>        return number1 - number2;<br>    }<br>}</pre><pre>public class Calculator {<br>    public int calculateNumber(int number1 , int number2 , Operation operation){<br>        return  operation.perform(number1 , number2);<br>    }<br>}</pre><p>Here we created an interface for the basic operation. Then we create separate classes for operations like adding, subtraction by implementing the operation interface. So, if we want to add a new operation like multiplication we can implement operation interface and override the operation method as we want. By implementing the classes like this we can ensure that our design follows opened/closed principle.</p><h3>3. <strong>Liskov Substitution Principle (LSP)</strong></h3><p>This means, any instance of a derived class should be substitutable for an instance of its base class without affecting the correctness of the program. That&#39;s mean, objects of a superclass should be replaceable with objects of a subclass without altering the correctness of the program. This means that the subclass should extend the capabilities of the superclass without changing its fundamental behavior.</p><p>Lets see an example.</p><pre>class Bird {<br>    public void fly() {<br>        System.out.println(&quot;Flying...&quot;);<br>    }<br>}</pre><pre>class Sparrow extends Bird {<br>  // Inherits the fly method from Bird<br>}</pre><pre>class Penguin extends Bird {<br>    @Override<br>    public void fly() {<br>        throw new UnsupportedOperationException(&quot;Penguins can&#39;t fly!&quot;);<br>    }<br>}</pre><p>In this example, <strong><em>Sparrow</em></strong> and <strong><em>Penguin</em></strong> classes are derives from the <strong><em>Bird</em></strong> class. But As we all know Penguin cannot fly. So in the Penguin class fly method changes its fundamental behavior. That violates the Liskov Substitution Principle.</p><p>Lets see how we can change the class design that aligns with Liskov Substitution Principle.</p><pre><br>class Bird {<br>    public void makeSound() {<br>        System.out.println(&quot;Bird sound&quot;);<br>    }<br>}</pre><pre>class FlyingBird extends Bird {<br>    public void fly() {<br>        System.out.println(&quot;Flying...&quot;);<br>    }<br>}</pre><pre>class Sparrow extends FlyingBird {<br>    // Inherits the fly method from FlyingBird<br>}</pre><pre>class Penguin extends Bird {<br>    // Penguins cannot fly, so no fly method here<br>}</pre><p>In this approach, the <strong><em>Bird</em></strong> class only has methods common to all birds, while the <strong><em>FlyingBird</em></strong> subclass has the Fly method. This way, substituting subclasses like <strong><em>Sparrow</em></strong> and <strong><em>Penguin</em></strong> maintains the program&#39;s correctness and adhere to the Liskov Substitution Principle.</p><h3>4. <strong>Interface Segregation Principle (ISP)</strong></h3><p>This means, no client should be forced to depend on methods it does not use. Simply it says, create smaller, more focused interfaces for specific use cases.</p><p><strong>Why it matters:</strong> By splitting large interfaces into smaller, more specific ones, you ensure that implementing classes only need to be concerned with the methods that are relevant to them.</p><p>Lets see an example.</p><pre>public interface Worker {<br>    void work();<br>    void eat();<br>}</pre><pre>public class HumanWorker implements Worker {<br>    @Override<br>    public void work() {<br>        // Human work<br>    }<br><br>    @Override<br>    public void eat() {<br>        // Human eat<br>    }<br>}</pre><pre>public class RobotWorker implements Worker {<br>    @Override<br>    public void work() {<br>        // Robot work<br>    }<br><br>    @Override<br>    public void eat() {<br>        throw new UnsupportedOperationException(&quot;Robots don&#39;t eat&quot;);<br>    }<br>}</pre><p>we have a <strong><em>Worker</em></strong> interface that has both w<strong><em>ork()</em></strong> and <strong><em>eat()</em></strong> methods. This design forces a <strong><em>RobotWorker</em></strong> to implement <strong><em>eat()</em></strong>, which it doesn&#39;t need, leading to an <strong><em>UnsupportedOperationException</em></strong>.</p><pre>public interface Workable {<br>    void work();<br>}<br><br>public interface Eatable {<br>    void eat();<br>}</pre><pre>public class HumanWorker implements Workable, Eatable {<br>    @Override<br>    public void work() {<br>        // Human work<br>    }<br><br>    @Override<br>    public void eat() {<br>        // Human eat<br>    }<br>}</pre><pre>public class RobotWorker implements Workable {<br>    @Override<br>    public void work() {<br>        // Robot work<br>    }<br>}</pre><p>By splitting the <strong><em>Worker</em></strong> interface into <strong><em>Workable </em></strong>and <strong><em>Eatable</em></strong> interfaces, we adhere to the ISP. This way, <strong><em>RobotWorker </em></strong>only implements <strong><em>Workable</em></strong>, and <strong><em>HumanWorker</em></strong> implements both <strong><em>Workable</em></strong> and <strong><em>Eatable</em></strong>.</p><h3>5. <strong>Dependency Inversion Principle (DIP)</strong></h3><p>This means, High-level classes should not depend on low-level classes. Both High-level and low-level classes should depend on abstractions.</p><p><strong>Why it matters:</strong> By depending on abstractions rather than concrete implementations, you make your code more flexible and easier to maintain.</p><p>Lets see an example.</p><pre>public class EmailSender {<br>    public void sendEmail(String message) {<br>        System.out.println(&quot;Sending email: &quot; + message);<br>    }<br>}</pre><pre>public class NotificationService {<br>    private EmailSender emailSender;<br><br>    public NotificationService() {<br>        this.emailSender = new EmailSender();<br>    }<br><br>    public void sendNotification(String message) {<br>        emailSender.sendEmail(message);<br>    }<br>}</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        NotificationService notificationService = new NotificationService();<br>        notificationService.sendNotification(&quot;Hello, this is a notification!&quot;);<br>    }<br>}</pre><p>In this example, a <strong><em>NotificationService</em></strong> class directly depends on a <strong><em>EmailSender</em></strong> class, making it difficult to extend the notification system to use other types of notifications (e.g., SMS, Push notifications).</p><p>Now, let’s refactor the code to follow the Dependency Inversion Principle. We’ll introduce an interface <strong><em>Notifier</em></strong> and make both <strong><em>NotificationService</em></strong> and <strong><em>EmailSender</em></strong> depend on this abstraction.</p><pre>public interface Notifier {<br>    void send(String message);<br>}</pre><pre>public class EmailSender implements Notifier {<br>    @Override<br>    public void send(String message) {<br>        System.out.println(&quot;Sending email: &quot; + message);<br>    }<br>}</pre><pre>public class SmsSender implements Notifier {<br>    @Override<br>    public void send(String message) {<br>        System.out.println(&quot;Sending SMS: &quot; + message);<br>    }<br>}</pre><pre><br>public class NotificationService {<br>    private Notifier notifier;<br><br>    public NotificationService(Notifier notifier) {<br>        this.notifier = notifier;<br>    }<br><br>    public void sendNotification(String message) {<br>        notifier.send(message);<br>    }<br>}</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        Notifier emailSender = new EmailSender();<br>        Notifier smsSender = new SmsSender();<br><br>        NotificationService emailNotificationService = new NotificationService(emailSender);<br>        emailNotificationService.sendNotification(&quot;Hello, this is an email notification!&quot;);<br><br>        NotificationService smsNotificationService = new NotificationService(smsSender);<br>        smsNotificationService.sendNotification(&quot;Hello, this is an SMS notification!&quot;);<br>    }<br>}</pre><p>Here the <strong><em>Notifier</em></strong> interface provides an abstraction for different types of notification senders (<strong><em>EmailSender</em></strong>, <strong><em>SmsSender</em></strong>). The <strong><em>NotificationService</em></strong> class now depends on the <strong><em>Notifier</em></strong> abstraction rather than concrete implementations like <strong><em>EmailSender</em></strong>. This setup allows the <strong><em>NotificationService</em></strong> to work with any type of notifier that implements the <strong><em>Notifier</em></strong> interface, making the code more flexible and easier to maintain or extend.</p><p>So, the next time you find yourself frustrated with a piece of messy code, take a step back and see which SOLID principles might help you clean it up. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58d68a6624e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Email Verification with Nodemailer.]]></title>
            <link>https://medium.com/@isuru99/email-verification-with-nodemailer-e8ca35d254c7?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8ca35d254c7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nodemailer]]></category>
            <category><![CDATA[develpment]]></category>
            <category><![CDATA[email-verification]]></category>
            <category><![CDATA[verification]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 05:39:40 GMT</pubDate>
            <atom:updated>2024-04-02T05:39:40.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlHOKIHEL7sor-n0Ik3rBA.png" /></figure><p>Email verification is a crucial aspect of user authentication in web applications, ensuring that users provide valid email addresses and confirming their identities. In this blog post, we’ll discuss how to build an email verification system using Node.js.</p><p>First of all, let’s understand the logic behind this process one by one.</p><ol><li>Add two properties called <strong><em>isVerifiedEmail </em></strong>and<strong><em> emailToken </em></strong>to the user model. (These properties are used to identify whether each profile has a verified email or not.)</li><li>Send an email with a verification link to the email that was entered by the user when they signed up for the system.</li><li>When users click on that verification link, a request should be sent to the server. Then update the <strong><em>isVerifiedEmail</em></strong> property to true and make the value of <strong><em>emailToken to </em></strong>null.</li></ol><p>Let’s implement this practically with a Nodejs backend. These will be used here;</p><ol><li>MySQL and Sequalize (As the database)</li><li>Gmail ( As the email Service provider)</li><li>Nodemailer ( As email service )</li><li>crypto (To generate the email token)</li></ol><p>This is how your file structure should be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*aGkgwBqElAhrn0Wv0z6Org.png" /></figure><h3>1. Create the express backend</h3><pre>const express = require(&quot;express&quot;)<br>const bodyparser = require(&quot;body-parser&quot;);<br>const cors = require(&quot;cors&quot;);<br><br><br>const db = require(&quot;./models&quot;)<br>const userRoutes = require(&quot;./UserRoute&quot;);<br>const app = express()<br>app.use(express.json())<br><br><br>//middleware<br>app.use(cors());<br><br>app.use(bodyparser.json());<br>app.use(&quot;/api/user&quot;, userRoutes); <br>app.use((err, req, res, next) =&gt; {<br>  console.log(err); <br>  res.status(err.status || 500).send(&quot;Something went wrong!&quot;);<br>});<br><br>db.sequelize.sync().then(() =&gt; {<br>  app.listen(3000, () =&gt; {    <br>    console.log(&quot;Server running on port 3000&quot;);<br>  }); <br>});                  </pre><h3>2. Create the basic model for user</h3><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const User = sequelize.define(&quot;User&quot;, {<br>    email: {<br>      type: DataTypes.STRING,<br>      allowNull: false,<br>    },<br>    password: {<br>      type: DataTypes.STRING,<br>      allowNull: false,<br>    },<br>    isVerifiedEmail: {<br>      type:DataTypes.BOOLEAN,<br>      defaultValue: false,<br>    },<br>    emailToken: {<br>      type: DataTypes.STRING,<br>      <br>    },<br><br>  });<br><br>  return User;<br>};</pre><p>Here, we assume the user enters only the user name and password in the signup process. The default value of <strong><em>isVerifiedEmail </em></strong>is false. That means when a user registers with the system, their email is still not verified.</p><h3>3.Create the route for user Signup</h3><pre>const express = require(&quot;express&quot;);<br>const router = express.Router();<br>const crypto = require(&quot;crypto&quot;);<br>const sendMail = require(&quot;./sendMail&quot;);<br>const { User } = require(&quot;./models&quot;);<br><br><br>router.post(&quot;/register&quot;, async (req, res) =&gt; {<br>  try {<br>    const { email, password } = req.body;<br>    const emailToken = crypto.randomBytes(64).toString(&quot;hex&quot;);<br>    // Create the user in the database<br>    const newUser = await User.create({<br>      email,<br>      password,<br>      emailToken,<br>    });<br><br>    sendMail(email, emailToken);<br>    res.status(201).json({ message: &quot;User created successfully&quot; });<br>  } catch (error) {<br>    console.error(&quot;Error creating user:&quot;, error);<br>    res.status(500).json({ message: &quot;Internal server error&quot; });<br>  }<br>});</pre><p>In the “<strong><em>/register</em></strong>” endpoint, we create a user from the values entered by the user and send an verification email.</p><h3>4. Implement email sending functionality</h3><pre>const nodemailer = require(&quot;nodemailer&quot;);<br><br>const sendMail = (email,emailToken) =&gt; {<br>    const transporter = nodemailer.createTransport({<br>        service: &quot;gmail&quot;,<br>        host: &quot;smtp.gmail.com&quot;,<br>        port: 587, <br>        secure: false, <br>        auth: {<br>          user: &quot;Enter your gemail here&quot;,<br>          pass: &quot;Enter your app password here&quot;,<br>        },<br>    });<br><br>    const mailOptions = {<br>        from: &#39;&quot;Your company&quot; &lt;your email&gt;&#39;,<br>        to: `${email}`,<br>        subject: &#39;Please verify your email...&#39;,<br>        html:`&lt;p&gt;Hello, verify your email address by clicking on this&lt;/p&gt;<br>        &lt;br&gt;<br>        &lt;a href=&quot;http://localhost:5173/verify-email?emailToken=${emailToken}&quot;&gt;Click here to verify&lt;/a&gt;<br>        `<br>    };<br><br>    transporter.sendMail(mailOptions, function(error, info){<br>        if (error) {<br>          console.log(error);<br>        } else { <br>          console.log(&#39;Email sent: &#39; + info.response);<br>        }<br>    });<br>}<br>  <br>module.exports = sendMail;</pre><p>We are using Gmail as the email service provider here. You need to enter your email and app password for your Gmail. Refer <a href="https://www.youtube.com/watch?v=lSURGX0JHbA">this</a> to find your app password for Gmail. This mailOptions object is a configuration used for sending an email. It includes details such as the sender&#39;s email address, the recipient&#39;s email address, the subject of the email, and the HTML content of the email body.<br>In the HTML content &lt;a&gt; tag contains a hyperlink to the frontend of the application (<strong><em>http://localhost:5173/verify-email?emailToken=${emailToken}</em></strong> )</p><p>Lets breakdown it into parts.</p><ul><li>http://localhost:5173/: This is the base URL of the web application. localhost refers to the frontend, and 5173 is the port number on which the web server is running. So, the web application is accessible at port 5173.</li><li>/verify-email: This part of the URL is an endpoint within the web application. User is being directed to a endpoint for email verification.</li><li>?emailToken=${emailToken}: This is a query parameter appended to the URL. Query parameters are used to pass data to the frontend of the application. Here, we are passing a key as emailToken. The value of emailToken will be dynamically inserted into the URL when the email is sent, this allows server to identify and verify the user&#39;s email address. Here value of emailToken is the the random string generated by <strong><em>crypto </em></strong>library.</li></ul><h3>4. Create a function in the frontend of the application to verify email</h3><pre>import React, { useEffect, useState } from &#39;react&#39;<br>import axios from &#39;axios&#39;; // Import axios<br>import { useLocation } from &#39;react-router-dom&#39;; // Import useLocation<br><br>function VerifyUserEmail() {<br>    const location = useLocation();<br>    const [isVerified, setisVerified] = useState(false);<br><br>    useEffect(()=&gt;{<br>        const handle = async () =&gt; {<br>            try {<br>                const params = new URLSearchParams(location.search);<br>                const emailToken = params.get(&#39;emailToken&#39;);<br>                const response = await axios.patch(&#39;http://localhost:3000/api/user/verifyemail&#39;, {<br>                    emailToken: emailToken<br>                });<br>                <br>                if(response.data.status === &quot;Success&quot;){<br>                    setisVerified(true);<br>                }<br><br>                console.log(response);<br>            } catch (error) {<br>              console.log(error);<br>            }<br>        };<br>        handle();<br>    },[]) <br><br>    return (<br>        &lt;div&gt;<br>            <br>            {isVerified ? &lt;h1&gt;Your email has been verified&lt;/h1&gt; : &lt;h1&gt;Verifying your email...&lt;/h1&gt;}<br>        &lt;/div&gt;<br>    )<br>}<br><br>export default VerifyUserEmail;</pre><p>So after the user clicks on the link in the email, they will be redirected to this page. Here we get the value of the emailToken from the <strong><em>useLocation </em></strong>hook<strong><em>. </em></strong>After that, we send a patch request to the backend. There, we send the value of emailToken in the request body.</p><h3>5. Create routes for user email verification</h3><pre>const express = require(&quot;express&quot;);<br>const router = express.Router();<br>const crypto = require(&quot;crypto&quot;);<br>const sendMail = require(&quot;./sendMail&quot;);<br>const { User } = require(&quot;./models&quot;);<br><br><br>router.post(&quot;/register&quot;, async (req, res) =&gt; {<br>  try {<br>    const { email, password } = req.body;<br>    const emailToken = crypto.randomBytes(64).toString(&quot;hex&quot;);<br>    // Create the user in the database<br>    const newUser = await User.create({<br>      email,<br>      password,<br>      emailToken,<br>    });<br><br>    sendMail(email, emailToken);<br>    <br><br>    // Respond with success<br>    res.status(201).json({ message: &quot;User created successfully&quot; });<br>  } catch (error) {<br>    console.error(&quot;Error creating user:&quot;, error);<br>    res.status(500).json({ message: &quot;Internal server error&quot; });<br>  }<br>});<br><br>router.patch(&quot;/verifyemail&quot;, async (req, res) =&gt; {<br>  <br>  const emailToken = req.body.emailToken;<br>  console.log(emailToken)<br>  if (!emailToken) {<br>    return res.status(400).json({ status: &quot;Failed&quot;, error: &quot;empty request&quot; });<br>  }<br>  let user = await User.findOne({ where: { emailToken: emailToken } });<br><br>  if (!user) {<br>    return res.status(404).json({ status: &quot;Failed&quot;, error: &quot;User not found&quot; });<br>  }<br><br>  await User.update(<br>    { isVerifiedEmail: true, emailToken: null },<br>    { where: { emailToken: emailToken } }<br>  );<br>  await User.findOne({ where: { emailToken: emailToken } });<br>  return res<br>    .status(200)<br>    .json({ status: &quot;Success&quot;, message: &quot;User verified successfully&quot; });<br>});<br><br>module.exports = router;</pre><p>So after receiving the patch request to the server, it checks if there any user account associated with this emaiToken. So if there is any user with that token, <strong><em>isVerifiedEmail </em></strong>property of that user will be set to true. Also, the value of emailToken value will be set to null.</p><p>Remember, the goal of email verification is not just to validate user email addresses but also to instill confidence in your users and protect your application from potential threats. With a well-implemented email verification system, you can establish a trusted relationship with your users and maintain the integrity of your platform.</p><p>So, go ahead and implement email verification in your Node.js application. Following the steps outlined above, and enjoy the benefits of a more secure and trustworthy authentication process. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8ca35d254c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why we need ORM]]></title>
            <link>https://medium.com/@isuru99/why-we-need-orm-54f65bdc2e3e?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/54f65bdc2e3e</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[sequelize]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 02:55:17 GMT</pubDate>
            <atom:updated>2024-03-03T02:55:17.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEeJ0MjUul1DQ5y0QU4e2g.png" /></figure><h3>What are ORMs</h3><p>So what is an ORM? It stands for Object-Relational Mapping. It’s a programming technique used in software development to bridge the gap between the object-oriented programming paradigm and relational databases.</p><p>In traditional relational database systems, data is stored in tables consisting of rows and columns. These tables have relationships defined by keys (primary and foreign keys). However, when we work with object-oriented programming languages like Java, Python, or C#, data is typically represented as objects with attributes and methods. <br>ORM frameworks provide a way to map these object-oriented concepts to relational database structures.</p><h3>Simple terms</h3><p>In simple terms, ORM acts as a bridge between your application code (written in an object-oriented language like Python, Java, etc.) and your database (which typically stores data in tables, rows, and columns). Instead of writing SQL queries directly, you work with objects in your code, and the ORM translates these objects into database operations.</p><p>For example, if you have a Python class representing a “User” in your application, the ORM can handle tasks like saving a new user to the database, retrieving existing users, updating user information, and deleting users. All these operations are done through the ORM’s methods, without you needing to write raw SQL queries. Essentially, ORM simplifies database interaction by allowing you to work with your database using the programming language’s native objects and methods rather than dealing directly with SQL.</p><h3><strong>Advantages of ORMs</strong></h3><ol><li><strong>Increased Productivity:</strong><br>ORM frameworks abstract away the complexities of database interactions, allowing developers to work with objects and classes instead of writing raw SQL queries.</li><li><strong>Object-Oriented Paradigm:</strong><br>ORMs align database operations with the object-oriented programming paradigm, making it easier for developers to model and manipulate data using familiar concepts such as classes, objects, and inheritance. This alignment enhances code readability, maintainability, and reusability.</li><li><strong>Automatic Schema Generation:</strong><br>Many ORM frameworks offer features for the automatic generation of database schemas based on object mappings. This eliminates the need for manual schema creation and synchronization, streamlining the database deployment process and reducing human error.</li><li><strong>Cross-Platform Compatibility:</strong><br>ORM frameworks are often compatible with multiple programming languages and platforms. Developers can use the same ORM library across different projects or platforms, enhancing code consistency and reducing learning curves.</li></ol><h3>Popular ORMS</h3><p>ORMs are available for various backend frameworks and programming languages.</p><ol><li><strong>Sequelize: (Node.js)</strong></li></ol><p>A promise-based ORM for Node.js that supports multiple database systems, including MySQL, PostgreSQL, SQLite, and MSSQL. Sequelize provides a wide range of features, such as model definition, associations, validation, and transactions.</p><p><strong>2. Hibernate: (Spring Boot)</strong></p><p>One of the most popular ORM frameworks for Java, Hibernate, is often used with Spring Boot applications. It simplifies database interactions by mapping Java objects to database tables and providing features like lazy loading, caching, and automatic schema generation.</p><p><strong>3. Entity Framework Core: (.NET)</strong></p><p>Microsoft’s official ORM framework for.NET Core and ASP.NET Core applications. Entity Framework Core enables developers to work with databases using LINQ queries and offers features such as automatic migrations, code-first development, and database seeding.</p><p><strong>4. Django ORM: (Django)</strong></p><p>Built-in ORM provided by the Django web framework for Python. It offers an intuitive way to interact with databases using Python objects and provides features such as querysets, model relationships, and migrations.</p><p>Now, let’s see how we can use sequelize with a Node.js backend and MySQL database.</p><p>First, create a Node.js backend. Your folder structure should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*QZg8P6YN4TSHtB8oRJW-JA.png" /></figure><p>Before getting started, you should install several dependencies. You can follow this command for that.</p><pre>npm i express fs mysql2 path sequelize sequelize-cli</pre><p>The <strong><em>config.json</em> </strong>file specifies the database connection details for different environments, such as development, test, and production. For this example, give your database credentials under<strong> development</strong>.</p><pre>{<br>  &quot;development&quot;: {<br>    &quot;username&quot;: &quot;root&quot;,<br>    &quot;password&quot;: &quot;1234&quot;,<br>    &quot;database&quot;: &quot;test&quot;,<br>    &quot;host&quot;: &quot;localhost&quot;,<br>    &quot;dialect&quot;: &quot;mysql&quot;<br>  },<br>  &quot;test&quot;: {<br>    &quot;username&quot;: &quot;root&quot;,<br>    &quot;password&quot;: null,<br>    &quot;database&quot;: &quot;database_test&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;mysql&quot;<br>  },<br>  &quot;production&quot;: {<br>    &quot;username&quot;: &quot;root&quot;,<br>    &quot;password&quot;: null,<br>    &quot;database&quot;: &quot;database_production&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;mysql&quot;<br>  }<br>}</pre><p>Inside the models, you can create tables in your database. First, create the <strong>Customer</strong> table as a model.</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const Customer = sequelize.define(&quot;Customer&quot;, {<br>    name: {<br>      type: DataTypes.STRING,<br>      allowNull: false,  <br>    },<br>    email: {<br>      type: DataTypes.STRING,<br>      allowNull: false, <br>      primaryKey: true <br>    },<br>    address: {<br>      type: DataTypes.STRING,<br>      allowNull: false,<br>    },<br>    phone: {<br>      type: DataTypes.STRING,<br>      allowNull: false,<br>    }<br><br>  });<br><br>  Customer.associate = models =&gt; {<br>    Customer.hasMany(models.Order, {<br>      foreignKey: &#39;customerEmail&#39;, // Assuming customerEmail is the foreign key in the Order table referencing Customer&#39;s email<br>      as: &#39;orders&#39; // This will allow you to access a customer&#39;s orders using `customer.orders`<br>    });<br>  };<br> <br>  return Customer;<br>};</pre><p>Then, Let’s create the <strong>Order </strong>table</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const Order = sequelize.define(&quot;Order&quot;, {<br>    orderId: {<br>      type: DataTypes.STRING,<br>      allowNull: false,<br>      primaryKey: true,<br>    },<br>    totalAmount: {<br>      type: DataTypes.FLOAT,<br>      allowNull: false,<br>    },<br>  });<br><br>  Order.associate = (models) =&gt; {<br>    Order.belongsTo(models.Customer, {<br>      foreignKey: &quot;customerEmail&quot;, // Assuming customerEmail is the foreign key in the Order table referencing Customer&#39;s email<br>      targetKey: &quot;email&quot;, // The target key in the Customer table to which the foreign key in the Order table refers<br>    });<br>  };<br><br>  return Order;<br>};</pre><p>In the customer table, email is the primary key. In the Order table, orderId is the primary key. There is a one to many relationship between Customer and order (the Customer has many orders). The index.js file will be added automatically when you are installing “<strong><em>sequelize</em></strong>” and “sequelize-cli.”.</p><p>Your main index.js file should look like this:</p><pre>const express = require(&quot;express&quot;);<br>const db = require(&quot;./models&quot;);<br>const app = express();<br>app.use(express.json());<br><br>db.sequelize.sync({ force: true }).then(() =&gt; {<br>  app.listen(3001, () =&gt; {<br>    console.log(&quot;Server running on port 3001&quot;);<br><br>    db.Customer.create({<br>      name: &quot;John Doe&quot;,<br>      email: &quot;john@example.com&quot;,<br>      address: &quot;123 Main St&quot;,<br>      phone: &quot;555-1234&quot;,<br>    })<br>      .then((customer) =&gt; {<br>        console.log(&quot;Customer created:&quot;, customer);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&quot;Error creating customer:&quot;, error);<br>      });<br><br>    db.Order.create({<br>      orderId: &quot;123456789&quot;,<br>      totalAmount: 100.0,<br>      customerEmail: &quot;john@example.com&quot;,<br>    })<br>      .then((order) =&gt; {<br>        console.log(&quot;Order created:&quot;, order);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&quot;Error creating order:&quot;, error);<br>      });<br>  });<br>});</pre><p>Here first, we have to set up an Express backend server, and after that, synchronize the sequelize models with the database using the <strong><em>sequelize.sync() </em></strong>method, and then start the server on port 3001.</p><p>Then let’s see how we can add data to the Customer and Order tables. Without ORMs, you have to write queries like <strong><em>INSERT INTO Customer values(“John Doe”,…).</em></strong> But with the aid of ORMs, it’s not that hard. You just need to pass the respective values to the <strong>create </strong>method of the relevant model, as in the above example.</p><p>In conclusion, Object-Relational Mapping (ORM) is a powerful technique that simplifies database interactions in software development by bridging the gap between object-oriented programming languages and relational databases. In this blog, we explored how to use Sequelize, a popular ORM for Node.js, with a MySQL database. Through a step-by-step guide, we learned how to set up a Node.js backend, define models for database tables, establish associations between models, and perform operations using Sequelize methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54f65bdc2e3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User Authentication with JWT]]></title>
            <link>https://medium.com/@isuru99/user-authentication-with-jwt-62d40f83f6bb?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/62d40f83f6bb</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt-auth]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 16:56:42 GMT</pubDate>
            <atom:updated>2024-02-05T16:56:42.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7pj7PmFaRfHtiz3p" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=medium&amp;utm_medium=referral">FlyD</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JSON Web Token (JWT) authentication has become a popular choice for securing web applications due to its simplicity, scalability, and versatility. In this comprehensive guide, let’s dive into the details of JWT authentication, covering its structure, working principles, advantages, and implementation considerations.</p><h3><strong>1. What is JWT?</strong></h3><p>Imagine a digital passport for your online identity. That’s essentially what a JWT is. It’s a self-contained, cryptographically signed piece of information passed between parties (usually a client and a server) to verify authorization and grant access to protected resources. This JWT comprises three parts:</p><p><strong><em>1. Header:</em></strong></p><p>The header typically consists of two parts: the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p><strong><em>2. Payload:</em></strong></p><p>The second part of the token is the payload, which contains claims. Claims are statements about an entity (typically like user ID, roles, expiration time, etc.)</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;kamal&quot;,<br>  &quot;iat&quot;: 1516239022<br>}</pre><p><strong><em>3.</em></strong><em> </em><strong><em>Signature:</em></strong></p><p>To create the signature part, the encoded header, encoded payload, and a secret key are used. The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way.</p><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; +<br>  base64UrlEncode(payload),<br>  secret<br>)</pre><h3><strong>2. How JWT Works:</strong></h3><ol><li><strong><em>Token Creation:</em></strong></li></ol><p>The server creates a JWT by encoding the header and payload, and then signing it with a secret key.</p><p>2.<strong> <em>Token Transmission:</em></strong></p><p>The JWT can be transmitted between parties (usually in the Authorization header of an HTTP request) without the need for the parties to share a password.</p><p><strong>3. <em>Token Verification:</em></strong></p><p>The recipient (server) of the JWT can verify its authenticity by decoding it and comparing the computed signature against the one included in the JWT. If they match, it indicates that the token is valid.</p><h3>3. How JWT differ from Traditional Authentication</h3><ol><li><strong><em>Statelessness:</em></strong></li></ol><p>Traditional authentication often involves maintaining a session state on the server. After a user logs in, the server stores information about the user’s session, requiring server-side storage and management. JWT is stateless. The token itself contains all the necessary information about the user, eliminating the need for the server to store session data. This statelessness contributes to scalability and reduces server-side storage requirements</p><p>2. <strong><em>Data Format:</em></strong></p><p>Traditional authentication involves the exchange of credentials (username and password) for a session ID or token, usually stored in cookies. JWTs use a compact, URL-safe format to represent claims. They consist of a header, payload, and signature, and they are often transmitted in the Authorization header of an HTTP request.</p><p><strong><em>3. Scalability:</em></strong></p><p>Session-based authentication can lead to challenges in scalability, especially in systems with a large number of concurrent users. Maintaining session state requires server resources. JWTs more scalable because of the Stateless nature and decentralized verification. Each request contains the necessary information for authentication, reducing the server’s dependency on session management.</p><p><strong><em>4. Token Expiration and Refresh Tokens:</em></strong></p><p>Session-based systems may rely on short-lived session IDs, but refreshing the session often requires additional server requests. JWTs can include an expiration time, and refresh tokens can be used to obtain a new access token without requiring the user to re-enter credentials</p><p><strong><em>5. Decentralized Authentication</em></strong></p><p>Traditional authentication often relies on a centralized server to manage session state and validate user identity. JWTs support decentralized authentication. Different services or microservices can independently verify JWTs without a centralized authentication server.</p><h3><strong>4. Best Practices for JWT Authentication</strong></h3><p>When JWT authentication implemented correctly, provides a secure and efficient way to handle user authentication in web applications. However, to ensure the integrity and confidentiality of the authentication process, it’s essential to follow best practices.</p><p><strong><em>1. Use HTTPS</em></strong></p><p>Always use HTTPS to encrypt data in transit. This prevents man-in-the-middle attacks and ensures that the token is transmitted securely between the client and the server.</p><p><strong><em>2. Token Expiration</em></strong></p><p>Set a reasonable expiration time for JWTs to limit their validity. This mitigates the risk of stolen or intercepted tokens being misused for an extended period.</p><p><strong><em>3. Secret Key Security</em></strong></p><p>Keep the secret key used for signing JWTs confidential. Use strong, unique keys, and avoid hardcoding them in your codebase. Consider using environment variables to store sensitive information.</p><p><strong><em>4. Avoid Storing Sensitive Information</em></strong></p><p>Do not include sensitive information in the JWT payload. JWTs are not meant for storing confidential data.</p><p><strong><em>5. Token Refreshing</em></strong></p><p>Consider using refresh tokens for a more secure token rotation mechanism. Refresh tokens can be used to obtain a new access token without requiring the user to re-enter their credentials.</p><h3>5. Implementing JWT with Nodejs</h3><p>Lets see how we can implement user authentication with Nodejs</p><p>First create a Nodejs backend in your local machine. Here is the command. This will install the basic necessary dependencies for this project.</p><pre>npm init<br>npm install express bodyparser cors cookieParser jwt</pre><p>Then create a index.js file and add following codes.</p><p><strong>1. Express Setup</strong></p><pre>const express = require(&quot;express&quot;);<br>const bodyparser = require(&quot;body-parser&quot;);<br>const cors = require(&quot;cors&quot;);<br>const cookieParser = require(&quot;cookie-parser&quot;);<br>const jwt = require(&quot;jsonwebtoken&quot;);<br>const app = express();</pre><ul><li>This section imports the necessary packages/modules: express for creating the server, body-parser for parsing request bodies, cors for handling Cross-Origin Resource Sharing, cookie-parser for parsing cookies, and jsonwebtoken for working with JSON Web Tokens (JWT).</li><li>It initializes an Express application using express().</li></ul><p><strong>2. Middleware Setup</strong></p><pre>app.use(express.json());<br>app.use(cookieParser());<br>const PORT = 3000;<br>app.use(cors());<br>app.use(bodyparser.json());</pre><p><strong>3.Login Endpoint</strong></p><pre>app.post(&quot;/login&quot;, async (req, res) =&gt; {<br>  try {<br>    const { email, password } = req.body;<br><br>    if (email == &quot;test@gmail.com&quot; &amp;&amp; password == &quot;123&quot;) {<br>      const accessToken = jwt.sign(email, &quot;key&quot;);<br>      res.cookie(&quot;token&quot;, accessToken);<br>      res.json({ Status: &quot;Success&quot; });<br>    } else {<br>      return res.status(401).send(&quot;Invalid credentials&quot;);<br>    }<br>  } catch (error) {<br>    res.json({ Status: &quot;Falied to login&quot; });<br>  }<br>});</pre><ul><li>This route handles the POST request to “/login”. It expects an email and password in the request body.</li><li>If the provided credentials match a hardcoded set (&quot;test@gmail.com&quot; and &quot;123&quot;), it generates a JWT using jwt.sign and sets it as a cookie named &quot;token&quot;.</li><li>If the credentials are incorrect, it returns a 401 status with the message “Invalid credentials”.</li></ul><p><strong>4. Authentication Middleware</strong></p><pre>function authenticate(req, res, next) {<br>  try {<br>    const token = req.cookies.token;<br>    const decoded = jwt.verify(token, &quot;key&quot;);<br>    next();<br>  } catch (e) {<br>    res.status(401).send({ error: &quot;please authenticate&quot; });<br>  }<br>}</pre><ul><li>This middleware function (authenticate) checks if there is a valid JWT in the &quot;token&quot; cookie. If not, it sends a 401 status response with the message &quot;please authenticate&quot;.</li><li>If the token is valid, it calls the next() function, allowing the request to proceed to the next middleware or route.</li></ul><p><strong>5. Dashboard Endpoint</strong></p><pre>app.get(&quot;/dashboard&quot;, authenticate, async (req, res) =&gt; {<br>  res.json({ Status: &quot;Success&quot;});<br>});</pre><ul><li>This route (“/dashboard”) is protected by the authenticate middleware. Only requests with a valid JWT in the &quot;token&quot; cookie can access this route.</li><li>If the request passes authentication, it responds with a JSON object containing “Success” and some data (req.name is expected, but it seems to be missing in the code).</li></ul><p><strong>6. Error Handling Middleware</strong></p><pre>app.use((err, req, res, next) =&gt; {<br>  console.log(err);<br>  res.status(err.status || 500).send(&quot;Something went wrong!&quot;);<br>});</pre><p>This is a generic error-handling middleware. If any error occurs in the previous middleware or routes, it logs the error and sends a generic error message with an appropriate status code (defaults to 500 Internal Server Error).</p><p><strong>7.Server Listening</strong></p><pre>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on http://localhost:${PORT}`);<br>});</pre><p>This starts the server on the specified port (3000 in this case) and logs a message to the console when the server is successfully running.</p><h3>6. Testing</h3><p>Here I am using Thunder client extension in Vs code. But you can use postman as well.</p><p>First lets send a post request to check the login functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*u4SUBOdEAGgk_HDQ0F3uKw.png" /></figure><p>After sending a post request for login, a token will be sent back to the browser. You can view it on the Cookies tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*Smgfrb0Gj9eJ-N-DvfIfIg.png" /></figure><p>Then you can access the route (“/dashboard”) which is protected by the authenticate middleware. Because now you have a valid token in your client side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*pXWayfSbYXlxnBRlSETutQ.png" /></figure><p>If you delete the token from cookies you can not access the (“/dashboard”) route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*3iLVNRzV0W2DMFdoiylLrw.png" /></figure><p>That is how you can authenticate users and protect routes of a web application. Note that in real-world scenario you have to follow the best practices like hashing the passwords when users a registering to your system, pass an object as the payload instead of just the email when creating a token, use environment variables or a secure configuration management system to store sensitive information like jwt secret key.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62d40f83f6bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the World of Wireless Communication: My Journey with the NRF24 Module]]></title>
            <link>https://medium.com/@isuru99/exploring-the-world-of-wireless-communication-my-journey-with-the-nrf24-module-35b6a4856a26?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/35b6a4856a26</guid>
            <category><![CDATA[wireless-communication]]></category>
            <category><![CDATA[nrf24l01]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 04:26:50 GMT</pubDate>
            <atom:updated>2024-01-16T04:26:50.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Caxq0mwDvj5mVqFS" /><figcaption>Photo by <a href="https://unsplash.com/@maculan?utm_source=medium&amp;utm_medium=referral">Julien Maculan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever wondered about the inner workings of these wireless connections or how you could create your own wireless communication system? That’s where the NRF24 module comes into play. The NRF24 module is a small, affordable, and versatile piece of hardware that allows you to establish wireless communication between various electronic devices. Whether you’re an electronics hobbyist, a DIY enthusiast, or just curious about the world of wireless technology, this blog will introduce you to the fascinating world of NRF24 modules.</p><p>These modules are transceiver modules. That means same module can act as both transmitter and receiver.</p><p>Let’s see some features of nrf24 modules</p><ol><li><strong>Low Power Consumption</strong></li></ol><p>Typically operates at 3.3V, but can support a voltage range of 1.9V to 3.6V. And best of all, it consumes 26 μA in standby mode and 900 nA at power down mode. So, they’re the best wireless devices for low-power applications. ( Refer datasheet more details : <a href="https://www.nordicsemi.com/products/nrf24-series">https://www.nordicsemi.com/products/nrf24-series</a> )</p><p><strong>2. Adjustable Parameters</strong></p><p><strong>Data Rate</strong>: You can configure data rates as 250 kbps, 1 Mbps, and 2 Mbps.</p><p><strong>Transmit power</strong>: Adjustable transmit power levels ranging from -18 dBm to 0 dBm (in 6 dBm steps). Maximum output power is typically 0 dBm (1 mW).</p><p><strong>RF Channels</strong>: 126 available RF channels to choose from for communication.</p><p><strong>3. Supports SPI protocol.</strong></p><p>The NRF24L01 module and microcontrollers like Arduino communicate with each other using the Serial Peripheral Interface (SPI) protocol. This protocol commonly used to transfer data between microcontrollers, sensors, memory devices, and other peripheral devices.</p><p><strong>4. It operates in the 2.4 GHz ISM band</strong></p><p>ISM stands for “Industrial, Scientific, and Medical.” It’s a frequency band that has been reserved by regulatory bodies in many countries for non-licensed use. That’s means you can freely use these frequencies for communication. The NRF24 module operates at a specific frequency within the ISM band, which is 2.4 gigahertz (GHz). This frequency range is also commonly used by other wireless technologies, such as Wi-Fi, Bluetooth, and some microwave ovens.</p><p>Now let’s see how to establish a connection between two nrf24 modules. For that what you just need is two nrf4 modules and two microcontrollers (Eg: Arduino uno).</p><p>First you have to connect pins of the nrf24 module to the microcontroller accordingly. ( Refer this : <a href="https://projecthub.arduino.cc/tmekinyan/how-to-use-the-nrf24l01-module-with-arduino-813957">https://projecthub.arduino.cc/tmekinyan/how-to-use-the-nrf24l01-module-with-arduino-813957</a>).</p><p>Then you can upload the code for both transmitter and receiver.</p><p>Transmitter code.</p><pre>#include &lt;SPI.h&gt;<br>#include &lt;nRF24L01.h&gt;<br>#include &lt;RF24.h&gt;<br><br>RF24 radio(9, 10); // CE, CSN<br><br>void setup() {<br>  radio.begin();<br>  radio.openWritingPipe(0xF0F0F0E1LL); // Set the address for the receiver<br>  radio.setPALevel(RF24_PA_LOW);       // Set the power level low to conserve energy<br>  radio.stopListening();                // Put the radio in transmit mode<br>}<br><br>void loop() {<br>  char text[] = &quot;Hello, World!&quot;;<br>  radio.write(&amp;text, sizeof(text)); // Send the message<br>  delay(1000);                      // Send every 1 second<br>}</pre><p>Receiver code :</p><pre>#include &lt;SPI.h&gt;<br>#include &lt;nRF24L01.h&gt;<br>#include &lt;RF24.h&gt;<br><br>RF24 radio(9, 10); // CE, CSN<br><br>void setup() {<br>  Serial.begin(9600);<br>  radio.begin();<br>  radio.openReadingPipe(1, 0xF0F0F0E1LL); // Set the same address as the transmitter<br>  radio.setPALevel(RF24_PA_LOW);          // Set the power level low to conserve energy<br>  radio.startListening();                 // Put the radio in receive mode<br>}<br><br>void loop() {<br>  if (radio.available()) {<br>    char text[32] = &quot;&quot;;<br>    radio.read(&amp;text, sizeof(text)); // Read the incoming message<br>    Serial.println(text);<br>  }<br>}</pre><p>Here what we have done is sending a text message called “hello word” continuously within a one second delay. In the receiver’s end we are waiting for message and when we receive it, we print it on the serial monitor.</p><p>Not only just text messages but also you can do audio transmission as well. For that you can use an audio handling library such as RF24Audio.We have developed a Miner Safety Helmet for our first-year hardware project. There we have enabled two-way voice communication between two stations using nrf24 modules. If you are interested in how we have handled audio transmission feel free to refer this. ( <a href="https://github.com/isuruij/Miner-Safety-Helmet">https://github.com/isuruij/Miner-Safety-Helmet</a> )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35b6a4856a26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with MongoDB]]></title>
            <link>https://medium.com/@isuru99/getting-started-with-mongodb-6d4fbc93e0c3?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d4fbc93e0c3</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database-connection]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 05:37:12 GMT</pubDate>
            <atom:updated>2024-01-12T05:37:12.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dAtQ65LVZpLOd9tX" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When it comes to database management systems, MongoDB stands out as a powerful and flexible NoSQL solution. If you’re considering integrating MongoDB into your application, the first question that might come to mind is, “How can I get a MongoDB database?” In this blog post, we’ll explore various methods and platforms that allow you to access a MongoDB database and how to connect it with your backend.</p><h3><strong>1. MongoDB Atlas — The Cloud Platform:</strong></h3><p>MongoDB Atlas is MongoDB’s fully managed cloud database service, providing an easy and efficient way to deploy, manage, and scale MongoDB databases. There are special benefits of using MongoDB Atlas, including automatic backups, global clusters, and seamless integration with major cloud providers such as AWS, Azure, and GCP.</p><h3>2.<strong> Local Installation — A Hands-On Approach:</strong></h3><p>Local installation refers to the process of setting up and running a MongoDB database directly on your local machine for development and testing purposes. This approach is particularly useful when you are working on small-scale projects or during the initial stages of application development.</p><h3><strong>3. Cloud-based Platforms — Managed Services:</strong></h3><p>Services like Amazon DocumentDB on AWS can serve as fully managed alternatives to MongoDB, allowing you to leverage cloud scalability and infrastructure. Users can benefit from features like automatic backups, global clusters, and effortless scaling on AWS, making it an ideal choice for applications with varying workloads. The integration simplifies database deployment and management, allowing developers to focus on building robust applications without the burden of manual maintenance.</p><h3><strong>4.Docker — Containerize Your Database:</strong></h3><p>Containerization involves packaging an application and its dependencies into a lightweight, isolated container, ensuring consistency and portability. This section guides users through the process of creating a Docker container for MongoDB, allowing them to isolate the database environment and run it seamlessly on any system that supports Docker. This approach not only promotes consistency in database setups but also facilitates easier collaboration and deployment workflows within a containerized ecosystem.</p><p>MongoDB Atlas stands out as a better option due to its fully managed approach, global scalability, seamless cloud integration, security features, user-friendly interface, free tier for development, and strong community support. So let’s walk through the steps of getting MongoDB with MongoDB Atlas.</p><p>First, go to <a href="https://www.mongodb.com/">https://www.mongodb.com/</a> and create a MongoDB account. Create a New Cluster by choosing a cloud provider (AWS, Azure, or GCP) and a region for your cluster.</p><p>After that go to the quick start option In security and create a user by entering a username and password to access the database. Then add your current IP address from the network access. Now it is time to connect the database to the backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7v40IFlcoEN1IdOyo6BEbw.png" /></figure><p>Now go to the dashboard and click the connect option. Then choose the drivers option and select your driver and version. ( Here I have used nodejs and version 5.5)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*ia9_1Jp8tBkD5i_VUnAnaw.jpeg" /></figure><p>After that copy the MongoDB URI and go to your backend development environment. Let’s see how you can connect the MongoDB database to the backend.</p><p>You can create a separate JavaScript file in your folder structure to establish the connection. Eg: connection.js</p><p>( Note that here I am using a NodeJS backend )</p><pre>const mongoose = require(&quot;mongoose&quot;);</pre><p>This line imports the Mongoose library, which is a popular ODM (Object Data Modeling) library for MongoDB and Node.js. It provides a straight-forward, schema-based solution for modeling application data.</p><pre>const monogdbURI = &quot;mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster0.kijedwg.mongodb.net/?retryWrites=true&amp;w=majority&quot;;</pre><p>Here, you define the MongoDB connection URI. It includes the username, password, and the cluster details . This URI is specific to MongoDB Atlas, MongoDB&#39;s cloud service.</p><pre>mongoose.connect(monogdbURI, {<br>  useNewUrlParser: true,<br>  useUnifiedTopology: true,<br>});</pre><p>This code initiates a connection to MongoDB using Mongoose. The connect method takes the MongoDB connection URL and an options object.</p><pre>const connection = mongoose.connection;</pre><p>This line retrieves the connection object from Mongoose. It provides access to various events and methods related to the MongoDB connection</p><pre>connection.once(&quot;open&quot;, () =&gt; {<br>  console.log(&quot;MongoDB connected!&quot;);<br>});</pre><p>This code sets up an event listener for the “open” event. When the MongoDB connection is successfully established, this callback function is executed, logging a message to the console indicating that the MongoDB connection is open.</p><p>Now armed with the knowledge of MongoDB connection in a Node.js backend, you can start building applications that leverage the flexibility and scalability of this NoSQL database. As you dive deeper into MongoDB’s capabilities, keep exploring, innovating, and creating solutions that elevate your application to new heights. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d4fbc93e0c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java VS C/C++]]></title>
            <link>https://medium.com/linkit-intecs/java-vs-c-c-9720d1549df0?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9720d1549df0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 10:14:11 GMT</pubDate>
            <atom:updated>2024-09-22T05:47:29.796Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this article, I’m going to discuss some key differences between Java and C/C++.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-9tD2VYDMex7skle" /><figcaption>Photo by <a href="https://unsplash.com/@juanjodev02?utm_source=medium&amp;utm_medium=referral">Juanjo Jaramillo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ol><li><strong>C/C++ has a static memory allocation but Java has a dynamic memory allocation.</strong></li></ol><p>So what is the meaning of static and dynamic here? Static memory allocation means memory allocation happens at compilation time (c/c++). Dynamic means memory allocation happens during the runtime of the program (Java).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GhCdOav02q-3qaba9IAZpw.jpeg" /><figcaption>Artwork by <a href="https://medium.com/@isuru99">Author</a></figcaption></figure><p>2<strong>.C/C++ are platform-dependent. Java is platform-independent.</strong></p><p>Platform independent means we can write the source code on one operating system and execute it on another operating system (write once, run anywhere). As an example, if you write a Java program in the Windows operating system, you can run it in another OS (Linux or Mac OS) without changing the source code. Platform-dependent means compilation and execution should be done in the same operating system.</p><p>So why is Java platform independent while C/C++ is platform dependent? Because the Java program is not directly running on the computer. It is running on top of a machine called the JVM (Java virtual machine). Java source code is compiled into Java byte code. This byte code is platform-independent. (It is not dependent on the OS.) The JVM executes this byte code into an .exe file. Here, the JVM is platform-dependent. Since this byte code is platform-independent, we say Java is platform-independent.</p><p>But in c/c++ Source code is directly compiled into an.exe file. There is no intermediate file, like in Java. The compiler directly converts it into an OS-specific.exe file.</p><p><strong>3. C++ supports multiple inheritance, but Java does not support multiple inheritance.</strong></p><p>Inheritance is one of the main concepts in object-oriented programming. C follows the procedure-oriented programming paradigm, and C++ and Java follow the object-oriented programming paradigm. Since C follows a procedure-oriented programming paradigm, we cannot talk about inheritance in C. So simply, inheritance means passing the properties( variables and methods) of a superclass to its subclass.</p><p>So why doesn&#39;t Java support multiple inheritance? Let’s see this example.</p><pre>public class A {<br>    // variables<br>    int number1 = 10;<br>    int number2 = 20;<br><br>    // Method<br>    public void displayNumber() {<br>        System.out.println(&quot;Summation is: &quot; + number1 + number2);<br>    }<br>}</pre><pre>public class B {<br>    // variable<br>    int number1 = 10;<br>    int number2 = 20;<br><br>    // Method<br>    public void displayNumber() {<br>        System.out.println(&quot;The division is: &quot; + number1/number2);<br>    }<br>}</pre><pre>public class C extends A,B {<br>}</pre><p>If you try to inherit a single subclass from multiple superclasses, that is called multiple inheritance. This is not possible in Java because, as in this example, if super classes have the same method as<strong><em> displayNumber()</em></strong>, there will be an ambiguity about which method should be inherited by the subclass. Java language developers needed to reduce the complexity and simplify the language. That’s why Java does not support multiple inheritance.</p><p><strong>4. C/C++ follow both call-by-value and call-by-reference parameter passing mechanisms. Java follows a call-by-value parameter-passing mechanism only.</strong></p><p>a) call by value in c</p><pre>#include &lt;stdio.h&gt;<br><br>// Function that uses call by value<br>void increment(int num) {<br>    num = num + 1;<br>}<br><br>int main() {<br>    int x = 5;<br>    printf(&quot;Before increment: x = %d\n&quot;, x);<br>    increment(x);<br>    printf(&quot;After increment: x = %d\n&quot;, x);<br>    return 0;<br>}</pre><p>Here output is</p><pre>Before increment: x = 5<br>After increment: x = 5</pre><p>b) call by reference in c</p><pre>#include &lt;stdio.h&gt;<br><br>// Function that uses call by reference<br>void incrementByReference(int *num) {<br>    *num = *num + 1;<br>}<br><br>int main() {<br>    int x = 5;<br>    printf(&quot;Before increment: x = %d\n&quot;, x);<br>    incrementByReference(&amp;x);<br>    printf(&quot;After increment: x = %d\n&quot;, x);<br>    return 0;<br>}</pre><p>Here output is</p><pre>Before increment: x = 5<br>After increment: x = 6</pre><p>Here we pass a pointer variable to the <strong><em>incrementByReference()</em></strong> Function. That means we are passing a pointer variable to the function, and it is not just a normal variable. Then, inside the function, an increment by one happens to the variable x inside the main method. But in example <strong>a)</strong>, incrementing is happening to a local variable called num in the <strong><em>increment()</em></strong> function.</p><p>c) call by value in Java</p><pre>public class CallByValueExample {<br><br>    // Method that uses call by value<br>    public static void increment(int num) {<br>        num = num + 1;<br>        System.out.println(&quot;Inside method: num = &quot; + num);<br>    }<br><br>    public static void main(String[] args) {<br>        int x = 5;<br>        System.out.println(&quot;Before increment: x = &quot; + x);<br>        increment(x);<br>        System.out.println(&quot;After increment: x = &quot; + x);<br>    }<br>}</pre><p>Output is</p><pre>Before increment: x = 5<br>Inside method: num = 6<br>After increment: x = 5</pre><p>When we pass a parameter to a method in Java, we are passing a copy of the value of the actual argument. Any modifications made to the parameter within the method do not affect the original argument.</p><p>Then why doesn’t Java use the call-by-reference parameter passing mechanism? Because in Java, they do not use the concept of pointers. Even though there are reference variables in java, it stores the reference of the object but java restrict direct access memory address. So there are no pointer variables. Because of that, there is no way to store the actual memory location of a variable in Java.</p><p>I hope you have some ideas about Java and C/C++. Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9720d1549df0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/java-vs-c-c-9720d1549df0">Java VS C/C++</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compilation process in C]]></title>
            <link>https://medium.com/linkit-intecs/compilation-process-in-c-d75fa8dbee85?source=rss-e02258aed3a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75fa8dbee85</guid>
            <category><![CDATA[preprocesing]]></category>
            <category><![CDATA[assembling]]></category>
            <category><![CDATA[compilation-process]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[linking]]></category>
            <dc:creator><![CDATA[Isuru Jayalath]]></dc:creator>
            <pubDate>Thu, 22 Sep 2022 17:33:27 GMT</pubDate>
            <atom:updated>2022-09-22T17:33:27.152Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this article, I’m going to explain the compilation process in C language.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eCarXQzHVsiD1NjD" /><figcaption>Photo by <a href="https://unsplash.com/@radowanrehan?utm_source=medium&amp;utm_medium=referral">Radowan Nakif Rehan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before moving into the compilation process, let’s get a brief idea about what compilation is. Basically, the compilation is the translation process of human-understandable source code to machine instructions. These machine instructions are written in binary format which is ones and zeros. So, there are four main steps in the compilation process. They are;</p><ol><li>Preprocessing</li><li>Compiling</li><li>Assembling</li><li>Linking</li></ol><p>Let’s see them one by one.</p><ol><li><strong>Preprocessing</strong></li></ol><p>This is the starting point of the compilation process. This part is done by the preprocessor. The following tasks will be done during the preprocessing.</p><ul><li><strong>Comments removal</strong></li></ul><p>All the comments written in the source code will be ignored. <em>(Comments are used to explain what we have written in the code and to make it more understandable for others.)</em></p><ul><li><strong>File Inclusion</strong></li></ul><p>All the lines starting from<strong> #include</strong> will be replaced by their original content. (This <strong>#include</strong> directive is used to add a pre-written piece of code from a reserved header file into our code file.)</p><ul><li><strong>Macros expansion</strong></li></ul><p>Macros will be replaced by their original values. (Macros are some constant values/Expressions defined using #define directives. If you want to learn more about macros refer to this. <a href="https://www.scaler.com/topics/c/macros-in-c/)">https://www.scaler.com/topics/c/macros-in-c/)</a>. At the end of the preprocessing, the source code will be translated to expanded code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*LnmZ9xdhqX19ogBTMSa00w.jpeg" /></figure><h4><strong>2. Compilation</strong></h4><p>In this stage previously generated expanded code will be translated into Assembly code by the compiler. This compiler is also a special program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*ZYdUgYB1w_p1zHoCfqK8sQ.jpeg" /></figure><h4><strong>3. Assembling</strong></h4><p>Here, Assembler will translate the assembly code to Object code. Object code is a pure binary code written in machine language. Object code is also directly executable code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*k620JUMr3U3ANGjllxU01w.jpeg" /></figure><h4><strong>4. Linking</strong></h4><p>This is the final stage of the compiling process. Here, Linker will link the object code and other library files together. This linker will produce the final executable code for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*nNhPlubUCjTp20VfrLfKqQ.jpeg" /></figure><p>That’s about the compilation process in C. I hope you got a clear understanding of it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75fa8dbee85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/compilation-process-in-c-d75fa8dbee85">Compilation process in C</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>