Sunday, February 21, 2021

How to open/close react-datepicker on a condition?


 React Date picker allows the user to select the date and time with a nice beautiful Interface. It provides you fine control over the User Interface and a lot of features to customize it according to your need. You can find all the possible options with well-explained examples on their website at https://reactdatepicker.com/, but recently  I was working on a project where I need to open/close the date-picker on certain conditions, I tried a lot but didn't find any good way to achieve it, finally, I achieved it by using ref in react

Before I explain here are some useful links

Github Repo: https://github.com/guide-father/open-close-react-datepicker-on-condition

Preview: https://github-ze2knr.stackblitz.io

Stackblitz: https://stackblitz.com/edit/github-ze2knr?file=src/calendar.js



Calendar.js

import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";


class Calendar extends React.Component {

constructor() {
super()
this.state = {
selectedDate: new Date(),
isOpen:false
}
this.pickerRef = React.createRef() //Defining Ref
}
SetDate = (date) => {
this.setState({
selectedDate: date
})
}
ChangeState = () => {
this.pickerRef.current.setOpen(!this.state.isOpen)
this.setState({
isOpen:!this.state.isOpen
})
}
render() {
return (
<div>
<div>
<button onClick={this.ChangeState}>
                            {this.state.isOpen?"Close":" Open"}
                    </button>
</div>
<div>
<DatePicker
selected={this.state.selectedDate}
onChange={this.SetDate}
dateFormat="yyyy/MM/dd"
ref={this.pickerRef}
/>
</div>

</div>
)
}
}

export default Calendar


Declare a reference by

this.pickerRef = React.createRef()

and assign the reference to the DatePicker 
now you can have fine control over the state of datepicker by 

this.pickerRef.current.setOpen(state)


Tuesday, November 17, 2020

How to create a shortcut (Symbolic Links) to files and folders in Linux


Shortcut in linux

Creating Shortcut or Symbolic Links to files and folder is a very easy task to do. There are few files and folders which we need to access frequently, to access these file or folders we need to dig through the file system. This task became more irritating when using Linux without GUI.

We can create Symbolic links to access the files and folders more quickly.

Command


ln -s absolute_path_to_file_access_quick absolute_path_to_destination


Example


ln -s /home/guide-father/Documents/Guide ~/Desktop/

This will create a shortcut to the Guide folder on the Desktop. This command works both with and without GUI Linux platforms. 

GUI shortcut icon

Bonus Info

Other than Symbolic Links you can also create Hard Links by following command

ln absolute_path_to_file_access_quick absolute_path_to_destination


The main difference between hard links and soft links (Symbolic Link ) is if the real file/folder is deleted then Symbolic Link will not work while the hard link will continue to work.

Explanation

An inode is a data structure that stores various information about a file(like permissions, file size, owner, group, etc..) in Linux. Each inode is identified by an integer number.
You can check the number by 

ls -il

you should get something like following

29657809 -rw-rw-r-- 1 guide guide 0 Nov 17 21:46 random
29648880 -rw-rw-r-- 1 guide guide 0 Nov 17 21:46 test

here the number is the in inode integer associated with the files

Hard link refers to the inode directly while the symbolic link refers to the file itself, hence when the original file lost the symbolic link stop working.
symbolic hard link






Friday, July 31, 2020

How to properly create a server in aws?


AWS(Amazon Web Services ) is one of the leading cloud service providers. Amazon EC2 (Elastic Compute Cloud) is the most useful and popular service provided by AWS. EC2 is the SAAS (Server as a Service) offered by AWS. EC2 instances are the servers which are maintained by AWS, you need not worry about the underlying hardware and infrastructure, you can focus on configuring the server according to your need.

Today we will cover the following topics.
  1. Creating an IAM user
  2. Scheduling an EC2 instance
  3. Understanding Security Groups 
  4. Serve Static Pages using an EC2 instance
  5. Associate an Elastic IP with EC2 instance
How to create a server in aws

Creating an IAM user

