Sunday, April 1, 2018

Code snippet scrapping from website using Chrome extension plugin and NodeJS



Objective:
The objective of this project is to develop a chrome extension plugin which should scan for code-snippets from any active URL opened in the Chrome browser and should store them in MySQL database.

Requirement:
1) Need to develop Chrome Browser extension plugin, which on-click should find the source code snippet from the active URL in the Web browser and store the code snippet to MySQL database.
2) Incase if the URL is not valid, it should display the message saying invalid URL
3) Incase if the URL don’t have any code snippets, it should display the message saying no code snippets found and no record should be inserted to the MySQL database.

GitHub link:

Installation Steps:

1. Setup all the required pre-requisite softwares (as mentioned under the section Pre-requisites)
2. Git clone the project (For example, in my case, under D:\Projects\)
3. Once the clone is complete, execute the DB scripts available in D:\Projects\NodeJS_Projects\SourceCodeFind\db_scripts\db_scripts.sql in your local MySQL database.

CREATE DATABASE nodemysql;

USE nodemysql;

CREATE TABLE `code_capture` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `url_scanned` varchar(300) DEFAULT NULL,
 `code_snippet` varchar(1000) DEFAULT NULL,
 `last_updated_dt` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=68 DEFAULT CHARSET=latin1;


4. Now open the command prompt and cd to path D:\Projects\NodeJS_Projects\SourceCodeFind\NodeRestAPI and execute the command "npm install"

5. Now execute the command “nodemon”


Note: Please don’t close this. This is the Server code which should be always running. Incase if you want to stop this, you can use CTRL + C and close the window.

Error scenario:
Incase if you get the below error, it means that MySQL server is not up and running. Please start the MySQL and run the command “nodemon”.


6. Now install the Chrome Extension plugin. For this, open Chrome browser and type “chrome://extensions” in tab, enable the “Developer mode” on the left hand top,  click “LOAD UNPACKED”. It will open the “Browse For Folder” option (as shown in the below screen shot) and enter the path D:\Projects\NodeJS_Projects\SourceCodeFind\ChromeExtension and click Ok button.


Now you will see the extension added and you will see a blue icon added on the left hand side (as highlighted in yellow). 

Now you can open any valid URL in the browser where you can find code snippet (like stackoverflow page) and click this icon (highlighted in yellow), you will see the “Copy” button. Now click this “Copy” button, it will display “Code snippets are inserted successfully to the database”. Note that the Server component in Step 5 is running for this to be working.




You can query the MYSQL database table (code_capture) to see a latest entry, where you can see the following values:
Id: latest auto increment no
url_scanned: the URL active in the browser
code_snippet: The Code snippet from the URL
last_update_dt: The date time stamp of the insert

Negative scenarios:
1. If you try to hit a URL where you find any code snippet (For ex: www.google.com), you will receive the message saying – “No code snippets found in the URL: <URL>”.


