Showing posts with label Json. Show all posts
Showing posts with label Json. Show all posts

Thursday, May 4, 2017

Step by Step Guide to Create Deployment Build Using Gulp Automation

Gulp is a JavaScript task runner that enables automation and crunching of monotonous tasks all in one swoop. In a modern workflow, there is probably a host of tools that you're using in development and production. Some of the more popular ones are script concatenation and minification, and Sass compilation.


Gulp


It's often used to do front end tasks like:
·         Spinning up a web server
·         Reloading the browser automatically whenever a file is saved
·         Using preprocessors like Sass or LESS
·         Optimizing assets like CSS, JavaScript, and images
·         Gulp runs much, much faster. Tasks get crunched quicker, and the time you spend between writing code and seeing the changes in the browser is significantly less.

The first step to using Gulp is to require it in the gulp file.

var gulp = require('gulp');

The require statement tells Node to look into the node_modules folder for a package named gulp Once the package is found, we assign its contents to the variable gulp.
The basic syntax of a gulp task is:
gulp.task('task-name',function(){
});
task-name refers to the name of the task, which would be used whenever you want to run a task in Gulp.
Now, Let's create some variables and assign meaningful values to them.
var paths = {uisource: "UI", // Development Environment
    builddestination: "Build", //Build/Deployment Server
   };
We store folder names to the variables. So later when I want to change the name of the folder, I will have to change the values of var paths {} instead of doing change in the whole gulp file. 
Let's move on to create a Project.
You need to have Node.js (Node) installed onto your computer before you can install Gulp.
If you do not have Node installed already, you can get it by downloading the package installer from Node's website.
When you're done with installing Node, you can install Gulp by using the following command on the command line:
npm install --save-dev-g gulp
The -g flag in this command tells npm to install Gulp globally onto your computer, which allows you to use the gulp command anywhere on your system.
If you check the project folder when the command has finished executing, you should see that Gulp has created a node_modules folder. You should also see a gulp folder within node_modules.
When you're done with installing Gulp, you can create the package.json file by using the following command on the command line:
npm init
A package.json file contains metadata about your app or module. Most importantly, it includes the list of dependencies to install from npm when running "npm install" command. If you're familiar with Ruby, it's similar to a Gemfile. 
Gulp is flexible enough to work with any folder structure.
For this article, we will use the following structure.
 |- gulp/
        |- Build/
               |- content/
               |- fonts/
               |- images/
               |- js
       |- UI/
               |- content/
               |- fonts/
               |- images/
               |- js
               |- html
               |- scss
       |- index.html
       |- gulpfile.js
       |- node_modules
       |- package.json          
Now let’s create the first task of connecting to Build/Deployment Server.
We import gulp-connect Plugin which is used to run a web server (with Livereload).

gulp.task('connect', function () {
    console.log("Connect to the Server");
    connect.server({
        root: ".",
        port: 8888,
        livereload: true
    });
})

Now we'll create another task of opening files and URLs on Build/Deployment Server.

We import gulp-open Plugin to achieve this task.

gulp.task('open', function () {
    console.log("Open index.html on Localhost");
    gulp.src('index.html')
        .pipe(open({
            uri: 'http://localhost:8888/'
        }));
})

Now let’s create a task of moving HTML from Development Environment to Build/Deployment Server.

We import gulp-inject and gulp-inject-reload Plugin which is used to inject file references into your index.html.

gulp.task("movehtml", () => {
    console.log("Moving HTMLs to Build/Production Server With Auto Injecting CSS and Js files");
    var userScripts = pipes.devGetAndCopyValidatedUserScripts();
    var userCss = pipes.devGetAndCopyValidatedCss();
    return gulp.src(paths.uisource + '/html/*.{html,htm}')
        .pipe(inject(userScripts, {
            relative: true,
            name: 'bower'
        }))
        .pipe(inject(userCss, {
            relative: true,
            name: 'inject'
        }))
        .pipe(injectReload())
        .pipe(gulp.dest('.'))
        .pipe(connect.reload());
})
pipes.devGetAndCopyValidatedUserScripts = () => {
    return gulp.src([paths.builddestination + '/js/*.min.js']);
}
pipes.devGetAndCopyValidatedCss = () => {
    return gulp.src([paths.builddestination + '/content/*.min.css']);
}

