Getting started with TypeScript(TS)

In this article we will gonna learn some basics of TypeScipt.

  1. Installation of TypeScipt
  2. Introduction of TypeScipt
  3. Getting started with TypeScipt
    • Basic data type

So let’s start…….

1.Installation of TypeScipt

Step 1: Install node.js https://nodejs.org/en/download/ . Node basically provides server side environment. By installing node we will get Node Package Manager(NPM).

Npm helps us to  install packages. Package is basically javascript file library which can be use in your project.

If you want to know node is installed or not then open your CMD and type following command
C:\Users\AM\Desktop\TypeScript>node
>

If you want to know version of node then
C:\Users\AM\Desktop\TypeScript>node -v
v10.15.1

step 2: Now it’s time to install TypeScript
C:\Users\AM\Desktop\TypeScript>npm install -g typescript
Above command will install latest version of TS at global level. If you wants to install it locally(i.e for folder only) don’t use -g . To install older version use
C:\Users\AM\Desktop\TypeScript>npm install -g typescript@1.7.5

To know TS version use following command
C:\Users\AM\Desktop\TypeScript>tsc -version
Version 3.3.3333

step 3: We need some editor to write our code. Here i am using Visual Studio Code

2.Introduction of TypeScript

->TypeScript is a language.It’s a super set of JavaScript.
->Ts can be used where you want to write JavaScript.
->When compiled it generates JavaScript.
->TS provides compile time environment where JS lacks. Which means less exceptions or bugs.

->ECMAScript 6 is also called as  ES6 or ECMAScript 2015 or JavaScript 6. ->TypeScript is Extension of ES6
-> We can say JS(parent)->ES6(child of JS)->TS(child of ES6||JS6)

How Typescript make life easier???
practis.js:
function division(a, b) {
return a > b;
}
console.log(division(2,1));

O/P:
C:\Users\AM\Desktop\TypeScript>node practis.js
true

In the above example we have written simple javascript function which accepts two parameters compare it and returns the result. here we have pass two numbers.Let’s see what happens when we pass different type of parameter.

function division(a, b) {
return a > b;
}
console.log(division(2,"1"));

O/P:
C:\Users\AM\Desktop\TypeScript>node practis.js
true

When we pass one number and another string it also gets compared and result is true. This is wrong we can’t compare number with string. In the JavaScript we can’t specify data type of parameters. But in TypeScript you can specify type of arguments you want to accept. let’s see an example.
practice.ts:

In the above example we have written function which will accept two parameter both of type number. If you try to pass string it will throw an error.

We are all set 😉 Let’s start with TypeScript Programming…..

practis.ts
let a="Welcome to JustCompile"
console.log(a);

We have initialized one variable which stores string value. Next line print’s value of variable. Save file with .ts
Run that file with command
tsc practis.ts
after compilation we will get new Javascript file i.e practis.js.
here is the generated js file:
practis.js
var a = "Welcome to JustCompile";
console.log(a);

Now we have to execute this js file with
node practis.js

o/P:
Welcome to JustCompile

To be continued……. 😉

Please follow and like us:

Routing Without Express

Introduction

Today we are going to learn how routing works. In my previous article of Node.JS I have covered basics knowledge and how to start with Node.JS. If you don’t have basic idea of Node.JS please refer my previous article. All About Node.JS

This article covers the following areas
What is Routing?
Create Server
Example of Routing

What is Routing?

Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed to the code that handles them.

Prerequisites

Basic knowledge of
Node.JS

Create Server

To create a Node.JS server, here is few simple steps to follow:
Create NodeJSRouteApp folder.
In above folder create app.js file.

const http=require('http');
const port=3000;
const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type', 'text/html');
res.write('<h1>Hello World<h1>'); //write a response
res.end();
});
server.listen(port,()=>{
console.log('Server is running at ',port);
});

Now to run your node server run the command in your terminal
>node app.js
you will see “server is running at 3000” message in your terminal.
now go to your browser window and type URL http://localhost:3000/ you will see

 

Yehh😁! Our Node.JS server create successfully.

