Monday, February 27, 2017

Calling REST Seb service and parsing JSON DATA using Pyhton


JSON is now a standard way of sending and consuming data between different application using Web service.
JSON allows simple and clean way of data dealing between different application i.e. sender and consumer. In due course of time JSON api are availbale in all the language i.e. python, JAVA, JS, .net etc
Below we example show how to consume REST JSON API http://services.groupkt.com/country/get/iso2code/IN and consume one of its parameter in response
import json
import requests
from requests.auth import HTTPDigestAuth

# Replace with the correct URL
url = "http://services.groupkt.com/country/get/iso2code/IN"
myResponse = requests.get(url)
# check api response is (OK = 200)
if(myResponse.ok):
print("----myResponse.content-------"+ myResponse.text)
jData = json.loads(myResponse.content.decode('utf-8'))
print(jData)
locations = jData['RestResponse']['result']['alpha2_code']
print("locations"+locations)
else:
myResponse.raise_for_status()
Out Put :
----myResponse.content-------{
"RestResponse" : {
"messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Country found matching code [IN]." ],
"result" : {
"name" : "India",
"alpha2_code" : "IN",
"alpha3_code" : "IND"
}
}
}
{'RestResponse': {'messages': ['More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm', 'Country found matching code [IN].'], 'result': {'name': 'India', 'alpha2_code': 'IN', 'alpha3_code': 'IND'}}}
locationsIN

Note :- REST JSON Response 
{
"RestResponse" : {
"messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Country found matching code [IN]." ],
"result" : {
"name" : "India",
"alpha2_code" : "IN",
"alpha3_code" : "IND"
}
}

Calling SOAP Web service using requests module of Python 3.6.0

First you need to install request module else you will get following below error inside code when you try to import request module.
No module named 'requests' Python 3.6.0
use below command to install
c:\Test>pip install requests

image1
Use following below code to call SOAP Webservice using WSDL





note:- This is our SOAP Response xml

<!--soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <!--soapenv:Body>
      <!--ns:getKPIResponse xmlns:ns="http://main.siddhu.com">
         <!--ns:return xsi:type="ax21:KPIDo" xmlns:ax21="http://dataobject.siddhu.com/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <!--ax21:codeReviewCoverage>1<!--/ax21:codeReviewCoverage>
            <!--ax21:testCaseCoverage>1<!--/ax21:testCaseCoverage>
         <!--/ns:return>
      <!--/ns:getKPIResponse>
   <!--/soapenv:Body>
<!--/soapenv:Envelope>

Sunday, February 26, 2017

Simple MYSQL-Python CRUD Operation Example using Tkinter


Python support connection with many RDBMS i.e. Oracle, Cybase, MYSQL etc. In this example we has selected MYSQL as DB and performed basic operation like Select, Insert, Update and Delete.
We had used tkinter as Python UI for user and MYSQLdb package for connecting MYSQL.

from tkinter import *
import tkinter
from tkinter import messagebox
from lib2to3.fixer_util import Number
import MySQLdb