2. If you try to hit an invalid http (or https) URL (for ex: chrome://extensions/), then you will receive the message saying – “Not a valid http or https URL. URL received is: <URL>”.

Pre-requisites:

1. Node JS:
The pre-requisite for this project is to install NodeJS in your laptop. So let’s now install Node JS. 
Note: If NodeJS is already installed on your machine, you can skip this step and move to “Node and NPM upgrade on Windows” section of this document, to ensure you have the latest npm version installed.
Installation Steps:
• Download the Windows installer 64 bit from the Nodes.js® web site - https://nodejs.org/en/download/

• Run the installer (the .msi file you downloaded in the previous step.)
• Follow the prompts in the installer (Accept the license agreement, click the NEXT button a bunch of times and accept the default installation settings).

• Restart your computer. You won’t be able to run Node.js® until you restart your computer.

Test the installation:
Make sure you have Node and NPM installed by running simple commands to see what version of each is installed and to run a simple test program:
• Test Node: To see if Node is installed, open the Windows Command Prompt, Powershell or a similar command line tool, and type node -v. This should print a version number, so you’ll see something like this v6.10.2.
• Test NPM: To see if NPM is installed, type npm -v in Terminal. This should print NPM’s version number so you’ll see something like this 5.4.2
• Create a test file and run it: A simple way to test that node.js works is to create a JavaScript file: name it hello.js, and just add the code console.log('Node is installed!');. To run the code simply open your command line program, navigate to the folder where you save the file and type node hello.js. This will start Node and run the code in the hello.js file. You should see the output Node is installed!.


Node and NPM upgrade on Windows:
1. Run PowerShell as Administrator
2. Run the following commands in the PowerShell to upgrade 

Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade 



Explanation of the Source Code:
Project Structure:
1. The below is the project structure for this implementation:
\ChromeExtension – holds the Chrome Extension related code
\db_scripts – holds the db_scripts.sql file which has the database script to create database and table.
\NodeRestAPI – holds the Server side Node JS code, which will have the logic to persist the code-snippet details to the MySQL table via REST apis. 

2. SourceCodeFind\ChromeExtension\manifest.json:
Chrome Extension needs manifest.json, which holds the metadata details like:
Icons to be used – icon128.png, icon38.png, icon19.png
Browser_action – with default_popup value having the html file to be invoked. 
Permission – holding the Permission details to tell only activeTab to be considered, allow permission to invoke the Node JS API via the URL http://localhost:3000/insert

icon19.png, icon38.png, icon128.png are the icons of various sizes used.

3. SourceCodeFind\ChromeExtension\popup.html:
It has logic to display just a button named “Copy” and initialize the javascript file (popup.js) and CSS file (custom.css).


4. SourceCodeFind\ChromeExtension\popup.js
On-click of the copy button, the addEventListner() function will be invoked, which will inturn invoke the function triggerCopy(). This triggerCopy() function will fetch the active URL from the ChromeTab, invokes the REST API POST URL http://localhost:3000/insert via fetch API.  The Fetch API call will accept parameters like:
Method: POST
Headers: for Accept and Content-Type
Body: URL value fetched from Chrome tab
Once the Fetch API response is received, it will replace the div id “output” (defined in popup.html) using innerHTML() method.

5. SourceCodeFind\ChromeExtension\custom.css:
.button will apply the css attributes for button
.div.sansserif will apply the font attributes for the text displayed below the “Copy” button. 

6. SourceCodeFind\db_scripts\db_scripts.sql:
This holds the MySQL database script to create database, create table.
Id  - is the Auto_Increment number field
url_scanned – holds the URL that is active in the browser and will be scanned for code snippet
code_snippet – holds the code snippet found in the URL.
Last_updated_dt – holds the latest datetime value when the record got inserted.


7. SourceCodeFind\NodeRestAPI\app.js:
This is the Node component which will perform the following componets:
a) Import all the required dependencies via require().
express – Node library to start the server
mysql – Node library to connect to MySQL Database
cheerio – Node library to connect to HTML web scrape and look for keyword <pre> in our case in any website
request – Node library to hit the URL and get the request object
body-paser – Node library to parsing the request body to accept only json and URL encoding
moment-timezone – Node library to handle with the timezone and time, required while set today’s date time with Indian timezone (required while inserting the last_updated_dt in MYSQL database)

b) Initialize the Node express server, set the bodyparser middleware to accept only json and url encoding and start the express server to listen on port 3000.

c) Create MySQL database connection and connect to the database

d) Set the timezone to Indian Timezone using Moment Timezone library and date-time to current date time using Date.now().

e) Invoke the Post API method /insert, which should perform the following activities:
• Fetch the url (selected in the Chrome browser) from request body.
• Check if the incoming URL is valid URL (starting with http or https) using regex pattern
• If the URL is valid, invoke the URL via request library, load the website body into cheerio library and scan for the HTML keywords <pre> </pre>. Usually all the code snippets in any website will be marked between the <pre> and </pre> html code. Once you get the code snippets, insert them to MySQL Database via Insert script.



Complete Code snippet:
https://github.com/shyamnarayan2001/NodeJS_Projects/blob/master/SourceCodeFind/NodeRestAPI/app.js

8. SourceCodeFind\NodeRestAPI\package.json:
This file holds the node dependencies required to create node_modules folder. The “npm install” command will use this package.json file to install all the required dependencies mentioned for this project.