Let’s observe the output more deeply
Just right click on browser window and select inspect or you can just have  pressed f12 key
Go to Network tab
Select name localhost

It will give us all information like header, response etc.
In header tab we can see
Request URL- http://localhost:3000/
status code which is 200 means OK.
Request method – GET
Response Header contains Content-type: text/html


If you select Response tab you can see our message- ‘Hello World’



Now let’s finding the problem with URL http://localhost:3000/
If we add anything after above URL like http://localhost:3000/home/profile/
It will always show output Hello World

Oops😶! This is something which we don’t want.🤦‍♀️
Need to think some solution for this🤔
Let’s log req parameter to check what it gave us.

const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type', 'text/html');
res.write(<h1>Hello World<h1>'); //write a response
console.log(req)
res.end();
});


 

Ohhh, look what I found😃. Using URL, we can restrict other endpoints or path not to be hit.

Let’s add routing to avoid this problem into app.js file

const http = require('http');
const port=3000;
const server=http.createServer((req, res) =>{
    res.statusCode=200;
    res.setHeader('Content-Type', 'text/html');
    let url = req.url;
    if(url ==='/home'){
    res.write('<h1>Just Compile<h1>');
    res.end(); 
    }
    else if(url ==='/about')
    {
     res.write(`Just Compile believes in team work.
        Irrespective of project size they believe 
        in executing every project as a team. 
        They have a team of highly qualified 
        engineers with each specializing in their own 
        field like designing, testing and development.`);
     res.end();
   } 
   else if(url ==='/contact')
   { 
    res.write('<h1>contact us page<h1>');
    res.end(); 
   } 
  else
   { 
   res.write('<h1>404 Page<h1>'); 
   res.end(); 
   } 
}); 
server.listen(port,()=>{ 
console.log('Server is running at ',port); 
});

Finally, let’s run our server from the command line and see if it works! Let’s type  name of our server, port and corresponding endpoint(path) in our browser:
Now if we add URL http://localhost:3000/home
It will navigate you on below page

http://localhost:3000/about

http://localhost:3000/contact

If you enter other than above route like http://localhost:3000/fb
You will end up with 404 Page

 

Cool, now this is something which we want.😎

So, today we have learned how to route through multiple endpoints without express.

I hope this article will help you. Please put your feedback using comment which helps me to improve myself for next post. Thank You!

Please follow and like us:

All About Node.JS

Introduction

Now a day, Node is the fastest growing open source platform in the world. If you are wondering what Node.JS is and why is it so popular? so today, I am here to give you brief introduction about it.

This article covers the following areas of Node.JS.
Before starts with Node.JS
What is Node.JS
Why is it so popular?
Installation of Node.JS and NPM
Node Package Module (NPM)
Package.json
Example

Prerequisites

Basic knowledge of
HTML
JavaScript

Before starts with Node.JS

Common task for web server is to open a file on the server and return content of that file to the client.
Web applications written in a client- server model where
 The client would request for the file from the server and the server would respond with that file and close the connection after each response.

Now the question is, how server respond to millions of requests which is coming at the same time?
Lets Consider one example of ticket counter,
In ‘xyz’ station have only one ticket counter. When passenger count is increases its difficult to handle all passengers.Passengers would have to wait.
Solution for this problem is to increase ticket counters.
Here’s the concept coming named as Threads.

But this is not a good solution. Because, there is some point when request count is increases and each request is starting with new thread. Problem with this is, it consumes lots of memory and resources.

Yehhh😎, Now Here’s the time when Node.JS come

What is Node.JS?

Node.JS is runtime environment for executing JavaScript code outside of a browser. It is built on Google Chrome’s JavaScript Engine also known as V8 Engine.

Hmm, question raised in your mind right?🤔
So, what actually is a JavaScript Engine?

V8 is a powerful open source JavaScript engine provided by Google. It is a program that converts JavaScript code into machine code that microprocessors can understand.

Node.JS is not a framework and also not a programming language. Node.JS can use for building back-end services like APIs.

How Node.JS Works?

