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.


Friday, June 26, 2020

How to create a desktop app from website in 10 minutes?



desktop application from website


Building a Cross Platform Desktop Application (i.e.. App that can run on Windows, Linux, and Mac os) helps to reduce the development time and cost. Electron is one of the best and known frameworks to develop desktop applications. 
Many famous applications like VS Code, Slack, Figma, etc are built on Electron.
The best part about Electron is, you need not learn any new language, you can simply write JavaScript, HTML, or use a framework like REACT, VUE, and ANGULAR and compile it to a desktop app, or If you have a website hosted you can simply provide the URL of the website to create a desktop application.
Today we will see how to create a desktop application from a website hosted on the web and some must-have features to get you started.

If you have no time or wanna know what we are going to build then I recommend clone/download my desktop-app-in-minutes repo and replace the https://www.blog.guidefather.in URL with your websites URL.

What we will cover?

  • What is electronJS?
  • Create a desktop app from the website URL.
  • Create a Custom Header in electron app.
  • Using npm modules in the electron app.
  • Managing app events 
  • Distribution of an electron app
  • Pros and Cons of electrons
app preview

What is electronJS?

With the help of ElectronJs one can build cross-platform desktop applications with HTML, JavaScript, and CSS. It was introduced in 2013 to make cross-platform text-editors, later its scope was extended to build other utility apps. Electron has chromium in it
Electron has two processes 
  • Main Process: It manages the bootstrapping the application and lifecycle events like starting, quitting, etc. This main process is responsible for interacting with the native GUI of the Operating System. It creates the GUI of your application.
  • Rendering Process: It is created by the main process and its main purpose is to render the UI.

Create a desktop app from the website URL.

Before proceeding you need to have node and npm install in your system.
Steps to create a desktop app.
  • Create a folder with the name you want and type following commands
    npm init -y
    npm i electron --save-dev
  • add a start script in package.json
    "start":"electron ."
 You can get the complete project code from my GitHub Repository.

const { app, BrowserWindow, Menu, shell } = require('electron');

function createWindow() {
const win = new BrowserWindow({
width: 1100,
height: 800,
webPreferences: {
nodeIntegration: true
}
})
// win.webContents.openDevTools() //Open dev tools

// To open the file from a local directory.
// win.loadFile('index.html')

//open url
win.loadURL("https://www.blog.guidefather.in")


}

//lauch view when electron is ready
app.whenReady().then(createWindow)

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})

   main.js

This will open https://www.blog.guidefather.in in an application, from which you can interact.
BrowserWindow runs its own renderer process. This renderer process will take the HTML, CSS, and JavaScript and render it to the window.

win.webContents.openDevTools()
It is used to open dev tools in the application for debugging purposes.

If you have the code in ANGULAR, REACT, VUE, or any other framework which can be compiled down to HTML, CSS, and JavaScript you can create an application by providing a path to the dist folder
win.loadFile("path_to_dist")
By using the above code you will have a basic desktop application.

Create a custom header in electron app

By writing the above code you will have a desktop application but with a default header of your operating system. You can override the default headers and create custom headers by using the MENU module of electron.

const menu = Menu.buildFromTemplate([{
label: "Menu",
submenu: [
{
label: "Disclaimer",
click() {
utility.openModel(win, "Disclaimer")
}
},
{
label: "View Article",
click() {
//open external links
shell.openExternal("https://www.blog.guidefather.in")
}
},
{ type: "separator" },//introduce a gap in menu
{
label: "Exit",
click() {
app.quit() //quit application
}
}
]

}, {
label: "History",
accelerator: "CommandOrControl+H", //shortcut
click() {
utility.openModel(win, "History")
}
}])
Menu.setApplicationMenu(menu)
By implementing the above code you will have a menu like this
Menu Preview
 Menu.buildFromTemplate takes an array of objects which will be displayed as the menu. Each Object has a mandatory field label which will be displayed as the title of the menu. You can have sub-menu using submenu inside each object.
To perform click event you have to declare a function click.
You can specify shortcut keys to perform the task by using an accelerator. As you can see I have used CommandOrControl+H to open the history tab.

Events 