top = tkinter.Tk()
L1 = Label(top, text="First Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = LEFT)

L2 = Label(top, text="Second Name")
L2.pack( side = LEFT)
E2 = Entry(top, bd =5)
E2.pack(side = LEFT)
'''L3 = Label(top, text="Answer")
L3.pack( side = LEFT)
E3 = Entry(top, bd =5)
E3.pack(side = LEFT)'''
def buttonCallBack(selection):
print("E1.get()"+E1.get())
print("E2.get()"+E2.get())
print("selection"+selection)
a = E1.get()
b = E2.get()
if selection in ('Insert'):
# Open database connection
db = MySQLdb.connect("localhost","siddhu","siddhu","siddhutest" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query 
cursor.execute("SELECT VERSION()")

# Fetch a single row 
data = cursor.fetchone()

print ("Database version : %s " % data)

# Drop table if it already exist 
cursor.execute("DROP TABLE IF EXISTS SIDDHU_TEST")

# Create table Example
sql = """CREATE TABLE SIDDHU_TEST (
FNAME CHAR(20) NOT NULL,
LNAME CHAR(20))"""

cursor.execute(sql)

# Inserting in Table Example:- Prepare SQL query to INSERT a record into the database and accept the value dynamic. This is similar to prepare statement which we create.
sql = "INSERT INTO SIDDHU_TEST(FNAME, \
LNAME) \
VALUES ('%s', '%s')" % \
('siddhu', 'dhumale')
try:
# Execute command
cursor.execute(sql)
# Commit changes
db.commit()
except:
# Rollback if needed
db.rollback()
# disconnect from server 
db.close() 
print("Data Inserted properly "+a +"--"+b) 
elif selection in ('Update'): 
# Open database connection
db = MySQLdb.connect("localhost","siddhu","siddhu","siddhutest" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query 
cursor.execute("SELECT VERSION()")

# Fetch a single row 
data = cursor.fetchone()

print ("Database version : %s " % data)
# Update Exmaple:- Update record 
sql = "UPDATE SIDDHU_TEST SET LNAME = '%s'" % (b) +" WHERE FNAME = '%s'" % (a)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback() 
db.close() 
print("Data Updated properly "+a +"--"+b)
elif selection in ('Delete'): 
# Open database connection
db = MySQLdb.connect("localhost","siddhu","siddhu","siddhutest" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query 
cursor.execute("SELECT VERSION()")

# Fetch a single row 
data = cursor.fetchone()

print ("Database version : %s " % data)
# Delete Operation :- Delete Opearations
sql = "DELETE FROM SIDDHU_TEST WHERE FNAME = '%s'" % (a)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
db.close()
print("Data Deleted properly "+a +"--"+b)
else: 
# Open database connection
db = MySQLdb.connect("localhost","siddhu","siddhu","siddhutest" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query 
cursor.execute("SELECT VERSION()")

# Fetch a single row 
data = cursor.fetchone()

print ("Database version : %s " % data) 
# Select Query Example :- Selecting data from the table.
sql = "SELECT * FROM SIDDHU_TEST \
WHERE FNAME = '%s'" % (a)
try:
# Execute the SQL command
cursor.execute(sql)
lname = ""
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1] 
# Now print fetched result
E2.delete(0,'end')
print ("Value Fetch properly lname="+lname) 
E2.insert(0, lname)

except:
db.close()
print ("Value Fetch properly")

BInsert = tkinter.Button(text ='Insert', command=lambda: buttonCallBack('Insert'))
BInsert.pack(side = LEFT)
BUpdate = tkinter.Button(text ='Update', command=lambda: buttonCallBack('Update'))
BUpdate.pack(side = LEFT)
BDelete = tkinter.Button(text ='Delete', command=lambda: buttonCallBack('Delete'))
BDelete.pack(side = LEFT)
BSelect = tkinter.Button(text ='Select', command=lambda: buttonCallBack('Select'))
BSelect.pack(side = LEFT)

label = Label(top)
label.pack()
top.mainloop()

image1

Thursday, February 23, 2017

Simple Add/Sub/Div/Multiplication application in Python with Tk GUI

image_1image_2image_3image_4

from tkinter import *
import tkinter
from tkinter import messagebox
from lib2to3.fixer_util import Number

top = tkinter.Tk()
L1 = Label(top, text="First Number")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = LEFT)

L2 = Label(top, text="Second Number")
L2.pack( side = LEFT)
E2 = Entry(top, bd =5)
E2.pack(side = LEFT)
L3 = Label(top, text="Answer")
L3.pack( side = LEFT)
E3 = Entry(top, bd =5)
E3.pack(side = LEFT)
def helloCallBack(selection):
print("E1.get()"+E1.get())
print("E2.get()"+E2.get())
print("selection"+selection)
a = int(E1.get())
b = int(E2.get())
if selection in ('Addition'):
answer = a + b
print("answer"+str(answer))
E3.delete(0,'end')
E3.insert(0, answer)
elif selection in ('Substraction'): 
answer = a - b
print("answer"+str(answer))
E3.delete(0,'end')
E3.insert(0, answer)
elif selection in ('Division'): 
answer = a / b
print("answer"+str(answer))
E3.delete(0,'end')
E3.insert(0, answer) 
else: 
answer = a * b
print("answer"+str(answer))
E3.delete(0,'end')
E3.insert(0, answer) 
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection) 
if var.get() == 1:
#B.destroy()
selection = 'Addition'
label.config(text = selection) 

elif var.get() == 2:
#B.destroy()
selection = 'Substraction'
label.config(text = selection)

elif var.get() == 3:
#B.destroy()
selection = 'Division'
label.config(text = selection)


else:
#B.destroy()
selection = 'Multiplication'
label.config(text = selection)
B = tkinter.Button(text =selection, command=lambda: helloCallBack(selection))
B.pack(side = LEFT) 

var = IntVar()
R1 = Radiobutton(top, text="Add", variable=var, value=1, command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(top, text="Subtract", variable=var, value=2, command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(top, text="Division", variable=var, value=3, command=sel)
R3.pack( anchor = W)
R4 = Radiobutton(top, text="Multiplications", variable=var, value=4, command=sel)
R4.pack( anchor = W)
label = Label(top)
label.pack()
top.mainloop()

Simple Addition of two value using Python and Tk GUI

Python provides various options for developing graphical user interfaces (GUIs). Tkinter, wxPython and JPython is wellknow.
Tkinter comes in build with Python package and it provide most of the GUI component like canvas, button, checkbox, radiobutton, button etc.
In below example we are using Eclipse IDE along with python plugin to develop gui
Code:-
from tkinter import *
import tkinter
from tkinter import messagebox
from lib2to3.fixer_util import Number

top = tkinter.Tk()
L1 = Label(top, text="First Number")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = LEFT)

L2 = Label(top, text="Second Number")
L2.pack( side = LEFT)
E2 = Entry(top, bd =5)
E2.pack(side = LEFT)
def helloCallBack():
print("E1.get()"+E1.get())
print("E2.get()"+E2.get())
a = int(E1.get())
b = int(E2.get())
answer = a + b
#messagebox.showinfo( "Hello Python", "Hello World")
print("answer"+str(answer))
E3.insert(0, answer)
B = tkinter.Button(text ="Add", command = helloCallBack)
B.pack(side = LEFT)
L3 = Label(top, text="Answer")
L3.pack( side = LEFT)
E3 = Entry(top, bd =5)
E3.pack(side = LEFT)
top.mainloop()

add

Wednesday, February 22, 2017

How to resolve Python version 3.5 required, which was not found in the registry.


While trying to install cx_Oracle-5.2.1-12c.win-amd64-py3.5.exe (md5) for oracle from https://pypi.python.org/pypi/cx_Oracle/ using python we receive following below error
image_1
It indicate entry in your regedit is wrong.
Please follow below step to resolve the same.
Step 1:- Open your reg edit entry
run-->regedit
image_2
Step 2:- go insite HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\ and see what is the folder name in my case it was 3.5-32
image_3

Rename your folder from 3.5-32 to 3.5 and re run the cx_Oracle-5.2.1-12c.win-amd64-py3.5.exe (md5)

Tuesday, February 21, 2017

Simple CRUD operation on MYSQL using Python


To perform CRUD operation make sure you have installed MYSQLdb pacakge in your Python.
Like anyother programing language Python also need below step to perform CRUD on Database.
1-Import required API module for us as the data base is MYSQL we should import MYSQLdb in our Python file.
2- Acquiring connection with the database.
3- Performing SQL statments
4:- Closing the connection
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","siddhu","siddhu","testsiddhu" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query 
cursor.execute("SELECT VERSION()")
# Fetch a single row 
data = cursor.fetchone()
print ("Database version : %s " % data)
# Drop table if it already exist 
cursor.execute("DROP TABLE IF EXISTS SIDDHU_TEST")
# Create table Example
sql = """CREATE TABLE SIDDHU_TEST (
FNAME CHAR(20) NOT NULL,
LNAME CHAR(20),
AGE INT, 
GENDER CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# Inserting in Table Example:- Prepare SQL query to INSERT a record into the database and accept the value dynamic. This is similar to prepare statement which we create.
sql = "INSERT INTO SIDDHU_TEST(FNAME, \
LNAME, AGE, GENDER, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('siddhu', 'dhumale', 24, 'M', 1000)
try:
# Execute command
cursor.execute(sql)
# Commit changes
db.commit()
except:
# Rollback if needed
db.rollback()
# disconnect from server
# Select Query Example :- Selecting data from the table.
sql = "SELECT * FROM SIDDHU_TEST \
WHERE AGE > '%d'" % (4)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
gender = row[3]
income = row[4]
# Now print fetched result
print ("fname=%s,lname=%s,age=%d,gender=%s,income=%d" % (fname, lname, age, gender, income ))
print ("New fname=,lname=,age=,gender=,income=" % (fname, lname, age, gender, income ))
except:
print ("Value Fetch properly")


# Update Exmaple:- Update record 
sql = "UPDATE SIDDHU_TEST SET INCOME = 5000 WHERE GENDER = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback() 

# Delete Operation :- Delete Opearations
sql = "DELETE FROM SIDDHU_TEST WHERE INCOME = '%d'" % (5000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()


db.close()

How to install MYSQLDb for Python 3.6 and MYSQL 5.7.12

At present there are very few options for using Python 3* version with MYSQL
One of such option is to use
https://pypi.python.org/pypi/mysqlclient
- Django's, C based , most compatible and recommended library.
Go to above site and download required .whl file from the site as per your O/S need and run the same using following command
image_4
C:\Software>pip install mysqlclient-1.3.10-cp36-cp36m-win32.whl
Processing c:\software\mysqlclient-1.3.10-cp36-cp36m-win32.whl
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.3.10
Now you can use below import in your files
import MySQLdb

Tuesday, February 14, 2017

How to use PrimeNG in AngularJS2 project

Step 1:- Enter into your project folder
i.e we had project name as AddSubDivMultiProject
Open command prompt and enter into
C:\eclipse_workspace_angularjs2\AddSubDivMultiProject>
run following command
npm install primeng --save
This will install primeng folder inside your project node_modules folder
C:\eclipse_workspace_angularjs2\AddSubDivMultiProject>npm install primeng --save
add-sub-div-multi-project@0.0.0 C:\eclipse_workspace_angularjs2\AddSubDivMultiProject
`-- primeng@2.0.0
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.0.17: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN @ngtools/webpack@1.2.4 requires a peer of webpack@2.2.0 but none was installed.
npm WARN extract-text-webpack-plugin@2.0.0-rc.2 requires a peer of webpack@^2.2.0 but none was installed.
PLEASE CONFIRM YOU GET primeng FOLDER INSIDE YOUR PROEJCT NODE_MODULES FOLDER
Step 2:- Lets say we want to use button of PrimeNg in our project i.e. http://www.primefaces.org/primeng/#/button
import the required module in our project using belwo line. This line need to be written in our app.modules.ts
import {ButtonModule} from 'primeng/primeng';
Also add the same in imports in @NgModule
Step 3:- Add following line in our *.HTML files

<! -- button pButton type="button" class="ui-button-info" label="Click ttt"><!--/button>
Step 4:- Add following line in our styles.css files please at the same level of index.html
/* You can add global styles to this file, and also import other style files */
@import '../node_modules/primeng/resources/primeng.min.css';
@import '../node_modules/primeng/resources/themes/omega/theme.css';

Monday, February 06, 2017

Creating simple AngularJS2 project having topmenu, leftmenu, footer and central part

Lets try to build an website using AngularJS2. Generally in website we had top, left, bottm and central part.
We will try to create the same UI with the help of AngularJS2. In addition in this example we will also try to use some of the external ui component.
There are many ui component available with open source for angularjs2. We will try to use Angular Material 2
https://material.angular.io/
- Angular Material 2
- Fuel-UI
- Kendo UI
- ng-bootstrapng-lightning
- ng2-bootstrap
- Onsen UI
- Prime Faces
- Semantic UI
- Vaadin
We are using Tool Like
1- Eclipse
2- Oracle DB
3- SoapUI for mocking SOAP Service
Step 1:- Create an AngularJS2 project using eclipse
STep 2:- Distribute main pages in to following component
1- Top
2- Bottom
3- Left
4- Cetral
As angularjs2 is component base best way is to have sapare component for each above file. We can create above component using eclipse angularjs2 plugin.
Step 3:- Let create items in our left menu i.e we had created three items
1- Math
2- SOAP & REST web service call
3- CURD
Our intension is when the user click on Math left menu item ..our math screen will be displayed at the central part which contain operation like add, sub, div and multiplication.Similary when the user click on SOAP & REST web service call they will be presented with REST and SOAP w/S call screen at the center.
Step 4:- For REST JSON we are using
http://services.groupkt.com/country/get/all
http://services.groupkt.com/country/get/iso2code/IN
Step 5:- For SOAP we are using SOAPUI tool to mock up our request.
Code:-

1- app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { TopmenuComponent } from './topmenu/topmenu.component';
import { LeftmenuComponent } from './leftmenu/leftmenu.component';
import { FooterComponent } from './footer/footer.component';
import { CentralComponent } from './central/central.component';
import {MaterialModule} from '@angular/material';
import { AppRoutingModule } from './app-routing.module';
import 'hammerjs';
import { CrudcomponentComponent } from './crudcomponent/crudcomponent.component';
import { AddComponentComponent } from './add-component/add-component.component';
import { SubComponentComponent } from './sub-component/sub-component.component';
import { DivComponentComponent } from './div-component/div-component.component';
import { MultiComponentComponent } from './multi-component/multi-component.component';
import { MathcomponentComponent } from './mathcomponent/mathcomponent.component';
import { SiddhuServletService } from './siddhu-servlet.service';
import { SiddhuRestServiceService } from './siddhu-rest-service.service';
import { RestcomponentComponent } from './restcomponent/restcomponent.component';
@NgModule({
declarations: [
AppComponent,
TopmenuComponent,
LeftmenuComponent,
FooterComponent,
CentralComponent,
CrudcomponentComponent,
AddComponentComponent,
SubComponentComponent,
DivComponentComponent,
MultiComponentComponent,
MathcomponentComponent,
RestcomponentComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule.forRoot(),
AppRoutingModule
],
providers: [SiddhuServletService, SiddhuRestServiceService],
bootstrap: [AppComponent]
})
export class AppModule { }
2- app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'AngularJS2 Example showing Top, Left, Footer and Central Part';
}
3- app.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/

4- app.component.css
html, body {
height:100%;
margin:0;
padding:0;
}
.content {
margin-top: 60px;
background: pink;
height: 100%;
width: 500px;
}
5- app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CrudcomponentComponent } from './crudcomponent/crudcomponent.component';
import { AddComponentComponent } from './add-component/add-component.component';
import { SubComponentComponent } from './sub-component/sub-component.component';
import { DivComponentComponent } from './div-component/div-component.component';
import { MultiComponentComponent } from './multi-component/multi-component.component';
import { MathcomponentComponent } from './mathcomponent/mathcomponent.component';
import { RestcomponentComponent } from './restcomponent/restcomponent.component';

const routes: Routes = [
{ path: 'crudcomponent', component: CrudcomponentComponent },
{ path: 'addcomponent', component: AddComponentComponent },
{ path: 'subcomponent', component: SubComponentComponent },
{ path: 'divcomponent', component: DivComponentComponent },
{ path: 'multicomponent', component: MultiComponentComponent },
{ path: 'mathcomponent', component: MathcomponentComponent }, 
{ path: 'restcomponent', component: RestcomponentComponent }

];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
- Top Menu
6- topmenu.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-topmenu',
templateUrl: './topmenu.component.html',
styleUrls: ['./topmenu.component.css'] 
})

export class TopmenuComponent implements OnInit {
constructor() { }
ngOnInit() {}
}

7- topmenu.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/
8- topmenu.component.css
header {
width: 100%;
background: #e6ecff;
position: fixed; 
top: 0;
height: 60px !important;
left:0;
}

- Sub component
9- sub-component.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-sub-component',
templateUrl: './sub-component.component.html',
styleUrls: ['./sub-component.component.css']
})
export class SubComponentComponent implements OnInit {
answer : number;
constructor() { }
ngOnInit() {
}
subNumber(firstnumber, secondnumber) {
console.log(firstnumber)
console.log(secondnumber)
var myFirstNumber = +firstnumber
var mySecondNumner = +secondnumber
this.answer = myFirstNumber - mySecondNumner;
console.log(this.answer)

}
getAnswer()
{
return this.answer;
}
}
10- sub-component.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/
11- sub-component.component.css
h1 {
font-size: 1.2em;
color: #999;
margin-bottom: 0;
}
h2 {
font-size: 2em;
margin-top: 0;
padding-top: 0;
}
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}

- Rest Component
12- restcomponent.component.ts
import { Component, OnInit } from '@angular/core';
import { SiddhuRestServiceService } from './../siddhu-rest-service.service';
@Component({
selector: 'app-restcomponent',
templateUrl: './restcomponent.component.html',
styleUrls: ['./restcomponent.component.css']
})
export class RestcomponentComponent implements OnInit {
getJSONResponse:string;
getCountryCodeJSONResponse:string;
getSoapWebResponse:string;

constructor(private siddhurestservice: SiddhuRestServiceService) { }

ngOnInit() {
}

title = 'Calling REST Web service using AngularJS2';

getAllCountry() {
this.siddhurestservice
.getAllCountry().subscribe(
data => this.getJSONResponse = JSON.stringify(data), // put the data returned from the server in our variable
error => console.log("Error HTTP GET Service"), // in case of failure show this message
() => console.log("Job Done Get !")//run this code in all cases
);
}
getIsoofCountry(id : string) { 
console.log(id);

this.siddhurestservice
.getIsoofCountry(id).subscribe(
data => this.getCountryCodeJSONResponse = JSON.stringify(data), // put the data returned from the server in our variable
error => console.log("Error HTTP GET Service"), // in case of failure show this message
() => console.log("Job Done Get !")//run this code in all cases
);
}
getSoapResponse() {
this.siddhurestservice
.getSoapResponse().subscribe(
data => this.getSoapWebResponse = data, // put the data returned from the server in our variable
error => console.log("Error HTTP GET Service"), // in case of failure show this message
() => console.log("Job Done Get !")//run this code in all cases
);

}
}
13- restcomponent.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/

14- restcomponent.component.css
h1 {
font-size: 1.2em;
color: #999;
margin-bottom: 0;
}
h2 {
font-size: 2em;
margin-top: 0;
padding-top: 0;
}
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}

- multi component
15- multi-component.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-multi-component',
templateUrl: './multi-component.component.html',
styleUrls: ['./multi-component.component.css']
})
export class MultiComponentComponent implements OnInit {
answer : number;
constructor() { }
ngOnInit() {
}
multiNumber(firstnumber, secondnumber) {
console.log(firstnumber)
console.log(secondnumber)
var myFirstNumber = +firstnumber
var mySecondNumner = +secondnumber
this.answer = myFirstNumber * mySecondNumner;
console.log(this.answer)

}
getAnswer()
{
return this.answer;
}
}
16 -multi-component.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/
17- multi-component.component.css
h1 {
font-size: 1.2em;
color: #999;
margin-bottom: 0;
}
h2 {
font-size: 2em;
margin-top: 0;
padding-top: 0;
}
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}

- math component
18- mathcomponent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-mathcomponent',
templateUrl: './mathcomponent.component.html',
styleUrls: ['./mathcomponent.component.css']
})
export class MathcomponentComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}

19- mathcomponent.component.html

<!--nav>
<!--a routerLink="/addcomponent" routerLinkActive="active">Addition<!--/a>
<!--a routerLink="/subcomponent" routerLinkActive="active">Subtraction<!--/a>
<!--a routerLink="/multicomponent" routerLinkActive="active">Multiplication<!--/a>
<!--a routerLink="/divcomponent" routerLinkActive="active">Division<!--/a>
<!--/nav>
<!--h2>Click on above Tab to perform Math Operations !!!<!--/h2>
<!--router-outlet><!--/router-outlet>
20- mathcomponent.component.css
h1 {
font-size: 1.2em;
color: #999;
margin-bottom: 0;
}
h2 {
font-size: 2em;
margin-top: 0;
padding-top: 0;
}
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}

- left menu
21 - leftmenu.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-leftmenu',
templateUrl: './leftmenu.component.html',
styleUrls: ['./leftmenu.component.css']
})
export class LeftmenuComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
22- leftmenu.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/
23- leftmenu.component.css
.sidebar1 {
background: #809fff;
width: 246px;
height: 100%;
top: 60px;
position:fixed;
}
.sidebar1 {
left:0;
}

.example-container {
width: 500px;
}
.example-button-row {
display: flex;
align-items: center;
justify-content: space-around;
}

- Footer
24- footer.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}

25- footer.component.html
<!--footer>
<!--p>
footer works!
<!--/p>
<!--/footer>
26- footer.component.css
footer {
width: 100%;
background: #ff1a1a;
position: fixed; 
bottom: 0;
height: 30px;
left:0;
}
- div-component
27- div-component.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-div-component',
templateUrl: './div-component.component.html',
styleUrls: ['./div-component.component.css']
})
export class DivComponentComponent implements OnInit {
answer : number;
constructor() { }
ngOnInit() {
}
divideNumber(firstnumber, secondnumber) {
console.log(firstnumber)
console.log(secondnumber)
var myFirstNumber = +firstnumber
var mySecondNumner = +secondnumber
this.answer = myFirstNumber / mySecondNumner;
console.log(this.answer)

}
getAnswer()
{
return this.answer;
}
}
28- div-component.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/
29- div-component.component.css
h1 {
font-size: 1.2em;
color: #999;
margin-bottom: 0;
}
h2 {
font-size: 2em;
margin-top: 0;
padding-top: 0;
}
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}
-Crud Component
30- crudcomponent.component.ts

import { Component, OnInit } from '@angular/core';
import { SiddhuServletService } from './../siddhu-servlet.service';

@Component({
selector: 'app-crudcomponent',
templateUrl: './crudcomponent.component.html',
styleUrls: ['./crudcomponent.component.css']
})
export class CrudcomponentComponent implements OnInit {
title = 'Performing CRUd Opeartion using Servlet in AngularJS2';

getServletAddResponse:string;
getServletDeleteResponse:string;
getServletUpdateResponse:string;
getServletGetResponse:string;


constructor(private siddhuservletservice: SiddhuServletService) { }
ngOnInit() {
}

addProduct(method:string, name:string, qty:string) {
console.log('updateUser-'+method);
console.log('deleteUser-'+name);
console.log('deleteUser-'+qty);

this.siddhuservletservice
.addProduct(method, name, qty).subscribe(
data => this.getServletAddResponse = data, // put the data returned from the server in our variable
error => console.log("Error HTTP GET Service"), // in case of failure show this message
() => console.log("Add Job Done Get !")//run this code in all cases
);
}



deleteProduct(method:string, name:string, qty:string) {
console.log('updateUser-'+method);
console.log('deleteUser-'+name);
console.log('deleteUser-'+qty);

this.siddhuservletservice
.deleteProduct(method, name).subscribe(
data => this.getServletDeleteResponse = data, // put the data returned from the server in our variable
error => console.log("Error HTTP GET Service"), // in case of failure show this message
() => console.log("Delete Job Done Get !")//run this code in all cases
);
}


updateProduct(method:string, name:string, qty:string) {
console.log('updateUser-'+method);
console.log('updateUser-'+name);
console.log('updateUser-'+qty); 

this.siddhuservletservice
.updateProduct(method, name,qty).subscribe(
data => this.getServletUpdateResponse = data, // put the data returned from the server in our variable
error => console.log("Error HTTP GET Service"), // in case of failure show this message
() => console.log("Update Job Done Get !")//run this code in all cases
);
}


getProduct(method:string, name:string) {
console.log('updateUser-'+method);
console.log('deleteUser-'+name);

this.siddhuservletservice
.getProduct(method, name).subscribe(
data => this.getServletGetResponse = data, // put the data returned from the server in our variable
error => console.log("Error HTTP GET Service"), // in case of failure show this message
() => console.log("Get Job Done Get !")//run this code in all cases
);
}
}

31- crudcomponent.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/
32- crudcomponent.component.css

h1 {
font-size: 1.2em;
color: #999;
margin-bottom: 0;
}
h2 {
font-size: 2em;
margin-top: 0;
padding-top: 0;
}
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}

- Central

33- central.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-central',
templateUrl: './central.component.html',
styleUrls: ['./central.component.css']
})
export class CentralComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
34- central.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/

35- central.component.css

#scrollable2 {
background:#f1f1f1;
height: 100%;
min-width: 300px;
margin-left: 47%;
margin-right: 100px;
width:100%;
}
- add-component
36- add-component.component.ts
import { Component, OnInit } from '@angular/core';
//import { NumberEnter } from './number-enter';
@Component({
selector: 'app-add-component',
templateUrl: './add-component.component.html',
styleUrls: ['./add-component.component.css']
})
export class AddComponentComponent implements OnInit {

answer : number;
constructor() { }
ngOnInit() {
}

addNumber(firstnumber, secondnumber) {
console.log(firstnumber)
console.log(secondnumber)
var myFirstNumber = +firstnumber
var mySecondNumner = +secondnumber
this.answer = myFirstNumber + mySecondNumner;
console.log(this.answer)

}
getAnswer()
{
return this.answer;
}

}

37- add-component.component.html
For code refer to this site
https://shdhumale.wordpress.com/2017/02/06/creating-simple-angularjs2-project-having-topmenu-leftmenu-footer-and-central-part/
38- add-component.component.css
h1 {
font-size: 1.2em;
color: #999;
margin-bottom: 0;
}
h2 {
font-size: 2em;
margin-top: 0;
padding-top: 0;
}
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}
39- siddhu-servlet.service.ts

import { Injectable } from '@angular/core';
import {Http, Response, Headers, Request, RequestOptions, RequestMethod, URLSearchParams} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';

@Injectable()
export class SiddhuServletService {


private getServletUrl = 'http://localhost:8181/CRUDUsingAngularJS/AngularJSServlet'; // URL to web api



constructor(private _http: Http) { 

}

//To Add User in the database.
addProduct(method: string, name: string, qty: string){

let params: URLSearchParams = new URLSearchParams();
params.set('method', method);
params.set('name', name);
params.set('qty', qty);


//const url = `${this.getServletUrl}/${id}`; 

return this._http.get(this.getServletUrl, {
search: params
})
.map(response => response.text());
}


//To Delete in the database.
deleteProduct(method: string, name: string){
// const deleteServlerURL = `${this.getServletUrl}/${name}`;
let params: URLSearchParams = new URLSearchParams();
params.set('method', method);
params.set('name', name);

return this._http.get(this.getServletUrl, {
search: params
})
.map(response => response.text());
}

//To Update in the database.
updateProduct(method: string, name: string,qty: string){
let params: URLSearchParams = new URLSearchParams();
params.set('method', method);
params.set('name', name);
params.set('qty', qty);
return this._http.get(this.getServletUrl, {
search: params
})
.map(response => response.text());
}


//To getUser from id from the database.
getProduct(method: string, name: string){
//const getUserServlerURL = `${this.getServletUrl}/${name}`; 
let params: URLSearchParams = new URLSearchParams();
params.set('method', method);
params.set('name', name);
return this._http.get(this.getServletUrl, {
search: params
})
.map(response => response.text());
}


}

40- siddhu-rest-service.service.ts
import { Injectable } from '@angular/core';
import {Http, Response, Headers, Request, RequestOptions, RequestMethod, URLSearchParams} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';
@Injectable()
export class SiddhuRestServiceService {

private headers = new Headers({'Content-Type': 'application/json'});
private getAllUrl = 'http://services.groupkt.com/country/get/all'; // URL to web api

private getISOCode = 'http://services.groupkt.com/country/get/iso2code'; 

private getSoapResponseurl = 'http://10.38.113.148:8088/mockExposeWebServiceSoap11Binding';

private body: 
string = `<!--soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:main="http://main.siddhu.com">
<!--soapenv:Header/>
<!--soapenv:Body>
<!--main:getKPI>
<!--main:sprintId>1<!--/main:sprintId>
<!--/main:getKPI>
<!--/soapenv:Body>
<!--/soapenv:Envelope>`;

constructor(private _http: Http) { 

}

// getAllCountry(): Promise<{}> {
getAllCountry(){
/* console.log(this._http.get(this.getAllUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError));*/
// .map(response => response.json()));
/* return this._http.get(this.getAllUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);*/
return this._http.get(this.getAllUrl)
.map(response => response.json());

}

// getIsoofCountry(id: string): Promise<{}> {
getIsoofCountry(id: string) {
const url = `${this.getISOCode}/${id}`;
/* console.log(this._http.get(url)
.toPromise()
.then(response => response.json())
.catch(this.handleError));*/
/*return this._http.get(url)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);*/
return this._http.get(url)
.map(response => response.json());

}

/* getSoapResponse(){
return this._http.get(this.getSoapResponseurl)
.map(response => response);
return this._http.get(this.getSoapResponseurl).map(res => {
let xmlresult = res.text();
console.log(xmlresult);
console.log(res.text());
return xmlresult;
});

}*/

getSoapResponse(){
let options = new RequestOptions({
method: RequestMethod.Post,
url: this.getSoapResponseurl,
body: this.body
});
return this._http.request(new Request(options))
.map(this.extractData);


}

private extractData(res: Response) {
let body = res.text();
console.log(res.toString());
console.log(body);
return body;
}


private handleError(error: any) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}

//using promise
/*
* getHeroes(): Promise {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}


getHero(id: number): Promise {
const url = `${this.heroesUrl}/${id}`;
return this.http.get(url)
.toPromise()
.then(response => response.json().data as Hero)
.catch(this.handleError);
}
*/

}
For proper ui we had used AngularJS Material design in only one screen of add functionality
Screen shot:-
image1image2image3image4image5image6image7image8image9