A Node.JS app is run by single process, without creating a new thread for     every request.
While performing I/O operations, when the response comes back Node.JS resume the operations instead of blocking the thread.
This allows Node.JS to handle thousands of request with single server.

This all possible because of Event Loop
Now the question is What is Event Loop?🤔
It is a program that waits for events and dispatches them when they happen

Why Node is so popular?

1] Single Programming Language for both Front-End and Back-End.
Most important reason to use Node.JS is It uses JavaScript everywhere so it’s easy for a JavaScript programmer to build back-end services using Node.JS
2] Fast
Node.JS is built on top of the Chrome JavaScript Engine. It is Non-Blocking Input/output means it can read data and send it back very fast.
3] Used on Multi-Platform
It has a real cross-platform language which allows Node.JS to be used on Mac, Windows, and Linux.

Installation of Node.JS and NPM

Installation steps:
1. Download the installer from Node.JS official website
2. Run the installer.
3. Now, test Node.JS version using the following command.
> node –v
v11.0.0

4. To test NPM version
> npm –v
6.4.1

Node Package Module

NPM is the package module which helps JavaScript developers load dependencies effectively. Following command used to load dependencies.
> npm install

This command is finding a json file named as package.json in root directory to install all dependencies defined in the file.
Package.json look something like below
{
"name": "NodejsApp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4",
"mongoose": "^5.4.8"
}
}

The most important things in your package.json are name and version. Those are actually required, and your package won’t install without them.

Script
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app"
},

If there is a app.js file in the root, then npm will default the start command to node app

Dependencies
"dependencies": {
"express": "^4.16.4",
"mongoose": "^5.4.8"
}

Dependencies are specified in a simple object that maps a package name to a version range.

Example of Node.JS Application

Let’s Starts for doing some code😊
To create Node.JS application follow below listed steps:
Import required modules
Create server.
Read request and return response

Let’s create app.js file
const http=require('http');
const port=3000;
const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port,()=>{
console.log('Server is running at ',port);
});

1] http
On the first line, we required the HTTP module. The module provides as interface to deal with http operations.

This is how we import modules
const http=require(‘http’);

2] create server
we call the createServer() method which will helps to creates a server.
const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});

It will create server with response having status code 200, content type plain text and ‘Hello World’ response which is server sends to the browser. The request and response objects have information about incoming request and outgoing responses.

3] Read request and return response
After creating server, now it’s time to assign port number.
server.listen(port,()=>{
console.log('Server is running at ',port);
});

Here, the server listens to localhost on port 3000 and log “Server is running at 3000” in command prompt.

It’s time to run our app.js file.

Type url http://localhost:3000/ in the browser, to display Hello World string as shown on the screen below :

Congrats😄

You now know how to create Simple Node.JS app 😄

I hope this article was helpful for you. If it was, please leave a comment and clap it up! Thank You!

Please follow and like us:

TelerikListView LoadOnDemand With Command Xamarin Forms

 

TelerikListView LoadOnDemand With Command

Explanation:

Instead of loading the huge data into listView at Once , we can Populate our ListView Itemsource whenever the user scrolls down .

when List is loaded for First Time , we’ll set only few Items in List when user will scroll further more data will be set to Itemsource of List.

Lets see How I did it …

There is 2 Types of LoadOnDemand

  1. Automatic
  2. Manual

In Automatic the Busy Indicator of Data Loading will be automatically Visible

when you set IsLoadOnDemandEnabled to true .

In Manual , A Button will appear end of List, on clicking it, Data Will be loaded

further.

LoadMoreItemCommand will recursively set ListView Itemsource Whenever

user scrolls down.

ListViewLoadOnDemandCollection inherits ObservableCollection, ListView

Itemsource will be of type ListViewLoadOnDemandCollection .

here in my code

LoadDataFirstTime() will Load Initially Few Items in ListView , where I

Initialized ListView Itemsource and added few Items.

LoadDataOnDemand() this method will be called when data is present in List

and IsLoadOnDemandEnabled is set to true .

else you’ll never get Hit in Your LoadMoreItemCommand .

 

XAML

<ContentPage.BindingContext>
    <local:LoadOnDemandVM></local:LoadOnDemandVM>