Now we'll create another task of moving CSS from Development Environment to Build/Deployment Server.

We import gulp-cssmin Plugin which is used to minify CSS files.

gulp.task('minifycss', function () {
    console.log("Minify Css files");
    return gulp.src(paths.uisource + '/content/*.css')
        .pipe(cssmin())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.builddestination + '/content/'))
        .pipe(connect.reload());
})

Then, will create another task of moving Js from Development Environment to Build/Deployment Server. 

We import gulp-uglify Plugin which is used to minify files.

gulp.task('minifyjs', function () {
  console.log("Minify Js files");
  return gulp.src(paths.uisource + '/js/*.js')
  .pipe(gulpIf('*.js', uglify()))
  .pipe(rename({
    suffix: '.min'
  }))
  .pipe(gulp.dest(paths.builddestination + '/js/'))
  .pipe(connect.reload());
})

Let's move our fonts from Development Environment to Build/Deployment Server. Generally we use pipe symbol “|” for “or" conditions.

gulp.task('movefont', function () {
  console.log("Moving all fonts in Fonts folder");
  return gulp.src(paths.uisource + '/fonts/*.+(ttf|ttc|pfb|pfm|otf|eot|svg|woff|woff2|pfa|afm|dfont)')
  .pipe(gulp.dest(paths.builddestination + '/fonts/'))
  .pipe(connect.reload());
})


Let's move our Images from Development Environment to Build/Deployment Server.

We import gulp-imagemin Plugin which is used to minify PNG, JPEG, GIF and SVG images.

gulp.task('optimizeimage', function () {
  console.log("Optimize Image files");
  return gulp.src(paths.uisource + '/images/*.+(png|jpg|jpeg|gif|svg)')
  // Caching images that ran through imagemin
  .pipe(cache(imagemin({
    interlaced: true
  })))
  .pipe(gulp.dest(paths.builddestination + '/images/'))
  .pipe(connect.reload());
})

Now create a task which converts Sass files to CSS files and moves CSS files from Development Environment to Build/Deployment Server. 

For this task, we require a couple of Plugins like gulp-sass, gulp-rename, gulp-autoprefixer and gulp-sourcemaps.

Autoprefixer parses CSS files and adds vendor prefixes to CSS rules.Gulp sourcemaps will interpolate between transformations. So that you keep track of every change that happened.

gulp.task('sass', function () {
    console.log("Convert Sass to CSS files");
    return gulp.src(paths.uisource + '/scss/*.scss') // Gets the styles.scss file
        .pipe(sourcemaps.init()) // Initialize sourcemap plugin
        .pipe(sass()) // Passes it through a gulp-sass task
        .pipe(autoprefixer()) // Passes it through gulp-autoprefixer
        .pipe(sourcemaps.write()) // Writing sourcemaps
        .pipe(gulp.dest(paths.uisource + '/content/')) // Outputs it in the content folder
        .pipe(cssmin())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.builddestination + '/content/'))
        .pipe(connect.reload());
})

Now create a task for Deleting Files from Development Environment. Generally, this task runs at the very first stage, before creating a new build.

We import del Plugin which is used to delete files and folders.

gulp.task('delete', function () {
    console.log("Delete files");
    return del.sync(paths.uisource + '/*.+(ttf|ttc|pfb|pfm|otf|eot|svg|woff|woff2|pfa|afm|dfont|html|htm|css|js|png|gif|jpg|jpeg|svg)')
})

Create a task for clearing all Cache from Local Machine. We import gulp-cache Plugin to perform this task.

gulp.task('clearcache', function (callback) {
    console.log("Clearing all Cache from Local Machine");
    return cache.clearAll(callback)
})

Create a task for watching the changes in the files. Watch method is used to monitor your source files. When any changes to the source file are made, the watch will run an appropriate task.

The basic syntax of a gulp.watch() method is:

gulp.watch(Path of Source File', ['Task to be Run']);

We import gulp-watch Plugin to perform this task.

gulp.task('watch', function () {
    console.log("Watch for Changes");
    gulp.watch(paths.uisource + '/html/index.html', ['movehtml']);
    gulp.watch(paths.uisource + '/content/*.css', ['minifycss']);
    gulp.watch(paths.uisource + '/scss/*.scss', ['sass']);
    gulp.watch(paths.uisource + '/js/*.js', ['minifyjs']);
    gulp.watch(paths.uisource + '/fonts/*.+(ttf|ttc|pfb|pfm|otf|eot|svg|woff|woff2|pfa|afm|dfont)', ['movefont']);
    gulp.watch(paths.uisource + '/images/*.+(png|jpg|jpeg|gif|svg)', ['optimizeimage']);
})

Create the last task which runs a sequence of gulp tasks in the specified order.

We import run-sequence Plugin to perform this task.

gulp.task('default', function () {
    runSequence(['delete', 'clearcache', 'minifyjs', 'minifycss', 'optimizeimage', 'movefont', 'movehtml', 'connect', 'open', 'watch'])
})

It's default task of gulp.When you fire a command from cmd (Command Prompt) as "gulp" then this task will run. 

Now our whole gulp file is ready to run....

var gulp = require('gulp');
var watch = require('gulp-watch');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
var inject = require("gulp-inject");
var injectReload = require("gulp-inject-reload");
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var connect = require('gulp-connect');
var open = require('gulp-open');

var paths = {
    uisource: "UI",
    builddestination: "Build",
    uisourcecontect: "content",
    uisourcescss: "scss",
    builddestinationcontent: "content"
};
var pipes = {};

gulp.task('watch', function () {
    console.log("Watch for Changes");
    gulp.watch(paths.uisource + '/html/index.html', ['movehtml']);
    gulp.watch(paths.uisource + '/content/*.css', ['minifycss']);
    gulp.watch(paths.uisource + '/scss/*.scss', ['sass']);
    gulp.watch(paths.uisource + '/js/*.js', ['minifyjs']);
    gulp.watch(paths.uisource + '/fonts/*.+(ttf|ttc|pfb|pfm|otf|eot|svg|woff|woff2|pfa|afm|dfont)', ['movefont']);
    gulp.watch(paths.uisource + '/images/*.+(png|jpg|jpeg|gif|svg)', ['optimizeimage']);
})
gulp.task('movefont', function () {
    console.log("Moving all fonts in Fonts folder");
    return gulp.src(paths.uisource + '/fonts/*.+(ttf|ttc|pfb|pfm|otf|eot|svg|woff|woff2|pfa|afm|dfont)')
        .pipe(gulp.dest(paths.builddestination + '/fonts/'))
        .pipe(connect.reload());
})
gulp.task('minifyjs', function () {
    console.log("Minify Js files");
    return gulp.src(paths.uisource + '/js/*.js')
        .pipe(gulpIf('*.js', uglify()))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.builddestination + '/js/'))
        .pipe(connect.reload());
})
gulp.task('minifycss', function () {
    console.log("Minify Css files");
    return gulp.src(paths.uisource + '/content/*.css')
        .pipe(cssmin())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.builddestination + '/content/'))
        .pipe(connect.reload());
})
gulp.task("movehtml", () => {
    console.log("Moving HTMLs to Build/Production Server With Auto Injecting CSS and Js files");
    var userScripts = pipes.devGetAndCopyValidatedUserScripts();
    var userCss = pipes.devGetAndCopyValidatedCss();
    return gulp.src(paths.uisource + '/html/*.{html,htm}')
        .pipe(inject(userScripts, {
            relative: true,
            name: 'bower'
        }))
        .pipe(inject(userCss, {
            relative: true,
            name: 'inject'
        }))
        .pipe(injectReload())
        .pipe(gulp.dest('.'))
        .pipe(connect.reload());
})
pipes.devGetAndCopyValidatedUserScripts = () => {
    return gulp.src([paths.builddestination + '/js/*.min.js']);
}
pipes.devGetAndCopyValidatedCss = () => {
    return gulp.src([paths.builddestination + '/content/*.min.css']);
}
gulp.task('connect', function () {
    console.log("Connect to the Server");
    connect.server({
        root: ".",
        port: 8888,
        livereload: true
    });
})
gulp.task('open', function () {
    console.log("Open index.html on Localhost");
    gulp.src('index.html')
        .pipe(open({
            uri: 'http://localhost:8888/'
        }));
})
gulp.task('optimizeimage', function () {
    console.log("Optimize Image files");
    return gulp.src(paths.uisource + '/images/*.+(png|jpg|jpeg|gif|svg)')
        // Caching images that ran through imagemin
        .pipe(cache(imagemin({
            interlaced: true
        })))
        .pipe(gulp.dest(paths.builddestination + '/images/'))
        .pipe(connect.reload());
})
gulp.task('sass', function () {
    console.log("Convert Sass to CSS files");
    return gulp.src(paths.uisource + '/scss/*.scss') // Gets the styles.scss file
        .pipe(sourcemaps.init()) // Initialize sourcemap plugin
        .pipe(sass()) // Passes it through a gulp-sass task
        .pipe(autoprefixer()) // Passes it through gulp-autoprefixer
        .pipe(sourcemaps.write()) // Writing sourcemaps
        .pipe(gulp.dest(paths.uisource + '/content/')) // Outputs it in the content folder
        .pipe(cssmin())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(paths.builddestination + '/content/'))
        .pipe(connect.reload());
})
gulp.task('delete', function () {
    console.log("Delete files");
    return del.sync(paths.uisource + '/*.+(ttf|ttc|pfb|pfm|otf|eot|svg|woff|woff2|pfa|afm|dfont|html|htm|css|js|png|gif|jpg|jpeg|svg)')
})
gulp.task('clearcache', function (callback) {
    console.log("Clearing all Cache from Local Machine");
    return cache.clearAll(callback)
})
gulp.task('default', function () {
    runSequence(['delete', 'clearcache', 'minifyjs', 'minifycss', 'optimizeimage', 'movefont', 'movehtml', 'connect', 'open', 'watch'])
})