That's all. Hope this tutorial was useful.

Angular 5 CRUD with Firebase database



Objective:

The objective of this tutorial is to develop Angular 5 CRUD Operations with Firebase as database.

Application Demo:


GitHub link:
https://github.com/shyamnarayan2001/Angular_Projects/tree/master/angular5firebasecrud

Softwares Required:
The following are the softwares required to implement this.
-          Node
-          Angular CLI
-          Angular 5
-          Firebase project
-          Firebase and AngularFire2 (npm packages)
-          ngx-Toastr  (npm package)
-          Bootstrap and Font-Awesome Icons
-          VS Code Editor
Please install them if they are not already installed.

Setup Instructions:
1. Git clone the project
2. Replace the existing Firebase credentials with your personal account in angular5firebasecrud\src\environments\ environment.ts (Please refer the blog and follow steps from 3 to 7 to get your personal Firebase credentials). 
3. Open the command prompt, move the folder \angular5firebasecrud and run the command
npm install
4. Run the command ng serve
5. Open the browser and hit the URL http://localhost:4200/ to see the screen.

Development Steps to start from scratch:

Create Angular 5 application:

1. In-order to create an Angular 5 application, you can use following Angular CLI command
ng new angular5firebasecrud




2. It will create an angular 5 application in the current directory and install some default npm packages. To run this application:

//switch to project folder
cd angular5firebasecrud
//run the project
ng serve --open

It will open this project in your default web browser from 4200 port.


Create Firebase Project:

3. Goto Firebase Console. It will automatically log in with your gmail account.

4. Click On Add project. It will open a pop-up window, inside that name your project (Angular5CRUD in my case), then click on Create Project button. 

5. Firebase will now try to create the project and you will see the below message. Now click “Continue”.


6. Click on ‘Add Firebase to your web app’.


7. It will open another popup window with firebase project configuration. Copy the below configuration (highlighted in yellow in the below screenshot) and paste it to environment.ts file (under \angular5firebasecrud\src\environments\).




Change FirebaseDB Permission:

8. On the left hand side, go the following menu options:
Left hand Menu -> Develop -> Database -> Realtime Database -> Get Started 


9. You will see the below screen, now click the “Enable” button.


10. Goto Rules tab, edit the read and write values to ‘true’ and click “Publish” button. You will get a confirmation saying “Rules are published”.


11. You will get the below warning message, which you can “Dismiss” for now.

Install Firebase & Angularfire2 Modules:

12. If your ng serve command is still active, stop it with CTRL+C. Let’s now install Firebase and Angularfire2 npm packages.
13. Firebase and Angularfire2 are official packages to interact with firebase project from angular applications. In-order to install these packages use following npm commands

npm install firebase@4.6.1 angularfire2@5.0.0-rc.3 –save


14. Open appmodule.ts file, then initialize firebase module with firebase project configuration.

Add Required Angular 5 CRUD Components, Model and Service Classes:

15. Now we need to add 3 components, to add angular components you can use following Angular-CLI commands

//from root component
ng g c employees
Remaining two components will be child components for this employees component.
//switch to parent component directory
cd src\app\employees
//create child components
ng g c employee
ng g c employee-list

16. Open app.module.ts file, you can see that the newly added components are added already. If not, you can add them as shown in the below screen shot.


Let’s Start the Design:

17. We will use Bootstrap and Font-Awesome Icons for Application Design. So first of all add CDN reference for the style sheets inside index.html.

<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<!-- font-awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

18. Update app.component.html as follows
<div class="container">
  <app-employees></app-employees>
</div>


Add following to employees.component.html file.
<div class="text-center">
  <h2 class="jumbotron">Employee Register</h2>
</div>
<div class="row">
  <div class="col-md-7">
    <app-employee></app-employee>
  </div>
  <div class="col-md-5">
    <app-employee-list></app-employee-list>
  </div>
</div>


We need Model and Services to design remaining child components.

Create Service and Model Classes:

19. To create these classes let’s add a new folder with name shared inside employees folder (/src/app/employees/).