</ContentPage.BindingContext>
<ContentPage.Content>


    <telerikDataControls:RadListView x:Name ="listView"
                                        IsLoadOnDemandEnabled="{Binding  IsLoadOnDemandEnabled}"
                                        ItemsSource="{Binding Source}"
                                        LoadOnDemandMode="Automatic">


        <telerikDataControls:RadListView.ItemTemplate>
            <DataTemplate>
                <telerikListView:ListViewTemplateCell>
                    <telerikListView:ListViewTemplateCell.View>
                        <StackLayout Padding ="8,8,8,8">
                            <Label Text ="{Binding Name}" />
                        </StackLayout>

                    </telerikListView:ListViewTemplateCell.View>
                </telerikListView:ListViewTemplateCell>
            </DataTemplate>
        </telerikDataControls:RadListView.ItemTemplate>
        <telerikDataControls:RadListView.Commands>
            <telerikListViewCommands:ListViewUserCommand Command ="{Binding LoadMoreItemsCommand}"
                                                             Id="LoadOnDemand" />
        </telerikDataControls:RadListView.Commands>
    </telerikDataControls:RadListView>
</ContentPage.Content>

 

ViewModel

public class LoadOnDemandVM : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public LoadOnDemandVM()
    {
        LoadDataFirstTime();
        this.LoadMoreItemsCommand = new Command(() =>
        {
            LoadDataOnDemand();
        });

    }
    public List<Employees> _data = new List<Employees>()
    {
        new Employees(){Name="abc"},
        new Employees(){Name="bcd"},
        new Employees(){Name="cde"},
        new Employees(){Name="def"},
        new Employees(){Name="efg"},
        new Employees(){Name="fgh"},
        new Employees(){Name="ghi"},
        new Employees(){Name="hij"},
        new Employees(){Name="ijk"},
        new Employees(){Name="jkl"},
        new Employees(){Name="klm"},
        new Employees(){Name="lmn"},
        new Employees(){Name="mno"},
        new Employees(){Name="nop"},
        new Employees(){Name="opq"},
        new Employees(){Name="pqr"},
        new Employees(){Name="qrs"},
        new Employees(){Name="rst"},
        new Employees(){Name="stu"},
        new Employees(){Name="tuv"},
        new Employees(){Name="uvw"},
        new Employees(){Name="vwx"},
        new Employees(){Name="wxy"},
        new Employees(){Name="xyz"}
    };

    public ListViewLoadOnDemandCollection Source { get; set; }

    private bool _IsLoadOnDemandEnabled = true;

    public bool IsLoadOnDemandEnabled
    {
        get { return _IsLoadOnDemandEnabled; }
        set
        {
            _IsLoadOnDemandEnabled = value;
            NotifyPropertyChanged();
        }
    }

    public ICommand LoadMoreItemsCommand { get; set; }

    public void LoadDataOnDemand()
    {
        List<Employees> result = new List<Employees>();
        result = _data.Skip(Source.Count).Take(3).ToList();
        for (int i = 0; i < result.Count; i++)
        {
            Source.Add(result.ElementAt(i));
        }

        if (Source.Count >= _data.Count)
        {
            IsLoadOnDemandEnabled = false;
        }
    }

    public void LoadDataFirstTime()
    {
        Source = new ListViewLoadOnDemandCollection((CancellationToken) =>
        {
            Task.Delay(4000, CancellationToken).Wait();
            return null;
        });

        for (int j = 0; j <= 1; j++)
        {
            Source.Add(_data.ElementAt(j));
        }
    }
}
public class Employees
{
    public string Name { get; set; }
}

 

Please follow and like us:

Angular Element

Angular logo

In this article, we will create one simple angular element.

  1. Creating angular Project
  2. Adding element into project
  3. Deploying angular element

Let’s start..

1. Creating angular Project

Create angular project. Here i am creating project with name customer for this i have used V.S Code

2. Adding element into project

install all required files to cerate angular element

>ng add @angular/elements –project=customer

lets create our component which will display customer name and address
app.component.html

app.component.ts