Now Open your cmd (Command Prompt), go to Project Path where your gulp file is located. Type gulp or gulp default in cmd. 

Our gulp file runs like this....



Now, your final Deployment Build is ready. 

Our final Project Structure looks like this....


Guys, now you have now leveled up by knowing how to deal with Gulp. 

I am attaching whole Project Source Code along with the package.json file.Thus, you don't need to download any dependencies which require running gulp file.   





Wednesday, March 1, 2017

Read WhatsApp Web DOM Elements Using Chrome Extension

A Chrome extension gives Image Paths and Captions of Images which are posted in a WhatsApp Group.

Writing a Chrome extension can be a bit tricky initially, due to its API and the way you have to structure your code. 


WhatsApp Web


In this post, I want to show how you can write a simple extension that reads the Dom Elements of the WhatsApp Web page once it’s loaded. The whole lot is in Javascript, which gives you easy access to the DOM.

Features of Chrome Extension (Information Display in Console)
  • Image Paths are displayed.
  • Image Captions are displayed.
  • The Image who has no caption to display, for that "No Caption" Text is displayed.
  • Image Paths and Captions are displayed in a consecutive manner. So that End User can easily find out the Caption with respect to the Image.
Architecture of an Extension

  • Background page - not visible by the user. A long running script that handles the state of your extension. Communicates with other parts of the extension with messaging.
  • Event page - the same as a background page, but only executes in response to events you define. Preferred to background pages as they are less resource intensive.
  • Options page - UI page that allows a user to set options. An HTML page that references javascript files.
  • Browser actions/page actions - an icon either in the extension bar or the Omnibox respectively. Clicking on the icon will show an UI tab which is an HTML page that can reference javascript. These pages cannot communicate with the website resources/DOM, it needs to message the content script to do that.
  • Content scripts - javascript only. What is used to modify the page itself? The only part that can access and modify the DOM but not code loaded by the website. Files are run once for each page that matches the manifest. All the JS files in the list are loaded so you can use libraries just by including it. This is what we’ll use for our extension.
There are plenty more elements that can be used in an extension, but this list covers the core that will get most of your extension built and most other parts are for specific tasks.
Permissions
When users see ‘This extension can see and modify data on all pages’, they get nervous. So it’s best to limit where your extension will be active by explicitly setting permissions in the manifest.
You’ll also need to specify what pages your content scripts will match and run on. 
[manifest.json]
"permissions": [
    "tabs", "http://www.google.com/*"
  ],
Writing your own extension
Let’s start with the manifest. We need to state which version it is, if you’re uploading a new version to the web store, the version number must be greater than the existing one. Don’t confuse this with the manifest_version, which is always 2 and is not extension specific.
Create a new folder called ‘WhatsAppWeb’ then a new file called ‘manifest.json’ inside it and copy the following into it.
[manifest.json]
{   "manifest_version": 2,
     "name": "WhatsAppWeb",
    "description": "This extension gives Image Paths and Captions of Images which was Posted in a WhatsApp Group.",
    "version": "1.1",
    "icons": {
    "16": "daisy_16.png",
    "48": "daisy_48.png",
    "128": "daisy_128.png"
    },
    "content_scripts": [
        {"matches": ["https://web.whatsapp.com/*"],
            "js": ["jquery-2.2.0.min.js", "whatsappweb.js"],
            "run_at": "document_end" } ] 
}
You must supply 3 icons in sizes 16, 48 and 128 px. These are used on the extension page and the toolbar.
You can now load your extension into Chrome. Go to Window -> Extensions to open the extensions page. Tick developer mode on the top right which allows you to load your own extensions. Click the ‘Load unpacked extension’ button and then select the ‘WhatsAppWeb’ directory. You should now have something that looks like this:

To modify a page we need a content script. Now save a new file called whatsappweb.js and the following as the content:

[whatsappweb.js]

document.addEventListener("DOMNodeInserted", function (event) {
    var tempHTML = "<html>" + $("html").html() + "</html>";
    loadData();
});

function loadData() {
    var images = [];
    var caption = [];
    
    $("#main .message-list .msg .bubble-image img").each(function () {
        images.push($(this).attr('src'));
    })
    console.log(images);
    
    $("#main .message-list .msg .bubble-image").each(function (i) {
        if ($(this).children('.image-caption').length > 0 &&      $(this).children('.image-caption').length !== 'undefined') 
 {
         caption.push($(this).children('.image-caption').children('.emojitext').text());
        } 
        else {
          caption.push("No Caption");
        }
    })
    console.log(caption);
}

Go back to the extensions page and hit reload or press Ctrl + R (this is very important. If you ever wonder why nothing changed even though you updated the code this is probably the reason).

Go to a WhatsApp Web. Use WhatsApp on your phone to scan the code. Once you have done with it, your WhatsApp screen will be visible on your Desktop/Laptop Screen. 

Create a dummy group says for example "Test", add some participants in it. Now post a couple of images with captions as well as without captions in the same group. Ask Group Participants to post the same. 

Now press an F12 key, go to Console Tab. You get the following output.


Image Paths and Captions are displayed in a sequential manner. So that End User can easily find out the Caption with respect to the Image.

In this way, you can read WhatsApp Web Dom Elements Using Chrome Extension. I am attaching Source Code for your reference.

Source Code

Happy learning..:)


  

Saturday, January 14, 2017

JSON (JavaScript Object Notation) HTTP Request by Ajax to Show Data on Webpage

First,We create one .Txt file which contains names of different countries.

Country.txt File: 
  1. [  
  2.     {  
  3.         "display""India",  
  4.     },   
  5.     {  
  6.         "display""China",  
  7.     },   
  8.     {  
  9.         "display""USA",  
  10.     },   
  11.     {  
  12.         "display""UK",  
  13.     },   
  14.     {  
  15.         "display""Canada",  
  16.     },   
  17.     {  
  18.         "display""Japan",  
  19.     },   
  20.     {  
  21.         "display""Russia",  
  22.     },   
  23. ]  
In the second step, Reads the data from file and display it to the webpage. Use XMLHttpRequest to read the text file, and use fetchData () to display the array.

JsonHttpXmlReqbyAjax.html  
  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4. <div id="maindiv"></div>  
  5. <script>  
  6. var xmlhttp = new XMLHttpRequest();  
  7. var url = "Country.txt";  
  8. xmlhttp.onreadystatechange = function()  
  9. {  
  10.    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)  
  11.    {  
  12.          var myarray = JSON.parse(xmlhttp.responseText);  
  13.          fetchData(myarray);  
  14.    }  
  15. }  
  16. xmlhttp.open("GET", url, true);  
  17. xmlhttp.send();  
  18. function fetchData(arr)  
  19. {  
  20.          var out = "";  
  21.          var i;  
  22.           for(i = 0; i < arr.length; i++)  
  23.          {  
  24.                out += arr[i].display + '<br>';  
  25.          }  
  26.          document.getElementById("maindiv").innerHTML = out;  
  27. }  
  28. </script>  
  29. </body>  
  30. </html>  
After completing all these steps, you will get following output.

India
China
USA
UK
Canada
Japan
Russia 
Enjoy Coding...!!!