AWS provides IAM (Identity and access management) to maintain user access. AWS strictly says that don't use your root account to perform any action except payment and bill management, also don't give any extra permissions to your user, give only the required ones. It helps to avoid any confusion or problem in case your keys are exposed to the world.
  • Login to your AWS account using your root credentials 
  • From the top menu under Services search for IAM and click on it

    services in aws
  • From the left menu click on Users

    menu
  • Click on Add User from the top bar and give your user a name and AWS Management Console access and click on Next:Permissions button.

    create user
   

  • Select Attach existing policies directly, and search for AmazonEC2FullAccess and attach this policy with your user.

    attach policies
  • Add tags if you want, this helps to categorize the entity later and click on theNext button. 
  • Review your user and click on create once you are satisfied. 
  • In the next screen, you will be able to see the credentials of the user you just created and the URL from which you can access the console. Download the future for future reference because you will not able to see this screen again.

    user credentials
    Congratulations you have successfully created your first AWS user 

Scheduling an EC2 instance 

Before scheduling an EC2 instance you have to understand that there are two types of services 
  1. Global Services: Global services are those which are not bounded in a region like IAM.
  2. Regional Services. : Regional services are those which are bounded to a specific region like EC2. 
In Regional Services selecting the proper region in important to reduce the latency. For example if you are targeting the audience in London and scheduling your server in India, you will face unnecessary delays and costs.
You can change your region from the top left corner

aws region

There are different types of EC2 instances and depending on CPU intensive tasks, memory-intensive tasks, etc and each EC2 instance has difference pricing model depending on the region and resource you are using.


  • Log in to the AWS account with the user you just created and search for EC2 from the services dropdown.
  • Click on Running Instances and then on Launch Instance.
  • In first step you have to select the OS(Operating System) for your server. I am selecting Ubuntu 18.04 but you are free to use any OS according to your need.

    os type
  • Next, you have to select the CPU and RAM required by your server. I am choosing t2.micro because this is the only option in the free tier, But you can choose any server according to your need.
  • Next, You can see the additional setting, review and click on add Storage
  • Then you can add Tags to categorize the server later.
  • Then you will have the most important part of this process Security Group this is the step which will decide the security of your application. For now, just give it a name and allow SSH from your IP only.

  • In free tier, AWS gives you 8 GB of SSD but you can increase it if necessary. Select storage and click on Review and Launch
  • Review the setting and click on Launch. You will be prompted with a popup to select keys.
    These are the keys required to access your server. Create new if you don't have any and remember to save it because you will not able to view these records again.
    And never never never... share it with anyone or make it publicly available.
    Click on launch once you are done.


  • Once you are done you will be able to view your server running in your dashboard.
Congratulations you have scheduled your server successfully 

Understanding Security Groups

Security Groups are the firewall of your server. It will decide what will go inside the server and what will come out from the server. It helps to restrict server access based on ports and IP.
Go to Security Groups from the left side menu and select the security group you just created.

 here you can see mainly two options 
Inbound rules: These are the rules define what type of request from where will go inside the server. Try to keep it as tight as possible. In general, allow port 80 (HTTP)  and 443(HTTPS) to listen from anywhere and open 1 SSH port to access the server and restrict it with your IP address.

Outbound rules: These rules define what will go outside of your server. You can leave it open for the world.

Serve Static pages using EC2 Instance

If you want to serve the static page you first have to access the server. If you are using Linux, Mac, or Windows 10 then it will be easy for you, because both of them support SSH. but if you are using windows prior to Windows 10 you have to use Putty.
 If you are using Linux, Windows 10, or Linux try the following steps to access the server.

Access the server

  • Go to the directory where you stored the keys you downloaded while launching the EC2 instance.
  • Open Terminal and type the following command to change the mode of your key (not required in windows).

    sudo chmod 400 your_key_name.pem

     
  • Go to your EC2 dashboard and select the instance and then click on Connect on the top 

    connect to ec2
    copy the string and run it in the terminal.
    If you face issues regarding timeout make sure that your current IP is added in the security group, because then only you can access the server.
If everything goes right you should be inside the server.

Running NGINX to serve static pages.

  • Run the following commands to update your EC2 server if you are using ubuntu

    sudo apt-get update
    sudo apt-get upgrade


  • Run the command to install NGINX, a web proxy

    sudo apt-get get install nginx

  • Once it is done you can test it by running the following command

    curl localhost

    if you and HTML page then congratulations, it's working.

  •  Go to the security group and allow HTTP access from anywhere


    allow http in security group
  • Once you are done with that you can access the page with the public IP provided by AWS

    public IP
  • Now to upload your website to the server I will use SCP(Server Copy Protocol)
    sudo scp -i your_key_name.pem -r
    local/path/to/website
    connection_string_toServer:path/in/server

    example

    sudo scp -i first_ec2.pem -r
    /home/black/Downloads/allfood/allfood
    ubuntu@ec2-15-207-110-187.ap.compute.amazonaws.com:/home/ubuntu

  • Change the owner of file so that Nginx can access this file.

    sudo chown -R www-data:www-data folder_name/
  • Now edit the Nginx Config 

    sudo nano /etc/nginx/sites-available/default

  • Replace the root path to the path of your website folder

    nginx config

    save the changes by Ctrl+ O then Enter then Ctrl + X to exit
  • Restart the Nginx config by 

    sudo service nginx restart


    and its done, Congratulations you have served your website