now we need to add our component into module.Here instead of bootstrap:[] we are using entryComponents. use createCustomElement to register custom element with browser Custom Element Registry.

build your project. with the following command you will get new dist folder with some js files

>ng build –prod

We need some more packages to make our component work.

>npm install –save-dev concat fs-extra

create elements-build.js file to pull out all these into one file.

Now add new script to your package.json file, so it will build our component and generate file without hashed name.

“build:elements”: “ng build –prod –output-hashing none && node elements-build.js”

now build project,a fter runing this command you will get new folder it contains js file with element name

npm run build:elements

Now, create index.html file inside element folder

3. Deploying angular element

All is set for running our component we need server here i am using static server

>npm install static-server

Run static server inside your elements folder

>cd elements

>static-server

You might get following error

To solve this add following package

>npm i @webcomponents/custom-elements –save

Add script file into angular.json file

“node_modules/@webcomponents/custom-elements/src/native-shim.js”

Add following into polyfills.js

import ‘@webcomponents/custom-elements/custom-elements.min’;

Here our component is ready

Reason to Use angular element

  • Making reusable component. Which can also be used in non angular platform
  • It can also be used in your server side program
  • We can make dynamic angular application like dynamic dashboard by creating interpreter component which will create dashboard atv runtiime by using DynamicComponentLoader
  • Independent deployment

Please follow and like us:

Getting Started with Angular Material

 

In this article, we are going to show you how to install Angular material to your angular project in few simple steps.So let’s dive right into it.

We are going to divide this article into several section.

  1. Project Creation
  2. Installing and configuring angular material to your project
  3. Creating material module
  4. Example of Angular Material (MatRadioModule)

1)Project Creation

We are going to use Angular CLI to create project ,creating other stuff like module and component etc. So, let’s open a command prompt window and create our Angular project:

ng new angular-material-example

Once the creation is done, we are going to start the Visual Studio Code editor and open our project.

2)Installing and configuring angular material to your project.

We are going to use npm to install the required packages.So, let’s do that first by navigating to the root folder of our project and running the below command.

npm install --save @angular/material @angular/cdk @angular/animations

After installation finishes, we should see this result:

Now, we need to configure animations, by importing BrowserAnimationsModule into the app.module.ts file:

Alternatively, you can disable animations by importing NoopAnimationsModule.

To continue, let’s include the prebuilt theme for Angular Material. The theme is required and we can choose one of the available pre-built themes:

  • deeppurple-amber.css
  • indigo-pink.css
  • pink-blugrey.css
  • purple-green.css

To include a theme, we need to open the styles.css file and include the following line

Now we install hammerjs library to support gesture.

npm install --save hammerjs

After the installation, we are going to import it as a first line in the maint.ts file:

3)Creating material module:

We can import all the required angular material component to our app.module.ts but it is not recommended. Therefore we create a separate module named material.module.ts in that module we import all the required component from angular material library and then we can import this module to our app module.

So, let’s create material module.

npm g module material --spec false

The above command create the module for us with a folder material and inside it material.module.ts file will be created. In created module one thing will be missing when you create module from command that is exports array under @ngModule. So we have to write exports array.For right now we declare exports array empty.

Note:Exports array is containing components.It will allow us to use material module components outside this module.

4)Example of Angular Material (MatRadioModule)

 

First we have to create component. Let’s create component with name RadioExample .

ng g component radio-example --spec false

The above command create component for us and add to the imports of app.module.ts .

 

Example will on radio button. In this example we create radio button group and a label.We show the value of selected radio button value to that label.

First we have to import MatRadioModule module from angular material library to our material module. We have exports our MatRadioModule so app module can use component inside MatRadioModule.

Now we have to import material module to app module.Also add FormsModule as shown below

Open radio-example.component.ts and add these lines of code.

Open radio-example.component.html and add these lines of code.

Open radio-example.component.css and add these lines of code.

Remove defualt code and add selector of radio-example.component to our app.component.html

Now it’s time to run our project and see the outcome.For running our project use ng serve command.

All looks good.

Conclusion : In this article we created angular project and seen basic example to get started with angular material.

 

Please follow and like us: