Friday, January 27, 2017

Building the UI with GridLayout in NativeScript

NativeScript is a cross-platform mobile applications development platform using JavaScript, TypeScript or Angular. Telerik – a Progress Company (NASDAQ: PRGS), created NativeScript. NativeScript is a different technology - it is a runtime, not a web technology.

To try out this blog post, basic understanding of JavaScript, CSS, Terminal usage and any text editor knowledge will be helpful.

To begin with, we need to have NativeScript installed on the workstation to start coding. Download link to NativeScript is shared below:

NativeScript - http://docs.nativescript.org/angular/tutorial/ng-chapter-1#11-install-nativescript-and-configure-your-environment

NativeScript supports various layouts:
  1. FlexboxLayout
  2. AbsoluteLayout
  3. DockLayout
  4. GridLayout
  5. StackLayout
  6. WrapLayout

The example is this blog post explains usage of GridLayout. To start coding navigate to the terminal or command prompt. We first run the command "tns --version" to check NativeScript installation.

GridLayout in NativeScript, NativeScript version check command


If you can see version of NativeScript, we can proceed to creating our demo project. To create a new project we execute command "tns create *project-name* --ng". Please refer below screen-shot for more information on success of project creation.

NativeScript command for project creation, GridLayout in NativeScript

Once the project is created, navigate to the project folder with change directory command. We need to add platform based on the device we need to test the demo project on. The command to add platform is "tnd platform add android"

GridLayout in NativeScript, NativeScript command for adding android platform CLI

After adding the platform we are all set to add GridLayout for our UI in the demo application. Let us take a look at the  project folder structure. By default when a new project is created with NativeScript CLI, it has a basic template with "Tap the button" functionality. 

GridLayout in NativeScript


The most important folder on which we will focus now is 'app' folder. This folder contains source code of the application including all the classes, html and css. To make the demo for GridLayout, we will navigate to this folder and modify the 'app.component.html' file. Before making any changes, lets run the project once and see the output. The command for running the project is "tns run android --emulator". If android phone is connected to the development pc in debug mode then command used will be "tns run android" or "tns run android --watch". Please refer below screen shot for output.

GridLayout in NativeScript


GridLayout defines grid for the available screen area on the device. In this example, we will create 3x3 grid which means, three rows and three columns. We will try to place one icon in absolute center of the device screen. To be more precise, we will place one icon in grid (1,1). The grid system considers first row and column to be zero, so (1,1) refers to first row, first column.

Consider the code below for initializing the GridLayout.
<GridLayout columns="*, auto, *" rows="*, auto, *">

</GridLayout>

The columns attribute in the code signifies three columns as "*, auto, *". 'auto' occupies the height as much as the content is placed in this grid. "*" signifies all the remaining area will be used. As in code above we have two "*" and one "auto". So the content height will be used by "auto" and the remaining area will be used by other two "*" columns. Similarity the rows attribute has "*, auto, *" so content width will be used by middle row and remaining two rows will use the remaining area excluded by the "auto" row.

The final code for GridLayout will look something like below:

<GridLayout columns="*, auto, *" rows="*, auto, *">
    
    <Label text="Label 1" row="0" col="0" backgroundColor="white"></Label>
    <Label text="Label 2" row="0" col="1" backgroundColor="green"></Label>
    <Label text="Label 3" row="0" col="2" backgroundColor="white"></Label>
   
    <Label text="Label 4" row="1" col="0" backgroundColor="blue"></Label>  
    <Label text="Label 5" row="1" col="1" backgroundColor="orange"></Label>    
    <Label text="Label 6" row="1" col="2" backgroundColor="blue"></Label>
    
    <Label text="Label 7" row="2" col="0" backgroundColor="pink"></Label>
    <Label text="Label 8" row="2" col="1" backgroundColor="purple"></Label>
    <Label text="Label 9" row="2" col="2" backgroundColor="pink"></Label>    

</GridLayout>

When we run the above code, it rendered like below screen on emulator.

GridLayout in NativeScript

Now we have a 3x3 GridLayout. As shown in picture above "Label5" refers to the center of the device which is row-1 and column-1. We will target this grid to add one image or icon. Let us change this grid content as below:
<Image src=" https://image.flaticon.com/teams/1-freepik.jpg" row="1" col="1" stretch="none"></Image>

After adding image to  grid of row-1 and column-1, our output changes as shown in screen-shot from emulator:

GridLayout in NativeScript

As shown above, the "auto" property helps in expanding the grid to contain the graphic and remaining grid use the rest available area as denoted by "*" property of rows and columns.

The complete working example can be seen in video below:



Download completed project file - Click here

-Nitin



Monday, January 23, 2017

Send/receive data from Javascript to Node.js using Express

One of the most basic requirement while creating node js web applications is to send and receive data between HTML client and Nodejs server pages. This blog post shows how can we send data from HTML forms using javascript to node.js server and receive the response.

There can be multiple ways to achieve the above-mentioned task. My post explains this communication with one simple example. In this example, we have one HTML form with username and password. Once the user submits the form data, it goes to node.js server and response is send back to HTML page about the status of the user.

To begin with, we need to have node.js installed on the workstation to start coding. Download link to node.js is shared below:

Node.js - https://nodejs.org/en/

We can use open source editors like sublime, atom or visual studio code for writing our codes. Download links for them are shared below:

Atom - https://atom.io/

Sublime - https://www.sublimetext.com/3

Visual Studio Code - https://code.visualstudio.com/

Once we are done with the setup, we start by initializing our project. Navigate to command prompt and change directory to the project folder. Please refer screenshot below for node project initialize command.

Node.js command for project initialize


Once "npm init" command is executed on command prompt you will set up your project by entering all the required fields as shown below:

Node.js command for project initialize


After the execution is complete, we can see a "package.json" file which stored all the information. Also keep a note of entry point "index.js" file as shown above. The main purpose of "package.json" file is to document for what packages your project depends on. It also makes our build reproducible which means, if we share our code with other developers it is easier for them to load dependencies and run the project easily.

To use the express server, we will install it in our current project. Any dependency required in the project is installed with npm command. In this example, we will install express using "npm install express" command.

Adding express server to node.js project


As mentioned in the initialize project configuration, we can create our index.js file. 

index.js

This file acts as main launch file for the node js web application. This file would be listening to a port which will act as a server.

var express = require('express');
var app = express();
app.use(express.static('public'));

//Routes
app.use(require('./routes'));  //http://localhost:8000/    http://localhost:8000/login
var server = app.listen(8000, function () {
  var host = server.address().address
  var port = server.address().port 
  console.log("Example app listening at http:// ", host, port);
});

One very important thing apart from listening to port is "Routes" in the index.js file. We create a routes file and define the behavior of our web application navigation in this file. Lets us have a look at our routes.js file below:

routes.js

The first route defined in the below file is for the index.html file. The index.html file is main launch file which is connected or mapped to the root of the application. The second route which is "/login" route will be used as POST URL from javascript in our HTML file. As shown below, we are also having a new dependency which we need to install with the command "npm install body-parser". body-parser gives you a middleware which uses the incoming request data to await the full, raw contents of the request body before "parsing it". "body-parser" extracts the entire body portion of an incoming request stream and exposes it on req.body as something easier to interface with.

var express = require('express');
var router = express.Router();
var path = require('path');
var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({ extended: false })


// Define the home page route
router.get('/', function(req, res) {  
  res.sendFile(path.join(__dirname +'/index.html'));
});


// Define the login route
router.post('/login',urlencodedParser, function(req, res) 
{
     if (!req.body)
     return res.sendStatus(400);  
    
     console.log("userid -> ",req.body.userid)
     console.log("password -> ",req.body.pwd)

     // we can connect and validate username and password from database
     // this project example does not include scope for database connection
     // here we will try to send static values from node.js to html and see response on client side
     var userstatus = false;

     res.setHeader('Content-Type', 'application/json')        
     res.end('{"userexist": '+userstatus+'}'); // userstatus is send to html client as response from node.js

});

module.exports = router;

The main client file which is connecting to the node.js server code is index.html. This file acts as the entry point of the application and loads a view to interact with the server.

index.html

The code below is used to render HTMLform which is sending data to the node.js code. The most important part in the code below in script tag which contains the javascript which is used for communication.

As shown, jQuery ajax call is made with POST method to connect to node route "http://localhost:8000/login" . The 'data' property is used to send the data to node.js server in JSON object format.

<!DOCTYPE html>
<html>
<head>
  <title>New Website</title>
 
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="css/style.css">

</head>

<body>


<div class = "container">
  <div class="wrapper">
    <form  method="post" name="Login_Form" class="form-signin" id="form.login" action="/login" >       
        <h3 class="form-signin-heading">Welcome ! Please Sign In</h3>
        <hr class="colorgraph"><br>
        
        <input type="text" class="form-control" name="InputUsername" id="InputUsername" placeholder="Username"  required="" autofocus="" />
        <input type="password" class="form-control" name="InputPassword" id="InputPassword" placeholder="Password"  required=""/>          
       
        <button class="btn btn-sm btn-primary btn-block"  id="SubmitBtn" value="sendData" type="button" >login</button> </br>
       
        <div id="select_link"  style="display:none ">
          <h6> You are not registered user. <a href="/signup">Click here </a> to signup.</h6>
        </div>
    </form>     
  </div>



<script type="text/javascript">
    $(document).ready(function(){
    $("#SubmitBtn").on("click",function(){
       //reading form data to send information to node.js
       var userid =$("#InputUsername").val(); 
       var pwd =$("#InputPassword").val();

       //send data as POST to node url defined in node routes
        $.ajax({
        type: 'POST', 
        url: 'http://localhost:8000/login',
        data: {"userid":userid,"pwd":pwd},        
        //success function executes once communication with node.js is complete and we receive response from node as data params
        success: function (data) {
            var receivedData = data;            
            if (receivedData.userexist == false) {
              $("#select_link").show()
            }
        },
        error: function (xhr, status, error) {
            console.log('Error: ' + error.message);
            console.log('Error connecting to the server.');
        }
        });
    });
  });
  </script>
 
</div>
</body>
</html>

The complete working example of this communication can be seen in video below:




Download completed project files - Click here

-Nitin



Using FormBuilder, Validators & FormGroup in Angular 2 to post data to Node server (node.js)

This blog explains usage of  FormBuilder , Validators , FormGroup classes in Angular 2 projects. In this post we will create HTML form a...