Now create employee model class

//switch to shared folder
cd src\app\employees\shared
//create employee model class
ng g class employee --type=model
//create employee service class
ng g s employee
20. In this application, we deals with employee details like

Full Name
Position
Office Location
Salary
So let’s add properties corresponding to these employee’s details inside employee.model.ts file.

export class Employee {
    $key: string;
    name: string;
    position: string;
    office: string;
    salary: number;
}


$key is used to store unique key automatically generated by firebase DB when we insert a new record.

Inside the service file we will do Firebase CRUD Operation as follows

/src/app/employees/shared/employee.service.ts


EmployeeService contains selectedEmployee property of the type employee model class Employee, to store currently active employee details. employeeList variable store all the employee records from Firebase DB.

In-order to interact with firebase project we have injected AngularFireDatabase as firebase. getData function initialize employeeList from firebase node ’employees’. We will store employee records under this node rest of the functions are self-explanatory.

Using selectedEmployee property we can design form for insert and update operation inside employee component. In-order to list inserted employees we can use employeeList property in employee-list component. So first of all we have to Inject this service class inside child components. Before that we have to discuss our application structure.

Application Structure:

21. This our application structure, component employees will be the parent component for employee and employee-list component.
We are going to inject EmployeeService inside the Parent Component Employees and there by we can access the same injected service instance from child components Employee and Employee-List. So whenever we make changes in one child component same change can be seen from other child component also.

Inject Employee Service in Components:

22. First of all inject the service class inside parent component Employees


To inject a class inside a component, mention the class inside component providers array and then create private parameter inside component constructor.

Now we can use this injected instance in child components, for that you can do this, inside employee.component.ts file

Inside employee-list.component.ts file
 

Angular 5 CRUD Operations Form:

23. We’ll create an employee form to implement Insert and Update Operation with employee Component. For that, let’s create a Template Driven Form (TDF) using selectedEmployee property from injected EmployeeService Class.

So first of all we have to import FormsModule in appmodule.ts file.


You can use following html in employee.component.html file.

and this employee form with data looks like this.


This form is a collection of label – text box pair with Submit and Reset button. We have an extra hidden field to store $key of current employee. Same form is used for Insert and Update Operation.

Form Validation:

24. required attribute is set to name text box, so employee name is mandatory to submit this form. When name text-box is invalid, ng-invalid and ng-dirty classes are added to it. So based on these we have implemented form validation.

When name is empty, employee form as whole is not valid so we add conditional disable attribute to Submit Button.

<button class="btn btn-default" type="submit" [disabled]="!employeeForm.valid">

To show validation error indication we’ll show red border around the text box using CSS. Here is the complete css rules for this application


Insert, Update and Reset Operation:

25. Inside employee.component.ts file we will write code for Insert and Update Operation. Before that I’m going to install ngx-toastr from npm package, this package helps us to show notification message inside angular applications.

ngx-toastr installation
In-order to install the package, you can use following npm command.
npm install ngx-toastr --save
then add ToastrModule inside app.module.ts file.

src/app/employees/employee/employee.component.ts


restForm() function is used reset form controls value to initial stage, we called this function from reset button click event and from ngOnint  Lifecycle Hook to initialize the form.

Inside the form submit event function OnSubmit, we implement both insert and update operation based on $key value. To show the success message, we use ToastrService class object tostr.

List Inserted Records and Delete Operation:

26. Using employee-list component, we’ll list all inserted employees and then implement Delete Operation.

you can add following inside employee-list component.

/src/app/employees/employee/employee-list.component.ts


Inside this we have injected EmployeeService and ToastrService Classes. Also we created an Employee array employeeList. Inside the ngOnint  Lifecycle Hook, we subscribe to firebase db collection and we store employee records inside an array. Using this array variable, we will display inserted employees inside employee-list component.

employee-list.component.html looks like this.


Component design will look like this.


when we click on pencil button, it will call onEdit() function to populate the corresponding record inside the employee form, after changing user’s details, he can update record as we discussed before(inside employee component).Using trash icon we implemented delete operation with onDelete()  function.

That's all. Hope this tutorial was useful.