Associate an Elastic IP with your EC2 instance

By default, the IP provided by AWS will change when you restart your server. AWS provides elastic IPs which are basically static IPs which when associated with an EC2 instance will not change the IPs of your EC2 instance 
AWS provides 5 elastic IPs in a region per account. You can always request more static IPs but if you need more than 5 elastic IPs you should reconsider your architecture.

Steps to associate elastic Ip
  • Go to Elastic IPs from the left menu and click on Associate Elastic Ip address.

Elastic Ips
  • Keep defaults and click on Allocate, to get a static IP
  • From the actions dropdown select Associate Elastic IP
  • From instance choose your AWS EC2 instance  


and its done, Congratulations now you can use this IP to access your website

Thank you for Reading

Saturday, July 11, 2020

How to use NETLIFY for publishing website and netlify lambda functions?


publish website using Netlify

NETLIFY is an awesome service that provides hostingserverless backend, analytics, free SSL, etc with a great free tier. It is a fast and easy way to build your website for testing and production. You can consider this service as an alternative to Firebase, Github Pages, or any shared hosting platform. You can use Netlify to host your static or dynamic website for free.
Netlify lambda functions use AWS lambda functions under the hood, AWS does have a free tier but its quite difficult to use. Netlify abstracts the complex wiring for you and provides easy APIs to use these lambda functions.
Today we will cover all the following stuff to get you started with Netlify.
  • Deploy the website to Netlify using the dashboard.
  • Connection your website with your domain.
  • Deploy website using GitHub continuous integration.
  • Developing Netlify lambda functions.
  • Use the NPM package in Netlify lambda functions.
  • Develop and deploy the simple jokes app

Deploy the website to Netlify using the dashboard.

  • Register to Netlify: Its a simple and easy process, Just go to Netlify Signup and register yourself in your preferred way.
  • Once you logged in you should get something like this.Netlify Dashboard
  • Now Drag and drop your website folder into the drag and drop section. I have a simple project in my local system I am going to deploy that.
  • Once you drop your code you will see the URL provided by Netlify for your website on the top.

Connect your website with your domain.

  • Copy the URL  provided by Netlify for your website and go to your domain manager.
  • Netlify suggests changing the nameservers of your domain but I don't like that idea.
    Add a CNAME record
    Cname
    here I am using the subdomain that why I used tell-a-joke as the name, If you are using your root domain, leave it blank or put @ and my Value is nruffled-khorana-8c57e9.netlify.app (the URL provided by Netlify for my website)

    You can read more if required from here
  • From the dashboard, you will see the websites uploaded by you. Select the website to which you want to add the domain and navigate to Settings -> Domain Management

    Domain config
    Click on add domain and enter the URL of your website. Your domain will be verified within a few minutes and free SSL will be activated automatically.

Deploy website using GitHub continuous integration.

  • Push your code to GitHub and navigate to Settings -> Build & Deploy -> Continuous Deployment.
  • Click on Link site to Git 
  • Click on GitHub and add select the repository you want to add and then click on deploy site

    Github authority
  •  Under overview, you will recently publish code.

    recently published
  • whenever you push your changes to Github, your code will be build based on the recent changes.
    If you want to stop continuous deployment you can click on the recently published code and Lock publish to this deploy and change to stop auto-deploy.

    stop continuous deployment


Developing Netlify lambda functions

Netlify provides lambda function which is a serverless backend service. Under the hood, it uses AWS lambda functions, but Netlify removes all the complexity and gives an easy to use interface.
  • To create a lambda function create a folder with any name you want (I am using API), inside that folder create a JS file( I am creating getJoke.js). keep in mind that the folder and file name will be the URL.
  • Add the following code to the JS file (getJoke.js)
    exports.handler = async (event,context,cb) => {
    return {
    statusCode: 200,
    message:"success",
    body: "Here is a joke",
    }
    }
getjoke.js
  • Create a netlify.toml file and add the following code.This file will indicate which one is the function directory and what command to run

    [build]
    functions = "./api"
    command = "npm i"

netlify.toml
  • Commit and push the code to GitHub, If the continuous integration is activated then your functions will be automatically deployed. You can verify the functions in the functions tab
    functions tabs
    click on it to view the URL


    endpoint

Using NPM package in Netlify lambda functions.

To use the NPM package in lambda function first make sure that netlify.toml file has command in it.
In this we will use Get me a joke package
  • Create a package.json by using.

    npm init -y

     
  • Install dependency by

    npm i give-me-a-joke

  • Replace the content in getJoke.js with the following content.

    const giveMeAJoke = require('give-me-a-joke');

    exports.handler = async (event,context,cb) => {
    function joker() {
    return new Promise(function (resolve, reject) {
    giveMeAJoke.getRandomDadJoke(function (joke) {
    resolve(joke)

    });
    })
    }

    //getting random joke
    let joke = await joker()
    return cb(null, {
    statusCode: 200,
    body: JSON.stringify({
    statusCode: 200,
    message:"success",
    body: joke,
    })
    })
    }


  • Deploy the code again, Once the code build successfully you should see the result as follow
API endpoint

Develop and deploy the simple jokes app

To create this app I am fetching the API we created and display the results in browser

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Joke teller</title>
<link rel="stylesheet" href="styles/bootstrap.min.css">
</head>

<body class="bg-primary">
<div class="container text-center mt-5 ">
<h1 class="header">Today's Joke</h1>
<div class="card">
<div class="card-body">

</div>
</div>
</div>
</body>

</html>

<script>
fetch("https://tell-a-joke.guidefather.in/.netlify/functions/getJoke")
    .then(function (response) {
    return response.json();
}).then(function (data) {
document.querySelector(".card-body").innerHTML=`<p>${data.body}</p>`

}).catch(function (e) {
console.log("Error",e);
});
</script>


index.html



tell a joke
End result

The code is available in my GitHub repository. Fell free to clone/download it to explore Netlify.
Netlify is an awesome service which does all the heavy lifting and gives an easy to use interface. Whether you are a complete fresher or an expert you can use Netlify to enhance your skills.

THANKS FOR READING



Monday, July 6, 2020

How to create a bootable drive using RUFUS?



Bootable media using Rufus

Welcome noobs, here is your GuideFather. You want to make a bootable pendrive, but you don't like the softwares which have the superpower to do so because they come at a cost. Either you have to buy it or crack it.
They also consume a lot of space in your Disk and time in your life just to get installed in your system.Using softwares like Power ISO could be a drag sometimes...
But we have a solution for this, i.e. RUFUS.
In this article, your GuideFather will teach you how to create a bootable pendrive without the help of those heavy load softwares on your PC.
Rufus

Rufus is a utility that helps format and create bootable USB flash drives, such as USB keys/pendrives, memory sticks, etc.

It can be especially useful for cases where:

  • you need to create USB installation media from bootable ISOs (Windows, Linux, UEFI, etc.)
  • you need to work on a system that doesn't have an OS installed
  • you need to flash a BIOS or other firmware from DOS
  • you want to run a low-level utility

Despite its small size, Rufus provides everything you need!


NOTE:Before you make your pendrive bootable, make sure you have backed up your data, because after following these steps(formatting) you will lose all the data in your pendrive. 

Step 1:

Ofcourse, first you have to download this 1MB software from https://rufus.ie/

Don't worry about the installation, you don't have to install it, just the run the .exe file

Step 2:

Now you need the iso file of the OS to create a bootable image.

If you want to install windows 10, then our previous article have the required links and steps to get the latest and genuine iso for the OS


Step 3:

i.Select the drive you want to make bootable.



ii.Select the iso file.


Let the other settings as default. 

The best setup for Windows 10 is as follow:

  • Partiton scheme---->GPT
  • Target system------->UEFI
  • File System--------->NTFS
  • Cluster size--------->4096 bytes


once you click start you will be prompted with a warning, If you have nothing to lose anymore in your life then proceed.


wait until it's finished then use it.

If you have any trouble regarding how to boot your system via USB or windows installation you can check our other articles.


NOTE:Don't remove your pendrive while formatting, otherwise you won't be able to use it ever again.