app.quit() : This will close the application 
shell.openExternal() :  To open External links 
openModal: I've created a custom function to open models in utility.js
function openModel(parent, pageType) {
modal = new BrowserWindow({
width: 600,
height: 700,
title: 'Info',
frame: false,//remove headers
backgroundColor: '#2e2c29',
parent: parent,//to specify the parent
webPreferences: {
nodeIntegration: true
}
});
// modal.webContents.openDevTools()
switch (pageType) {
case "Disclaimer":
modal.loadFile("./src/info.html")
break;
case "History":
modal.loadFile("./src/history.html")
break;
}
modal.on('close', function () {
modal = null;
});
}

Using NPM module in the electron app.

You can use the NPM module in the electon app in the same way as you use in node.js, but the best part is if you specify nodeIntegration = true in BrowserWindow then you can access Node.js in HTML files.
To access Node.js in HTML file, simply declare a script tag in the HTML page and start writing Node.js 
<script>
const remote = require("electron").remote;
const utility = require("../utility")
document.querySelector("#close-info").addEventListener("click", function () {
remote.getCurrentWindow().close() //get current window and close it
})
utility.getHistory().then(history => {
history.forEach(d => {
document.getElementById("hist-row")
            .insertAdjacentHTML('beforeend',
                                  `<tr><td>${d[0]}</td><td>${d[1]}</td><tr>
                                `);
});
})
</script>

As you can see I have imported utility using require statement to call utility functions.

Managing App Events

You can monitor the events performed by the user in the application by app events. I've used this feature to monitor the history of the user by writing it to a CSV file.
win.webContents give access to the running process.
win.webContents.on("will-navigate", function (e, url) {
utility.writeHistory(url)
})

You can check all the option here
To specify the directory where to save the file I've used 
const historyPath= (app || remote.app).getPath("userData") + "/history.csv";
getpath will return the path depending on the operating system. If you don't specify this then your code may not runs all platforms.

Distribution of electron app

After development comes the most tricky part compiling the OS-specific builds. To build an application in electron I recommend using electron-builder
  • Install electron builder
    npm i electron-builder --save-dev
  • Add icons 
    create a folder in the project directory, name it build and place icon with the name of icon.png and dimension of 256 X 256.
  • Modify package.json, electron builder take the details from package.json file. 
    {
    "name": "gview",
    "version": "1.1.0",
    "description": "website to desktop app in 5 mins",
    "main": "main.js",
    "scripts": {
    "start": "electron .",
    "build:linux": "electron-builder --linux deb",
    "build:win": "electron-builder --win", "build:mac": "electron-builder --mac"
    },
    "keywords": [],
    "author": {
    "name": "Service",
    "email": "service.b@blog.guidefather.in"
    },
    "license": "ISC",
    "devDependencies": {
    "electron": "^9.0.5",
    "electron-builder": "^22.7.0"
    },
    "dependencies": {
    "csv-writer": "^1.6.0"
    },
    "homepage": "https://blog.guidefather.in",
    "nsis": {
    "deleteAppDataOnUninstall": true,
    "uninstallDisplayName": "app"
    }
    }
replace the details with you own.
  • run commands
    npm run build:linux for Linux
    npm  run build:win for windows
    npm  run build:mac for Mac
    for more details and info you can check the link 

Pros and Cons of electron App

PROS

  • You need not to learn an extra language or framework. If you have knowledge of HTML, CSS and JavaScript you can build cross-platform apps in few minutes.
  • Its has great documentation and APIs which help you achieve the desired results and access native APIs easily.
  • You can develop without worrying about platform compatibility.
  • NPM support, you have access to the huge libraries of npm, using which you can achieve anything.

CONS

  • Build size is huge, Even for small application build size is huge because it has the chromium engine built in it.
  • Hight CPU utilization, Electron consumes a high amount because it launches a separate instance of chromium every time a new window loads.
  • Build Complications, Building OS-specific installable may not give desired results. You will most likely face issues with icons, writing files, etc.. because each and every system behaves differently.

Conclusion 

ElectronJs is great if you are not developing something out of the box or CPU intensive apps. With nice documentation and support electronJs is still evolving. I recommend to clone my GitHub repo and check CPU utilization, build size etc.. and make sure electron is best for your need.

T̳h̳a̳n̳k̳ y̳o̳u̳