COPA2ndsemTT English
COPA2ndsemTT English
PROGRAMMING ASSISTANT
NSQF LEVEL - 4
2nd Semester
TRADE THEORY
NATIONAL INSTRUCTIONAL
MEDIA INSTITUTE, CHENNAI
Post Box No. 3142, CTI Campus, Guindy, Chennai - 600 032
(i)
Copyright @ NIMI Not to be Republished
Sector : IT & ITES
Duration : 1 - Year
Trade : Computer Operator and Programming Assistant 2nd Semester - Trade Theory -
NSQF Level 4
Rs. 245/-
No part of this publication can be reproduced or transmitted in any form or by any means, electronic or mechanical, including
photocopy, recording or any information storage and retrieval system, without permission in writing from the National
Instructional Media Institute, Chennai.
Published by:
NATIONAL INSTRUCTIONAL MEDIA INSTITUTE
P. B. No.3142, CTI Campus, Guindy Industrial Estate,
Guindy, Chennai - 600 032.
Phone : 044 - 2250 0248, 2250 0657, 2250 2421
Fax : 91 - 44 - 2250 0791
email : chennai-nimi@nic.in, nimi_bsnl@dataone.in
Website: www.nimi.gov.in
(ii)
Copyright @ NIMI Not to be Republished
FOREWORD
The Government of India has set an ambitious target of imparting skills to 30 crores people, one out of every
four Indians, by 2020 to help them secure jobs as part of the National Skills Development Policy. Industrial
Training Institutes (ITIs) play a vital role in this process especially in terms of providing skilled manpower.
Keeping this in mind, and for providing the current industry relevant skill training to Trainees, ITI syllabus
has been recently updated with the help of Mentor Councils comprising various stakeholder's viz. Industries,
Entrepreneurs, Academicians and representatives from ITIs.
The National Instructional Media Institute (NIMI), Chennai, has now come up with instructional material to
suit the revised curriculum for Computer Operator and Programming Assistant Trade Theory 2nd
Semester in IT & ITES Sector . The NSQF Level - 4 Trade Theory will help the trainees to get an international
equivalency standard where their skill proficiency and competency will be duly recognized across the globe
and this will also increase the scope of recognition of prior learning. NSQF Level - 4 trainees will also get
the opportunities to promote life long learning and skill development. I have no doubt that with
NSQF Level - 4 the trainers and trainees of ITIs, and all stakeholders will derive maximum benefits from
these IMPs and that NIMI's effort will go a long way in improving the quality of Vocational training in the
country.
The Executive Director & Staff of NIMI and members of Media Development Committee deserve appreciation
for their contribution in bringing out this publication.
Jai Hind
RAJESH AGGARWAL
Director General/ Addl. Secretary
Ministry of Skill Development & Entrepreneurship,
Government of India.
(iii)
Copyright @ NIMI Not to be Republished
PREFACE
The National Instructional Media Institute (NIMI) was established in 1986 at Chennai by then Directorate
General of Employment and Training (D.G.E & T), Ministry of Labour and Employment, (now under Directorate
General of Training, Ministry of Skill Development and Entrepreneurship) Government of India, with technical
assistance from the Govt. of the Federal Republic of Germany. The prime objective of this institute is to
develop and provide instructional materials for various trades as per the prescribed syllabi (NSQF Level 4)
under the Craftsman and Apprenticeship Training Schemes.
The instructional materials are created keeping in mind, the main objective of Vocational Training under
NCVT/NAC in India, which is to help an individual to master skills to do a job. The instructional materials are
generated in the form of Instructional Media Packages (IMPs). An IMP consists of Theory book, Practical
book, Test and Assignment book, Instructor Guide, Audio Visual Aid (Wall charts and Transparencies) and
other support materials.
The trade practical book consists of series of exercises to be completed by the trainees in the workshop.
These exercises are designed to ensure that all the skills in the prescribed syllabus are covered. The trade
theory book provides related theoretical knowledge required to enable the trainee to do a job. The test and
assignments will enable the instructor to give assignments for the evaluation of the performance of a trainee.
The wall charts and transparencies are unique, as they not only help the instructor to effectively present a
topic but also help him to assess the trainee's understanding. The instructor guide enables the instructor to
plan his schedule of instruction, plan the raw material requirements, day to day lessons and demonstrations.
IMPs also deals with the complex skills required to be developed for effective team work. Necessary care
has also been taken to include important skill areas of allied trades as prescribed in the syllabus.
The availability of a complete Instructional Media Package in an institute helps both the trainer and
management to impart effective training.
The IMPs are the outcome of collective efforts of the staff members of NIMI and the members of the Media
Development Committees specially drawn from Public and Private sector industries, various training institutes
under the Directorate General of Training (DGT), Government and Private ITIs.
NIMI would like to take this opportunity to convey sincere thanks to the Directors of Employment & Training
of various State Governments, Training Departments of Industries both in the Public and Private sectors,
Officers of DGT and DGT field institutes, proof readers, individual media developers and coordinators, but for
whose active support NIMI would not have been able to bring out this materials.
R. P. DHINGRA
Chennai - 600 032 EXECUTIVE DIRECTOR
(iv)
Copyright @ NIMI Not to be Republished
ACKNOWLEDGEMENT
National Instructional Media Institute (NIMI) sincerely acknowledges with thanks for the co-operation and
contribution extended by the following Media Developers and their sponsoring organisations to bring out this
Instructional Material (Trade Theory) for the trade of Computer Operator and Programming Assistant under
the IT & ITES Sector
NIMI records its appreciation for the Data Entry, CAD, DTP operators for their excellent and devoted services in
the process of development of this Instructional Material.
NIMI also acknowledges with thanks the invaluable efforts rendered by all other NIMI staff who have contributed
towards the development of this Instructional Material.
NIMI is also grateful to everyone who has directly or indirectly helped in developing this Instructional Material.
(v)
Copyright @ NIMI Not to be Republished
INTRODUCTION
TRADE THEORY
The manual of trade theory consists of theorectical information for the Second Semester course of the COPA
Trade. The contents are sequenced according to the practical exercise contained in the manual on Trade
practical. Attempt has been made to relate the theortical aspects with the skill covered in each exercise to the
extent possible. This co-relation is maintained to help the trainees to develop the perceptional capabilities for
performing the skills.
The Trade Theory has to be taught and learnt along with the corresponding exercise contained in the manual
on trade practical. The indicating about the corresponding practical exercise are given in every sheet of this
manual.
It will be preferable to teach/learn the trade theory connected to each exercise atleast one class before
performing the related skills in the system lab. The trade theory is to be treated as an integrated part of each
exercise.
The material is not the purpose of self learning and should be considered as supplementary to class room
instruction.
TRADE PRACTICAL
The trade practical manual is intented to be used in workshop . It consists of a series of practical exercies to
be completed by the trainees during the Second Semester course of the COPA trade supplemented and
supported by instructions/ informations to assist in performing the exercises. These exercises are designed
to ensure that all the skills in the prescribed syllabus are covered.
The manual is divided into five modules to maintain completancy of learning process in a stipulated time basis.
The skill training in the computer lab is planned through a series of practical exercises centred around some
practical project. However, there are few instance where the individual exercise does not form a part of project.
While developing the practical manual a sincere effort was made to prepare each exercise which will be easy
to understand and carry out even by below average traninee. However the development team accept that there
if a scope for further improvement. NIMI, looks forward to the suggestions from the experienced training faculty
for improving the manual.
(vi)
Copyright @ NIMI Not to be Republished
CONTENTS
(vii)
Copyright @ NIMI Not to be Republished
Lesson No. Title of the Lesson Page No.
(viii)
Copyright @ NIMI Not to be Republished
Lesson No. Title of the Lesson Page No.
Module 4 : E Commerce
(ix)
Copyright @ NIMI Not to be Republished
SECOND SEMESTER – 06 Months
Industrial Visit/Project work (1. Create and host a web site of atleast 6 web pages using
48 - 49 JavaScript containing interactive objects, functions etc. OR
2. Create a project with Excel & VBA on Payroll Systems. OR
3. Create a company in Tally and post vouchers in it for a financial period. Vouchers should
contain purchase, sales with VAT, contra, payment , receipts, cost centre cost category etc.)
50-51 Revision
52 Examination
Understanding JavaScript
Objectives : At the end of this lesson you shall be able to
• define programming and scripting languages
• know what is JavaScript and history of Java Script
• explain how to run JavaScript
• list out tools you need to run JavaScript
• view sample JavaScript Program
• know features of JavaScript
• describe advantages and disadvantages of JavaScript
• explain JavaScript Versions.
Introduction to programming and scripting languages words, you can make your webpage more lively and
interactive, with the help of JavaScript. JavaScript is also
Computer programming is the process of writing being used widely in game development and Mobile
instructions that get executed by computers. The application development.
instructions, also known as code, are written in a
programming language which the computer can Fig 1
understand and use to perform a task or solve a problem.
1
Copyright @ NIMI Not to be Republished
Tools You Need to run JavaScript • It is object based language as it provides predefined
objects.
To start with, a text editor to write the code and a browser
• Every statement in JavaScript must be terminated with
to display the web pages. A text editor uses of choice
semicolon (;).
including Notepad++, Visual Studio Code, Sublime Text,
Atom or any other text editor is comfortable with. And • Most of the JavaScript control statements syntax is
also, can use any web browser including Google Chrome, same as syntax of control statements in C language.
Firefox, Microsoft Edge, Internet Explorer etc.
• An important part of JavaScript is the ability to create
new functions within scripts.
Sample JavaScript program
Advantages of JavaScript
<html>
<head> • Executed on the client side: For example, user can
validate any user input before sending a request to the
<title>My First JavaScript code!!!</title>
server. This makes less load on the server.
<script type=”text/javascript”>
• Relatively an easy language: This is quite easy to learn
alert(“Welcome to JavaScript Program!”); and the syntax that is close to English.
</script> • Instance response to the visitors: Without any server
interaction, don’t have to wait for a page reload to get
</head>
the desire result.
<body>
• Fast to the end user: As the script is executed on the
</body> user’s computer, depending on task, the results are
</html> completed almost instantly.
• Interactivity increased: Creating interfaces that can react
Features of JavaScript when the user hovers over them or activates them using
the keyboard.
JavaScript is a client side technology, it is mainly used for
client side validation, but it has lot of features which are • Rich interfaces: Drag and drop components or slider
shown in Fig 2. may give a rich interface to site visitors.
Disadvantages of JavaScript
Fig 2
Object‐based scripting language • Security issues: Any JavaScript snippets, while
appended onto web pages on client side immediately
Scripting language Client side technology can also be used for exploiting the user’s system.
• Doesn’t have any multiprocessor or multi threading
capabilities.
Interpreter based
Control Statements
JavaScript • As no supports are available, JavaScript cannot be used
Basics
Case sensitive for any networking applications.
Looping Statements
• JavaScript does not allow us to read or write files.
Event handling
• JavaScript render varies: JavaScript may be rendered
Validating user Input by different layout engines differently. As a result, this
causes inconsistency in terms of interface and
Built‐in functions
functionality.
• It gives the user more control over the browser. JavaScript was invented by Brendan Eich in 1995, and
• It Handles dates and time. became an ECMA standard in 1997. ECMA Script is the
official name of the language.
• It detects the user’s browser and OS,
• It is light weighted. From 2015 ECMA Script is named by year (ECMA
Script 2015).
• It is a scripting language and it is not java.
• It is interpreter based scripting language.
• It is case sensitive.
2 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.94
Copyright @ NIMI Not to be Republished
ECMA Script Editions
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.94 3
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.95
COPA - JavaScript and creating Web page
Fig 1
Browser connects to a
Server and requests a Page
4
Copyright @ NIMI Not to be Republished
Fig 4 Now we can import the file in HTML file as follows:-
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.95 5
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.96A
COPA - JavaScript and creating Web page
• c stores the value 22 JavaScript variables can hold numbers like 100 and text
values like “Santhosh kumar”.
In example 2, mark1, mark2, and total, are variables:
In programming, text values are called text strings. Java
Example 2 Script can handle many types of data, but for now, just
think of numbers and strings.Strings are written inside
var mark1 = 85; double or single quotes. Numbers are written without
var mark2 = 66; quotes. If you put a number in quotes, it will be treated as
var total = marks1 + mark2; a text string.
The general rules for constructing names for variables are: var traineeName;
After the declaration, the variable has no value. Technically
• Names can contain letters, digits, underscores, and
it has the value of undefined. To assign a value to the
dollar signs.
variable, use the equal signs.
• Names must begin with a letter
traineeName = “Santhosh Kumar”;
• Names can also begin with $ and _
You can also assign a value to the variable when you
• Names are case sensitive (a and A are different
declare it.
variables)
var traineeName = “Santhosh Kumar”;
6
Copyright @ NIMI Not to be Republished
In the example below, we create a variable called Example 7
traineeName and assign the value “Santhosh Kumar” to
it. var x = 8 + 2 + 5;
Then we “output” the value inside an HTML paragraph with Now x has the value 15.
id=”demo”:
You can also add strings, but strings will be concatenated:
<p id =“demo”></p>
<script> Example 8
You can declare many variables in one statement. Start Note: If you put a number in quotes, the rest of
the statement with var and separate the variables by the numbers will be treated as strings, and
comma. concatenated.
var traineeName = “santhoshkumar”; JavaScript will treat the example above as,
var traineeName;
var a = “10” + “Apple”;
JavaScript Arithmetic
The output is 10 Apple
Do the arithmetic with JavaScript variables, using operators
like = and + Note: When adding a number and a string,
JavaScript will treat the number as a string.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96A 7
Copyright @ NIMI Not to be Republished
JavaScript evaluates expressions from left to right. Different Example 18
sequences can produce different results.
var num1 = 87.0; // Written with decimals
Example 13
var num2 = 87; // Written without decimals
var y = 20 + 5 + “Apple”;
Extra large or extra small numbers can be written with
The result is 25Apple scientific (exponential) notation:
Example 14 Example 19
Example 15
Note : Booleans are often used in conditional
testing.
var z; // Now z is undefined
z = 10; // Now z is a Number JavaScript Arrays
z = “Sakthi”; // Now z is a String
JavaScript arrays are written with square brackets. Array
items are separated by commas. The following code
JavaScript Strings
declares (creates) an array called bikes, containing three
A string or a text string is a series of characters like “Harini items (bike names):
Kumar”. Strings are written with quotes. You can use single
Example 21
or double quotes.
var bikes = [“Yamaha”, “TVS”, “Royal Enfield”];
Example 16
Note: Array indexes are zero-based, which
var bikeName = “Yamaha R15”; // Using double quotes
means the first item is [0], second is [1], and so
var bikeName = ‘ Yamaha R15’; // Using single quotes on.
You can use quotes inside a string, as long as they don’t JavaScript Objects
match the quotes surrounding the string:
JavaScript objects are written with curly braces. Object
Example 17 properties are written as name:value pairs, separated by
commas.
var answer = “It’s OK”; // Single quote inside
double quotes Example 22
var answer = ‘Patel is called // Double quotes inside
var personName
= {firstName:”Harini”,lastName:
“Iron Man”’; single quotes
”Kumar”, age:13,height.
”155 cms”};
JavaScript Numbers
The object (personName) in the example 22 above has 4
JavaScript has only one type of numbers. Numbers can properties: firstName, lastName, age and height.
be written with or without decimals.
The typeof Operator
8 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96A
Copyright @ NIMI Not to be Republished
The typeof operator returns the type of a variable or an Difference Between Undefined and Null
expression.
Undefined and null are equal in value but different in type.
Example 23
Example 28
typeof “” // Returns “string”
typeof undefined // undefined
typeof “Rithika” // Returns “string”
typeof null // object
typeof “Harini Kumar” // Returns “string”
null === undefined // false
typeof0 // Returns “number”
null == undefined // true
typeof81 // Returns “number”
typeof8.14 // Returns “number” Primitive Data
typeof(3+2) // Returns “number”
A primitive data value is a single simple data value with no
additional properties and methods. The typeof operator
Undefined
can return one of these primitive types.
In JavaScript, a variable without a value, has the value • string
undefined. The typeof is also undefined.
• number
Example 24
• boolean
var bike; // Value is undefined, type is
• undefined
undefined
Example 29
Note : Any variable can be emptied, by setting
the value to undefined. The type will also be typeof “Rajesh” // Returns “string”
undefined.
typeof 1.44 // Returns “number”
Empty Values typeof true // Returns “boolean”
An empty value has nothing to do with undefined. An typeof false // Returns “boolean”
empty string has both a legal value and a type. typeof a // if a has no value, it returns
Example 25 “undefined”
var bike = “”; // The value is “”, the typeof Complex Data
is “string”
The typeof operator can return one of two complex types:
Null
• function·
In JavaScript null is “nothing”. It is supposed to be
something that doesn’t exist. In JavaScript, the data type • object
of null is an object. You can empty an object by setting it
to null. The type of operator returns object for both objects, arrays
and null. It does not return object for functions.
Example 26
Example 30
var personName = {firstName:”Harini”,last Name;
”Kumar”, age:13, height:”155 cms”}; typeof {name, ‘Karthik’, age 27} // Returns “object”
personName = null; //Now value in null, but typeof [10, 20, 30, 40, 50] // Returns “object”
type is still an object (not “array”, see
You can also empty an object by setting it to undefined: note below)
typeof null // Returns “object”
Example 27
typeof function sampleFunc() { } // Returns “function”
var personName = {firstName:”Harini”, lastName:
”Kumar”, age:13, height:”155 cms”}; Note: The typeof operator returns “object” for
arrays because in JavaScript arrays are
personName = undefined; // Now both value and objects.
type is undefined.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96A 9
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.96B
COPA - JavaScript and creating Web page
The syntax to create a Constant is. But you can NOT reassign a constant object.
In the above syntax, “const” is the special keyword, const bike = {type:”Yamaha”, model:”R15", color:”blue”};
reserved to define a constant. As you can see, this syntax
looks a lot like a variable declaration but with the var bike = {type:”Tvs”, model:”Star city”, color:”black”};
keyword replaced with “const”. Most programmers use all
caps for the name of the constants to differentiate them // ERROR
from variables. Constant Arrays can Change
10
Copyright @ NIMI Not to be Republished
Additive Operators: The term additive operators include Example10
both addition (+) and subtraction( -) as subtraction is also
addition with a negative number. Operation Result Same as Result
Example 7 5&1 1 0101 & 0001 0001
Sometimes JavaScript addition can results in unexpected 5^1 4 0101 ^ 0001 0100
results. 5 >> 1 2 0101 >> 1 0010
Example 8 5 >>> 1 2 0101 >>> 1 0010
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96B 11
Copyright @ NIMI Not to be Republished
The less than operator checks whether the first value is and q=a++; is equivalent to
less than second value and if valid, it returns false. In the
above example, 5 is not less than 2, so it is not true and q=a;
code inside the if block will not execute. a=a+1;
The other three operator are in the same way do checking
The delete Operator
for greater then (>),Greater than or equal to(>=), Less than
or equal to (<=). The delete operator can be used to delete properties from
objects.
in operator checks whether a given index is contained
within an object. For example: Example 13
var MyObj= {star:"Algol", constellation: "Perseus"}; var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
if("star" in MyObj) {
delete person.age;
// do something
The delete operator is designed to be used on object
}
properties. It has no effect on variables or functions.
As star is a index the code will work. but in operator do The delete operator should not be used on predefined Java
not work on numeric types as it works for numbers only. Script object properties. It can crash your application.
Instanceof Operator checks whether an object instance
The Unary + Operator
or object variable of is an instance of a particular object.
The unary + operator can be used to convert a variable to
Example 11
a number.
var mydate=new Date(); Example 14
if(mydate instanceof Date) {
var y = "5"; // y is a string
//do something var x = + y; // x is a number
}
If the variable cannot be converted, it will still become a
number, but with the value NaN (Not a number):
Here mydate is an instance of built-in Date object. So the
code will be executed within the if block. Example 15
Unary Operator
var y = "John"; // y is a string
delete, void, typeof, ++, --, + , -, ~ , ! are unary operators
var x = + y; // x is a number (NaN)
in Javascript.
In the same way Unary - Operator also operates.
Example 12
Ternary or Conditional Operator: It can be used as
a = -10;
compact if else.
p=++a; Example 16
q=a++;
a = (b>5 ? 4:7); means
s=+p;
if(b>5)
There are pre and post increment and decrement operator.
a=4;
p=++a; is equivalent to
else
a=a+1; a=7;
p=a;
12 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96B
Copyright @ NIMI Not to be Republished
Assignment Operator: a = q; means value of q is assigned into a variable deleting
the previous value of a.
Assignment Operator is used to assign values into a
variable. Apart from = there are compound assignment Now a* = 3; is equivalent to a = a*3; and like that all other
operators as follows- compound assignment operator behaves.
*= /= %=
+= -= <<=
^= |=
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96B 13
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.97A & 2.1.97B
COPA - JavaScript and creating Web page
Control Statements: When we write code for a particular block of code to be executed if the condition is false
program, we sometimes takes various decisions for
}
executing different action. These can be done through
conditional/control statements. Example 2
In JavaScript we have the following conditional statements:
If the time is less than 18:00, create a "Good day" greeting,
otherwise "Good evening":
Use if to specify a block of code to be executed, if a
specified condition is true if (time < 18) {
greeting = "Good day";
Use else to specify a block of code to be executed, if the
same condition is false } else {
greeting = "Good evening";
Use else if to specify a new condition to test, if the first
condition is false }
The result of greeting will be:
Use switch to specify many alternative blocks of code to
be executed. Good day
Use the if statement to specify a block of JavaScript code Use the else if statement to specify a new condition if the
to be executed if a condition is true. first condition is false.
Syntax Syntax
If (condition) { if (condition1) {
block of code to be executed if the condition is true block of code to be executed if condition1 is true
} } else if (condition2) {
block of code to be executed if the condition1 is false
Example 1
and condition2 is true
Make a "Good day" greeting if the time is less than 18:00: } else {
if (time < 18) { block of code to be executed if the condition1 is false
and condition2 is false
greeting = "Good day";
}
}
The result of greeting will be: Example 3
Good day
If time is less than 10:00, create a "Good morning"
greeting, if not, but time is less than 18:00, create a "Good
The else Statement
day" greeting, otherwise a "Good evening":
Use the else statement to specify a block of code to be
if (time < 10) {
executed if the condition is false.
greeting = "Good morning";
if (condition) {
} else if (time < 18) {
block of code to be executed if the condition is true
greeting = "Good day";
} else {
} else {
14
Copyright @ NIMI Not to be Republished
greeting = "Good evening"; case 4:
} day = "Thursday";
The result of x will be: break;
Good day case 5:
day = "Friday";
The JavaScript Switch Statement
break;
Use the switch statement to select one of many blocks of
case 6:
code to be executed.
day = "Saturday";
Syntax
break;
switch(expression) {
}
case n1:
The result of day will be:
code block
Tuesday
break;
case n2: The break Keyword
code block
When the JavaScript code interpreter reaches a break
break; keyword, it breaks out of the switch block.
default: This will stop the execution of more execution of code
and/or case testing inside the block.
default code block
} The default Keyword
This is how it works: The default keyword specifies the code to run if there is no
case match:
• The switch expression is evaluated once.
Example 5
• The value of the expression is compared with the values
of each case.
If today is neither Saturday nor Sunday, write a default
• If there is a match, the associated block of code is message:
executed.
switch (new Date().getDay()) {
Example 4
case 6:
Use today's weekday number to calculate weekday name: text = "Today is Saturday";
(Sunday=0, Monday=1, Tuesday=2, ...)
break;
switch (new Date().getDay()) {
case 0:
case 0:
text = "Today is Sunday";
day = "Sunday";
break;
break;
default:
case 1:
text = "Looking forward to the Weekend";
day = "Monday";
}
break;
The result of text will be:
case 2:
Looking forward to the Weekend
day = "Tuesday";
Common Code and Fall-Through
break;
case 3: Sometimes, in a switch block, you will want different cases
to use the same code, or fall-through to a common default.
day = "Wednesday";
Note from the next example, that cases can share the
break;
same code block and that the default case does not have
to be the last case in a switch block:
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B 15
Copyright @ NIMI Not to be Republished
Example 6 The For Loop
switch (new Date().getDay()) { The for loop is often the tool you will use when you want to
create a loop.
case 1:
case 2: The for loop has the following syntax:
case 3:
for (statement 1; statement 2; statement 3) {
default:
code block to be executed
text = "Weekend is coming";
break; }
case 4:
Statement 1 is executed before the loop (the code block)
case 5: starts. It is called Initialisation Part
text = "Weekend is soon";
Statement 2 defines the condition for running the loop (the
break; code block).It is called condition part.
case 0:
Statement 3 is executed each time after the loop (the
case 6: code block) has been executed. It is called increment/
decrement part.
text = "Now in Weekend";
} Example 7
Loops are handy, if you want to run the same code over text += "The number is " + i + "<br>";
and over again, each time with a different value.
}
Often this is the case when working with arrays:
Instead of writing: From the example above, you can read:
text += train[0] + "<br>"; Statement 1 sets a variable before the loop starts
text += train [1] + "<br>"; (var i = 0).
text += train [2] + "<br>"; Statement 2 defines the condition for the loop to run
text += train [3] + "<br>"; (i must be less than 5).
text += train [4] + "<br>"; Statement 3 increases a value (i++) each time the code
text += train [5] + "<br>"; block in the loop has been executed.
You can write:
Initialisation Part
for (i = 0; i < train.length; i++) {
Normally you will use statement 1 to initiate the variable
text += train [i] + "<br>";
used in the loop (var i = 0).
} This is not always the case, JavaScript doesn't care.
Statement 1 is optional.
Different Kinds of Loops
You can initiate many values in statement 1 (separated
JavaScript supports different kinds of loops:
by comma):
• for - loops through a block of code a number of times
Example 8
• for/in - loops through the properties of an object
for (i = 0, len = train.length, text = ""; i < len; i++) {
• while - loops through a block of code while a specified
condition is true
text += train [i] + "<br>";
• do/while - also loops through a block of code while a
specified condition is true }
And you can omit statement 1 (like when your values are
set before the loop starts):
16 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B
Copyright @ NIMI Not to be Republished
Example 9 text += person[x];
}
var i = 2;
var len = train.length; While Loop
var text = "";
The while loop loops through a block of code as long as a
for (; i < len; i++) { specified condition is true.
text += train [i] + "<br>"; Syntax
} while (condition) {
code block to be executed
Condition Part
}
Often statement 2 is used to evaluate the condition of the
initial variable. In the following example, the code in the loop will run, over
and over again, as long as a variable (i) is less than 10:
This is not always the case, JavaScript doesn't care.
Statement 2 is also optional. Example 11
If statement 2 returns true, the loop will start over again, if while (i < 10) {
it returns false, the loop will end.
text += "The number is " + i;
If you omit statement 2, you must provide a break inside i++;
the loop. Otherwise the loop will never end. This will crash
}
your browser. Read about breaks in a later chapter of this
tutorial. If you forget to increase the variable used in the condition,
the loop will never end. This will crash your browser.
Increment/Decrement Part
The Do/While Loop
Often statement 3 increases the initial variable.
The do/while loop is a variant of the while loop. This loop
This is not always the case, JavaScript doesn't care, and
will execute the code block once, before checking if the
statement 3 is optional.
condition is true, then it will repeat the loop as long as the
condition is true.
Statement 3 can do anything like negative increment (i--),
or larger increment (i = i + 15), or anything else. Syntax
train = ["Duronto","Satabdi","Garib Rath","Rajdhani"]; An alert box is often used if you want to make sure
information comes through to the user. When an alert box
var i = 0;
pops up, the user will have to click “OK” to proceed.
var text = "";
Syntax
for (;train[i];) {
text += train[i] + "<br>"; window.alert(“sometext”);
i++;
Note: The window.alert() method can be written
} without the window prefix.
The loop in this example uses a while loop to collect the Example 15
car names from the train array:
alert (“Welcome to Java Script Coding!;)
train = ["Duronto","Satabdi","Garib Rath","Rajdhani"];
The result is shown in Fig 1.
var i = 0; Fig 1
var text = "";
while (train[i]) {
text += train[i] + "<br>";
i++;
}
Break statement is used to terminate a loop before its A confirm box is often used to verify or accept
completion. It saves machine time for not iterating a loop something.When a confirm box pops up, the user will have
uselessly. to click either “OK” or “Cancel” to proceed.If the user clicks
“OK”, the box returns true. If the user clicks “Cancel”, the
For example: In linear search, if we find the item then we box returns false.
can break the loop as no point of runnign it unnecessary. Syntax
Example 14 window.confirm(“sometext”);
Here, if the item is found, loop breaks and CPU time is else
saved. {
txt = “You clicked Cancel!”;
}
18 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B
Copyright @ NIMI Not to be Republished
The result is is shown in Fig 2. The result is is shown in Fig 3.
Fig 2 Fig 3
Syntax
window.prompt(“sometext”,”default text”);
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B 19
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.98A & 2.1.98B
COPA - JavaScript and creating Web page
Logic errors can be the most difficult type of errors to The JavaScript statements try and catch come in pairs.
track down. These errors are not the result of a syntax or
try {
runtime error. Instead, they occur when you make a mistake
in the logic that drives your script and you do not get the Block of code to try
result you expected.
}
20
Copyright @ NIMI Not to be Republished
catch (err){ }
Block of code to handle errors catch (err) {
} message.innerHTML = “Input is” + err;
JavaScript Throws Errors }
}
When an error occurs, JavaScript will normally stop and
generate an error message. This is technically called throw </script>
an exception (throw an error). JavaScript will actually
</body>
create an Error object with two properties - name and
message. </html>
The throw statement allows you to create a custom error. The finally statement lets you execute code, after try
The exception can be a JavaScript String, a Number, a and catch, regardless of the result:
Boolean or an Object:
try {
throw “very small”; // throw a text Block of code to try
throw 1000; // throw a number }
catch (err) {
Note: If you use throw together with try and
catch, you can control program flow and Block of code to handle errors
generate custom error messages. }
Input Validation Example finally {
This example examines input. If the value is wrong, an Block of code to be executed regardless of the try/
exception is thrown. The exception (err) is caught by the catch result
catch statement and a custom error message is displayed: }
<IDOCTYPE html> Example 2
<html>
function myFunction() {
<body>
var message, x;
<p>please input a number between 40 and 100</p>
message = document.getElementById(“s1”);
<input id = “demo” type = “text”>
message.innerHTML = “”;
<button type = “button”onclick = “myFunction()” >
x = document.getElementById(“demo”).value;
Sample Input </button>
try {
<p id = “s1”></p>
if (x ==””) throw “is empty”;
<script>
if (isNaN(x)) throw “is not a number”;
function myFunction() {
x = Number(x);
var message, x;
if (x>10) throw “is too high”;
message = document.get Element By Id (“s1”)
if (x<5) throw “is too low”;
message.inner HTML = “”,
}
x = document.getElementById(“demo”).value;
catch (err) {
try {
message.innerHTML = “Error:” + err + “.”;
if (x ==””) throw “nil”;
}
if (isNaN(x)) throw “not a number”;
finally {
x = Number(x);
document.getElementById (“demo”).value = “”;
if (x < 40) throw “too low”;
}
if (x > 100) throw “too high”;
}
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.98A & 2.1.98B 21
Copyright @ NIMI Not to be Republished
The Error Object }
JavaScript has a built in error object that provides error catch (err) {
information when an error occurs. The error object provides
document.getElementById(“demo”).innerHTML =
two useful properties - name and message.
err.name;
Property Description
}
Name - Sets or returns an error name
Syntax Error
message - Sets or returns an error message (a
string)
A SyntaxError is thrown if you try to evaluate code with a
syntax error.
Error Name Values
Example 5
Six different values can be returned by the error name
property. They are
try {
Error Name Description
Eval Error - An error has occurred in the eval() eval (“alert (“Welcome’); // Missing “will produce
function an error
Range Error - A number “out of range” has occurred }
Reference catch (err) {
Error - An illegal reference has occurred document.getElementById(“demo”).innerHTML
Syntax = err.name;
Error - A syntax error has occurred }
Type Error - A type error has occurred
Type Error
URI Error - An error in encodeURI() has occurred
A TypeError is thrown if you use a value that is outside
Eval Error the range of expected types.
An Eval Error indicates an error in the eval() function.
Example 6
Range Error
var num = 10;
A RangeError is thrown if you use a number that is
try {
outside the range of legal values.
num.toUpperCase(); // You cannot convert a
Example 3 number to upper case
}
var num = 1;
catch (err) {
try {
document.getElementById(“demo”).innerHTML =
num.to Precision (200); // A number cannot have 200 err.name;
significant digits
}
}
catch (err) { URI (Uniform Resource Identifier) Error
document.get Element By Id (“demo”).inner HTML = A URIError is thrown if you use illegal characters in a URI
err.name; function:
} Example
try {
Reference Error
decode URI (“%%”); // You cannot use URI
A ReferenceError is thrown if you use a variable that has decode percent signs
not been declared.
}
Example 4
catch (err) {
var x;
document.getElementById(“demo”).innerHTML =
try { err.name
x = y + 1; // cannot be referenced. }
22 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.98A & 2.1.98B
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.99
COPA - JavaScript and creating Web page
Arrays in JavaScript
Objectives : At the end of this lesson you shall be able to
• define Array
• explain concepts of Array
• describe array methods
• know sorting of Array.
An array is a special variable, which can hold more than You refer to an array element by referring to the index
one value at a time. number.
If you have a list of items (a list of train names, for example), This statement access the value of the first element in
storing the trains in single variables could look like this. myTrains:
var train1 = "Garib Rath"; This statement modifies the first element in trains:
var train1 = "Duronto";
trains[0] = "Jan Satabdi";
However, what if you want to loop through the trains and [0] is the first element in an array. [1] is the second. Array
find a specific one? And what if you had not 3 trains, but indexes start with 0.
300?
Displaying Arrays
The solution is an array!
We will use a script to display arrays inside a <p> element
JavaScript Arrays with id="demo":
var array-name = [item1, item2, ...]; The first line (in the script) creates an array named trains.
Example 1 The second line "finds" the element with id="demo", and
"displays" the array in the "innerHTML" of it.
var trains = ["Duronto", "Jan Satabdi", "RAJDHANI"];
Spaces and line breaks are not important. A declaration
Using the JavaScript Keyword new can span multiple lines.
23
Copyright @ NIMI Not to be Republished
Don't put a comma after the last element (like Example 7
"RAJDHANI",). It is inconsistent across browsers.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
An array can hold many values under a single name and
fruits[fruits.length] = "Lemon"; // adds a new element
you can access the values by referring to an index number.
(Lemon) to fruits
You can have different objects in one array
Adding elements with high indexes can create undefined
"holes" in an array:
JavaScript variables can be objects. Arrays are special
kinds of objects.
Example 8
Because of this, you can have variables of different types
var fruits = ["Banana", "Orange", "Apple", "Mango"];
in the same Array.
fruits[10] = "Lemon"; // adds a new element (Lemon) to
You can have objects in an Array. You can have functions fruits
in an Array. You can have arrays in an Array:
Looping Array Elements
my Array[0] = Date.now;
The best way to loop through an array is using a standard
my Array [1] = my Function;
for loop:
my Array [2] = myTrains;
Example 9
Arrays are Objects
var index;
Arrays are a special type of objects. The typeof operator
var fruits = ["Banana", "Orange", "Apple", "Mango"];
in JavaScript returns "object" for arrays.
for (index = 0; index < fruits.length; index++) {
But, JavaScript arrays are best described as arrays.
text += fruits[index];
Arrays use numbers to access its "elements". In this }
example, person[0] returns Raja:
Associative Arrays? No Way!
Array
Many programming languages support arrays with named
var person = ["Raja", "Sen", 46]; indexes.
Arrays with named indexes are called associative arrays
Objects use names to access its "members". In this
(or hashes).
example, person.firstName returns Raja:
JavaScript does not support arrays with named indexes.
Object
Wrong:
var person = {firstName:"Raja", lastName:"Sen", age:46};
var person = new Array()
The length Property
person ["firstName"] = "Raja";
The length property of an array returns the length of an person ["lastName"] = "Sen";
array (the number of array elements).
person ["age"] = 46;
Example 6
The example above looks like it works. But it does not.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
If you try it, person ["firstName"] will return Raja, but person
[0] will return undefined, and person.length will return 0.
fruits.length; // the length of fruits is 4
If you want to create an associative array, create an object
The length property is always one more than the highest
instead.
array index.
When to Use Arrays? When to use Objects?
Adding Array Elements
JavaScript does not support associative arrays.
The easiest way to add a new element to an array is to
use the length property:
You should use objects when you want the element names
to be strings.
24 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99
Copyright @ NIMI Not to be Republished
You should use arrays when you want the element names JavaScript Array Methods
to be sequential numbers.
Converting Arrays to Strings
Avoid new Array()
toString() method
There is no need to use the JavaScript's built-in array
constructor new Array(). The JavaScript method toString() converts an array to a
string of (comma separated) array values.
Use [] instead.
Example 10
These two different statements both create a new empty
array named points. var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”,”Fitter”];
document.getElementById(“demo”).innerHTML =
var points = new Array(); // Bad
trade.toString();
var points = []; // Good
Result
These two different statements both create a new array
containing 6 numbers. COPA,IT,ICTSM,CHNM,Fitter
var points = new Array(40, 100, 1, 5, 25, 10) // Bad join() method
var points = [40, 100, 1, 5, 25, 10]; // Good
The join() method also joins all array elements into a
string.It behaves just like toString(), but in addition you
The new keyword complicates your code and produces
can specify the separator.
nasty side effects.
Example 11
var points = new Array(40, 100); // Creates an array with
two elements (40 and 100) var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”,”Fitter”];
document.getElementById(“demo”).innerHTML =
What if I remove one of the elements?
trade.join(“-”);
var points = new Array(40); // Creates an array with 40
undefined elements !!!!! Result
COPA - IT – ICTSM – CHNM - Fitter
How to Recognize an Array?
Popping and Pushing
A common question is: How do I know if a variable is an
array? When you work with arrays, it is easy to remove elements
and add new elements.
The problem is that the JavaScript operator type of returns
"object": Popping
var fruits = ["Banana", "Orange", "Apple", "Mango"]; The pop() method removes the last element from an array.
typeof fruits; // typeof returns object
Example 12
The type of operator returns object because a JavaScript
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”,”Fitter”];
array is an object.
trade.pop(); // Removes the last element (“Fitter”) from
To solve this problem you can create your own isArray() trade.
function:
Result
function isArray(myArray) {
COPA,IT,ICTSM,CHNM
return myArray.constructor.toString().indexOf("Array") > 1;
} The pop() method returns the value that was “popped out”.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99 25
Copyright @ NIMI Not to be Republished
Pushing Example 19
The push() method adds a new element to an array (at var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];
the end). trade.unshift(“ElecMech”); // Returns 5
Example 14 Changing Elements
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”];
Array elements are accessed using their index
trade.push(“DTPO”); // Adds a new element (“DTPO”) number:Array indexes start with 0. [0] is the first array
to trade. element, [1] is the second, [2] is the third ...
Result Example 20
The shift() method returns the string that was “shifted out”: Example 22
var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
Example 17
delete trade[0]; // Changes the first element in
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”]; trade to undefined
trade.shift(); // Returns “COPA”
Note :Using delete may leave undefined holes
The unshift() method adds a new element to an array (at in the array. Use pop() or shift() instead
the beginning), and “unshifts” older elements.
Splicing an Array
Example 18
The splice() method can be used to add new items to an
var trade = [“COPA”, “IT”, “ICTSM”, “CHNM”]; array:
fruits.unshift(“ElecMech”); // Adds a new element
“ElecMech” to trade Example 23
26 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99
Copyright @ NIMI Not to be Republished
Note: The first parameter (2) defines the var arr3 = [“Ramya”,”Kavi”];
position where new elements should be added var myTrainee = arr1.concat(arr2, arr3);
(spliced in).The second parameter (0) defines // Concatenates arr1 with arr2 and arr3
how many elements should be removed.The
rest of the parameters (“Turner”, The concat() method can also take values as arguments.
“Machinist”)define the new elements to be
added. Example 27 (Merging an Array with Values)
With clever parameter setting, you can use splice() to The slice() method slices out a piece of an array into a
remove elements without leaving “holes” in the array. new array. This example slices out a part of an array starting
from array element 2 (“DTPO”). The slice() method creates
Example 24 a new array. It does not remove any elements from the
source array.
var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
Example 28
trade.splice(0, 1); // Removes the first element of
trade var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
IT,DTPO,CHNM The slice() method can take two arguments like slice
(1, 3). The method then selects elements from the start
Note :The first parameter (0) defines the argument, and up to (but not including) the end argument.
position where new elements should be added
(spliced in). The second parameter (1) defines Example 29
how many elements should be removed.The
rest of the parameters are omitted. No new var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
elements will be added. var trade1 = trade.slice(1,3);
Merging or Concatenating Arrays If the end argument is omitted, like in the first examples,
the slice() method slices out the rest of the array.
The concat() method creates a new array by merging
existing arrays. Example 30
Example 25 (Merging Two Arrays) var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
var trade1 = trade.slice(2);
var names1 = [“Devi”, “Deepa”];
var names2 = [“Poorna”, “Saranya”, “Shalini”]; Automatic toString()
var myTrainee = names1.concat(names2); JavaScript automatically converts an array to a comma
//Concatenates (joins) names1 and names2. separated string when a primitive value is expected. This
is always the case when you try to output an array.
Result
These two examples will produce the same result:
Note: The concat() method does not change
the existing arrays. It always returns a new
Example 31
array.
var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
The concat() method can take any number of array
arguments. document.getElementById(“demo”).innerHTML =
trade.toString();
Example 26 (Merging Three Arrays)
Example 32
var arr1 = [“Priya”, “Mythili”];
var trade = [“COPA”, “IT”, “DTPO”, “CHNM”];
var arr2 = [“Sangeetha”, “Nancy”, “Sahana”];
document.getElementById(“demo”).innerHTML = trade;
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99 27
Copyright @ NIMI Not to be Republished
Note: All JavaScript objects have a toString() Reversing an Array
method.
The reverse() method reverses the elements in an
Sorting an Array array.You can use it to sort an array in descending order.
CHNM,COPA,ICTSM,IT
28 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.100A
COPA - JavaScript and creating Web page
The code inside the function will execute when "something" In JavaScript, functions can be used as variables:
invokes (calls) the function.
Example 4
• When an event occurs (when a user clicks a button)
Instead of:
• When it is invoked (called) from JavaScript code
• Automatically (self invoked) temp = toCelsius(32);
29
Copyright @ NIMI Not to be Republished
text = "The temperature is " + temp + " Centigrade"; Automatically Global
You can use: If you assign a value to a variable that has not been de-
clared, it will automatically become a GLOBAL variable.
text = "The temperature is " + toCelsius(32) + " Centigrade";
This code example will declare train as a global variable,
JavaScript functions can be redefined like ordinary even if it is executed inside a function.
variables. It can also be passed as values to other
functions. Example 7
30 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100A
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.100B
COPA - JavaScript and creating Web page
Objects in JavaScript
Objectives: At the end of this lesson you shall be able to
• define object
• explain object and OOP concept
• explain terminology related to objects.
JavaScript is object-oriented to its core, with powerful, An object characteristic, such as color.
flexible OOP capabilities.
Method
Object-oriented programming
An object capability, such as walk. It is a subroutine or
Object-oriented programming is a programming paradigm function associated with a class.
that uses abstraction to create models based on the real
world. It uses several techniques from previously Constructor
established paradigms, including modularity,
polymorphism and encapsulation. Today, many popular A method called at the moment of instantiation of an object.
programming languages (such as Java, JavaScript, C#, It usually has the same name as that of the class containing
C++, Python, PHP, Ruby and Objective-C) support object- it.
oriented programming (OOP).
Inheritance
Object-oriented programming may be seen as the design
of software using a collection of cooperating objects, as A class can inherit characteristics from another class.
opposed to a traditional view in which a program may be
seen as a collection of functions or simply as a list of Encapsulation
instructions to the computer. In OOP, each object is
capable of receiving messages, processing data, and A method of bundling the data and methods that use them
sending messages to other objects. Each object can be together.
viewed as an independent little machine with a distinct
role or responsibility. Abstraction
31
Copyright @ NIMI Not to be Republished
The original (and most canonical) example of a prototype- },
based language is the programming language Self
validatePhoneNo: function(phoneNo){
developed by David Ungar and Randall Smith. However,
the class-less programming style has recently grown // do something with phone number
increasingly popular, and has been adopted for }
programming languages such as JavaScript, Cecil,
NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when }
using the Viewer framework to manipulate Morphic // Object together with the method declarations
components), and several others.
MYAPP.event = {
JavaScript Object Oriented Programming addListener: function(el, type, fn) {
Namespace // code stuff
},
A namespace is a container which allows developers to
bundle up all functionality under a unique, application- removeListener: function(el, type, fn) {
specific name. In JavaScript a namespace is just another // code stuff
object containing methods, properties and objects.
},
It is very important to note that there is no language-level getEvent: function(e) {
difference between regular object and namespaces as there
is in some other object-oriented languages. // code stuff
}
The idea behind creating a namespace in JavaScript is
simple: one global object is created and all variables, // Can add another method and properties
methods and functions become properties of that object. }
Use of namespaces also minimizes the possibility of name
conflicts in an application. //Syntax for Using addListner method:
var MYAPP = MYAPP || {}; JavaScript has several objects included in its core, for
example, there are objects like Math, Object, Array and
Here in above code sample we have first checked whether String. The example below shows how to use the Math
MYAPP is already defined (either in same file or in another object to get a random number by using its random()
file). If yes, then use the existing MYAPP global object, method.
otherwise create an empty object called MYAPP which
will encapsulate method, functions, variables and objects. alert(Math.random());
We can also create sub-namespaces: This and all further examples presume a
function named alert (such as the one included
// sub namespace in web browsers) is defined globally. The alert
function is not actually a part of JavaScript
MYAPP.event = {}; itself.
Below is code syntax for creating namespace and adding See JavaScript Reference: Global Objects for a list of the
variable, function and method: core objects in JavaScript.
// Create container called MYAPP.commonMethod for Every object in JavaScript is an instance of the object
common method and properties Object and therefore inherits all its properties and methods.
Custom Objects
MYAPP.commonMethod = {
The Class
regExForName: "", // define regex for name validation
regExForPhone: "", // define regex for phone no validation JavaScript is a prototype-based language which contains
no class statement, such as is found in C++ or Java. This
validateName: function(name){ is sometimes confusing for programmers accustomed to
// Do something with name, you can access languages with a class statement. Instead, JavaScript uses
regExForName variable functions as classes. Defining a class is as easy as
defining a function. In the example below we define a new
// using "this.regExForName"
class called Person.
32 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B
Copyright @ NIMI Not to be Republished
function Person() { } In the example below we define the firstName property for
the Person class and we define it at instantiation.
or
function Person(firstName) {
var Person = function(){ }
this.firstName = firstName;
The Object (Class Instance)
alert('Person instantiated');
To create a new instance of an object obj we use the
}
statement new obj, assigning the result (which is of type
obj) to a variable to access it later. var person1 = new Person('Alice');
var person2 = new Person('Bob');
In the example below we define a class named Person
and we create two instances (person1 and person2). // Show the firstName properties of the objects
alert('person1 is ' + person1.firstName); // alerts "person1
function Person() { }
is Alice"
var person1 = new Person();
alert('person2 is ' + person2.firstName); // alerts "person2
var person2 = new Person(); is Bob"
Please also see Object.create for a new and alternative The Methods
instantiation method.
Methods follow the same logic as properties; the difference
is that they are functions and they are defined as functions.
The Constructor
Calling a method is similar to accessing a property, but
The constructor is called at the moment of instantiation you add () at the end of the method name, possibly with
(the moment when the object instance is created). The arguments. To define a method, assign a function to a
constructor is a method of the class. In JavaScript, the named property of the class's prototype property; the name
function serves as the constructor of the object therefore, that the function is assigned to is the name that the method
there is no need to explicitly define a constructor method. is called by on the object.
Every action declared in the class gets executed at the
In the example below we define and use the method
time of instantiation.
sayHello() for the Person class.
The constructor is used to set the object's properties or to
function Person(firstName) {
call methods to prepare the object for use. Adding class
methods and their definitions occurs using a different this.firstName = firstName;
syntax described later in this article.
}
In the example below, the constructor of the class Person Person.prototype.sayHello = function() {
displays an alert when a Person is instantiated.
alert("Hello, I'm " + this.firstName);
function Person() { };
alert('Person instantiated'); var person1 = new Person("Alice");
} var person2 = new Person("Bob");
var person1 = new Person(); // call the Person sayHello method.
var person2 = new Person(); person1.sayHello(); // alerts "Hello, I'm Alice"
person2.sayHello(); // alerts "Hello, I'm Bob"
The Property (object attribute)
In JavaScript methods are regular function objects that
Properties are variables contained in the class; every are bound to an object as a property, which means they
instance of the object has those properties. Properties can be invoked "out of the context". Consider the following
should be set in the prototype property of the class example code:
(function) so that inheritance works correctly.
function Person(firstName) {
Working with properties from within the class is done using this.firstName = firstName;
the keyword this, which refers to the current object.
}
Accessing (reading or writing) a property outside of the
class is done with the syntax: InstanceName.Property; Person.prototype.sayHello = function() {
this is the same syntax used by C++, Java, and a number
alert("Hello, I'm " + this.firstName);
of other languages. (Inside the class the syntax
this.Property is used to get or set the property's value.)
};
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B 33
Copyright @ NIMI Not to be Republished
var person1 = new Person("Alice"); // Add a couple of methods to Person.prototype
var person2 = new Person("Bob"); Person.prototype.walk = function(){
var helloFunction = person1.sayHello; alert("I am walking!");
person1.sayHello(); // alerts "Hello, I'm Alice" };
person2.sayHello(); // alerts "Hello, I'm Bob" Person.prototype.sayHello = function(){
helloFunction(); // alerts "Hello, I'm undefined" (or fails alert("Hello, I'm " + this.firstName);
// with a TypeError in strict mode) };
alert(helloFunction === person1.sayHello); // alerts // Define the Student constructor
true
function Student(firstName, subject) {
alert(helloFunction === Person.prototype.sayHello); //
// Call the parent constructor, making sure (using
alerts true
Function#call) that "this" is
helloFunction.call(person1); // alerts "Hello, I'm Alice"
// set correctly during the call
As that example shows, all of the references we have to Person.call(this, firstName);
the sayHello function - the one on person1, on
// Initialize our Student-specific properties
Person.prototype, in thehelloFunction variable, etc. - refer
to the same function. The value of this during a call to the this.subject = subject;
function depends on how we call it. In the common case };
when we call it in an expression where we got the function
from an object property - person1.sayHello() - this is set // Create a Student.prototype object that inherits from
to the object we got the function from (person1), which is Person.prototype.
why person1.sayHello() uses the name "Alice" and // Note: A common error here is to use "new Person()" to
person2.sayHello() uses the name "Bob". But if we call it create the Student.prototype.
other ways, this is set differently: Calling it from a variable
- helloFunction() - sets this to the global object (window, // That's incorrect for several reasons, not least that we
on browsers). Since that object (probably) doesn't have a don't have anything to
firstName property, we end up with "Hello, I'm undefined". // give Person for the "firstName" argument. The correct
(That's in loose mode code; it would be different [an error] place to call Person is
in strict mode, but to avoid confusion we won't go into
detail here.) Or we can set this explicitly using // above, where we call it from Student.
Function#call (or Function#apply), as shown at the end of Student.prototype = Object.create(Person.prototype); //
the example. See note below
} student1.sayGoodBye(); // "Goodbye!"
34 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B
Copyright @ NIMI Not to be Republished
// Check that instanceof works correctly Abstraction
alert(student1 instanceof Person); // true
Abstraction is a mechanism that permits modeling the
alert(student1 instanceof Student); // true current part of the working problem. This can be achieved
by inheritance (specialization), or composition. JavaScript
Regarding the Student.prototype =
achieves specialization by inheritance, and composition
Object.create(Person.prototype); line: On older JavaScript
by letting instances of classes be the values of attributes
engines without Object.create, one can either use a
of other objects.
"polyfill" (aka "shim", see the linked article), or one can
use a function that achieves the same result, such as:
The JavaScript Function class inherits from the Object
function createObject(proto) { class (this demonstrates specialization of the model) and
the Function.prototype property is an instance of Object
function ctor() { }
(this demonstrates composition).
ctor.prototype = proto;
var foo = function(){};
return new ctor();
alert( 'foo is a Function: ' + (foo instanceof Function) );
}
// alerts "foo is a Function: true"
// Usage:
alert( 'foo.prototype is an Object: ' + (foo.prototype
Student.prototype = createObject(Person.prototype); instanceof Object) ); // alerts "foo.prototype is an Object:
true"
See Object.create for more on what it does, and a shim
for older engines. Polymorphism
Encapsulation Just like all methods and properties are defined inside the
prototype property, different classes can define methods
In the previous example, Student does not need to know with the same name; methods are scoped to the class in
how the Person class's walk() method is implemented, which they're defined. This is only true when the two
but still can use that method; the Student class doesn't classes do not hold a parent-child relation (when one does
need to explicitly define that method unless we want to not inherit from the other in a chain of inheritance).
change it. This is called encapsulation, by which every
class inherits the methods of its parent and only needs to
define things it wishes to change.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B 35
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.101A
COPA - JavaScript and creating Web page
JavaScript strings are used for storing and manipulating var x = 'you\'re Welcome.';
text. A JavaScript string is zero or more characters written
The sequence \\ inserts a backslash in a string:
inside quotes.You can use single or double quotes.
Example 6
Example 1
var x = "The character \\ is called backslash.";
var cityname = "Chennai"; // Double quotes
var cityname = 'Chennai'; // Single quotes Strings Can be Objects
You can use quotes inside a string, as long as they don't Normally, JavaScript strings are primitive values, created
match the quotes surrounding the string. from literals.
var notes = "You're Welcome"; But strings can also be defined as objects with the keyword
new.
var ans = "Coimbatore is called 'Cotton City'";
var ans = 'Coimbatore is called "Cotton City"'; var tName = new String("Veni");
The length of a string is found in the built in property length. String methods help you to work with strings.
36
Copyright @ NIMI Not to be Republished
Example 8 Example 12
Result: Result:
The variable numhas the position value 22. The result of res will beCricket
Both indexOf(), and lastIndexOf() return -1 if the text is not If a parameter is negative, the position is counted from the
found. end of the string.This example slices out a portion of a
string from position -14 to position -8.
Example 9
Example 13
var str = "When I do good I feel good";
var str = "Hockey,Kabadi,Cricket";
var num = str.lastIndexOf("better");
var res = str.slice(-14, -8);
Result:
Result:
The variable numhas the position value -1.
The result of res will beKabadi
Both methods accept a second parameter as the starting
position for the search. If you omit the second parameter, the method will slice out
the rest of the string.
Example 10
Example 14
var str = "When I do good I feel good";
var res = str.slice(7);
var num = str.indexOf("good",15);
Result:
Result:
The result of res will beKabadi,Cricket
The variable numhas the position value 22.
The substring() Method
Searching for a String in a String
substring() is similar to slice().The difference is that
substring() cannot accept negative indexes.
The search() method searches a string for a specified value
and returns the position of the match.
Example 15
Example 11
var str = "Hockey,Kabadi,Cricket";
var str = "When I do good I feel good"; var res = str.substring(7, 13);
var num = str.search("good");
Result:
Result:
The result of res will beKabadi
The variable numhas the position value 10. The substr() Method
Note: The search() method cannot take a second If you omit the second parameter, substring() will slice out
start position argument. the rest of the string.The substr() Method substr() is similar
to slice().The difference is that the second parameter
Extracting String Parts specifies the length of the extracted part.
The slice() Method
Example 16
slice() extracts a part of a string and returns the extracted
var str = "Hockey,Kabadi,Cricket";
part in a new string.The method takes the starting position,
and the ending position. var res = str.substr(7, 6);
The result of res will be Kabadi,Cricket Converting to Upper and Lower Case
If the first parameter is negative, the position counts from A string is converted to upper case with toUpperCase()
the end of the string.
Example 22
Example 18
var str1 = "Information Technology";
var str = "Hockey,Kabadi,Cricket";
var str2 = str1.toUpperCase();
var res = str.substr(-7);
Result:
Result:
The result of str2 will be INFORMATION TECHNOLOGY
The result of res will be Cricket
A string is converted to lower case with toLowerCase().
Replacing String Content
Example 23
The replace() method replaces a specified value with
another value in a string.
var str1 = "INFORMATION TECHNOLOGY";
Example 19 var str2 = str1.toLowerCase();
38 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101A
Copyright @ NIMI Not to be Republished
Example 26 <script>
var str = "Temple";
var str = " India Gate ";
var arr = str.split("");
alert(str.trim());
var text = "";
Result:
var i;
India Gate is displayed without leading and trailing blank for (i = 0; i < arr.length; i++) {
spaces in alert box.
text += arr[i] + "<br>"
Extracting String Characters }
document.getElementById("demo").innerHTML = text;
The charAt() method returns the character at a specified
index in a string. </script>
</body>
Example 27
</html>
var str = "Thirumalai Nayakkar Mahal";
Result:
str.charAt(0); // returns T
T
The charCodeAt() method returns the unicode of the
e
character at a specified index in a string. The method
returns an UTF-16 cone integer between 0 and 65535. m
p
Example 28
l
var str = "Hill Station";
e
str.charCodeAt(0); // returns 72
?
Converting a String to an Array
JavaScript Number Methods
A string can be converted to an array with the split() Number methods help you work with numbers.
method.
Number Methods and Properties
Example 29
Primitive values like 2018 or 1.44 , cannot have properties
var txt1 = "Kovai,Nellai,Madurai"; // String and methods because they are not objects.
var txt2 = txt1.split(","); // Split on commas But with JavaScript, methods and properties are also
available to primitive values, because JavaScript treats
Result: primitive values as objects when executing methods and
properties.
The result of txt2 will be Kovai
The toString() Method
If the separator is omitted, the returned array will contain
the whole string in index [0].If the separator is "", the toString() returns a number as a string.All number methods
returned array will be an array of single characters. can be used on any type of numbers (literals, variables, or
expressions).
Example 30 Example 32
valueOf() returns a number as a number. Note : If the number cannot be converted, NaN
(Not a Number) is returned.
Example 36
The Number() Method Used on Dates. Number() can also
var x = 451; convert a date to a number:
x.valueOf(); // returns 451 from variable x Example 38
(451).valueOf(); // returns 451 from literal 451 Number(new Date("2018-09-15")); // returns
(400 + 51).valueOf(); // returns 451 from expression 400 1536969600000
+ 51
Note : The Number() method above returns the
Converting Variables to Numbers number of milliseconds since 1.1.1970.
There are 3 JavaScript methods that can be used to convert The parseInt()Method
variables to numbers: parseInt() parses a string and returns a whole number.
Spaces are allowed. Only the first number is returned.
40 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101A
Copyright @ NIMI Not to be Republished
Example 39 Example 42
Example 40 var n = 2 / 0;
JavaScript NEGATIVE_INFINITY
parseFloat("25"); // returns 25
parseFloat("25.77"); // returns 25.77 Example 45
parseFloat("255075"); // returns 25
var n = Number.NEGATIVE_INFINITY;
parseFloat("25 years"); // returns 25
NEGATIVE_INFINITY is returned on overflow:
parseFloat("years 25"); // returns NaN
Example 46
Note : If the number cannot be converted, NaN
(Not a Number) is returned. var x = -1 / 0;
JavaScript NaN - Not a Number
?
Example 47
Number Properties
var x = Number.NaN;
Property Description
NaN is a JavaScript reserved word indicating that a number
MIN_VALUE Returns the smallest number
is not a legal number.Trying to do arithmetic with a non-
possible in JavaScript
numeric string will result in NaN (Not a Number).
MAX_VALUE Returns the largest number
possible in JavaScript Example 48
POSITIVE_INFINITY Represents infinity (returned on var n = 500 / "Price"; // n will be NaN (Not a Number)
overflow)
Number Properties Cannot be Used on Variables
NEGATIVE_INFINITY Represents negative infinity
(returned on overflow) Number properties belongs to the JavaScript's number
object wrapper called Number.These properties can only
NaN Represents a "Not-a-Number" be accessed as Number.MAX_VALUE.
value
Using newNumber.MAX_VALUE, where 'newNumber' is a
JavaScript MIN_VALUE and MAX_VALUE variable, expression, or value, will return undefined.
Example 41 Example 49
var n = Number.MAX_VALUE; var a = 10;
Result: var b = a.MAX_VALUE; // b becomes undefined
MAX_VALUE returns the largest possible number in
JavaScript.
1.7976931348623157e+308
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101A 41
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.101B
COPA - JavaScript and creating Web page
Math.round(x) returns the value of x rounded to its nearest Math.sin(0 * Math.PI / 180); // returns 0 (the sine of 0
integer: degrees)
Math.pow(x, y) returns the value of x to the power of y: Angle in radians = Angle in degrees x PI / 180.
Example 2 Example 8
Example 4 Example 10
Math.ceil(x) returns the value of x rounded up to its nearest Math.random() returns a random number between 0
integer: (inclusive), and 1 (exclusive):
Example 5 Example 11
42
Copyright @ NIMI Not to be Republished
Math.SQRT1_2 // returns the square root of 1/2 Math Constructor
Math.LN2 // returns the natural logarithm of 2 Unlike other global objects, the Math object has no
constructor. Methods and properties are static. All
Math.LN10 // returns the natural logarithm of 10 methods and properties (constants) can be used without
creating a Math object first.
Math.LOG2E // returns base 2 logarithm of E
Method Description
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101B 43
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.101C
COPA - JavaScript and creating Web page
JavaScript Dates
Objectives : At the end of this lesson you shall be able to
• explain JavaScript Date Objects
• explain JavaScript Date Formats
• explain JavaScript Date get methods
• explain JavaScript Date set methods.
By default, JavaScript will use the browser's time zone new Date(year, month, ...) creates a new date object with
and display a date as a full text string. a specified date and time.
There are 4 ways to create a new date object. They are Result: (Fig 2)
1 new Date()
new Date() creates a new date object with the current
date and time.
Example 1:
Note: JavaScript counts months from 0 to 11.
var d = new Date(); January is 0. December is 11.
alert(d);
6 numbers specify year, month, day, hour, minute, sec-
Result: (Fig 1) ond.
Fig 1 Example 3
Example 4
Example 5
Note Date objects are static. The computer time 3 numbers specify year, month, and day.
is ticking, but date objects are not.
44
Copyright @ NIMI Not to be Republished
Example 6
Note: JavaScript stores dates as number of mil-
var d = new Date(2018, 06, 30); liseconds since January 01, 1970, 00:00:00 UTC
(Universal Time Coordinated). Zero time is
2 numbers specify year and month. January 01, 1970 00:00:00 UTC. Now the time
is: 1537962903199 milliseconds past January 01,
Example 7 1970
Example 12
You cannot omit month. If you supply only one parameter Result: (Fig 5)
it will be treated as milliseconds. Fig 5
Example 8
Previous Century
Example 9
var d = new Date(96, 04, 12); January 01 1970 minus 100 000 000 milliseconds is ap-
proximately December 31 1969.
3 new Date(dateString)
Example 13
new Date(dateString) creates a new date object from a
date string. var d = new Date(-100000000);
Fig 6
var d = new Date("December 20, 2018 10:15:00");
Result: (Fig 4)
Fig 4
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C 45
Copyright @ NIMI Not to be Republished
The toDateString() method converts a date to a more read-
Example 14
able format.
var d = new Date(86400000);
Example 17
Result:
var d = new Date();
Fri Jan 02 1970 05:30:00 GMT+0530 (India Standard Time)
alert(d.toDateString());
Note: Using new Date(milliseconds), creates a
new date object as January 1, 1970, 00:00:00
Result: (Fig 8)
Universal Time (UTC) plus the milliseconds.
One day (24 hours) is 86 400 000 milliseconds. Fig 8
Date Methods
Displaying Dates
JavaScript Date Formats
By default JavaScript will output dates in full text string
format. When you display a date object in HTML, it is JavaScript Date Input
automatically converted to a string, with the toString()
method. There are generally 3 types of JavaScript date input for-
mats.
Example 15
Type Example
d = new Date();
ISO Date "2002-06-30" (The International Stan
alert(d); dard)
Same as: Short Date "06/30/2002"
d = new Date(); Long Date "Jun 30 2002" or "30 Jun 2002"
alert(d.toString()); JavaScript Date Output
The toUTCString() method converts a date to a UTC string. Independent of input format, JavaScript will output dates
in full text string format.
Example 16
JavaScript ISO Dates
var d = new Date();
ISO 8601 is the international standard for the representa-
alert(d); tion of dates and times. The ISO 8601 syntax (YYYY-
MM-DD) is also the preferred JavaScript date format.
Result: (Fig 7)
Example 18 (Complete date)
Fig 7
46 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C
Copyright @ NIMI Not to be Republished
Example 19 JavaScript Long Dates
var d = new Date("2002-06"); Long dates are most often written with a "MMM DD YYYY"
syntax like this.
Result:
Example 23
Sat Jun 01 2002 05:30:00 GMT+0530 (India Standard Time)
var d = new Date("Aug 31 2012");
ISO Dates (Only Year)
Month and day can be in any order.
ISO dates can be written without month and day (YYYY).
Example 24
Example 20
var d = new Date("31 Aug 2012");
var d = new Date("2011");
And, month can be written in full (January), or abbreviated
(Jan).
Result:
Example 25
Sat Jan 01 2011 05:30:00 GMT+0530 (India Standard Time)
var d = new Date("August 31 2012");
ISO Dates (Date-Time)
var d = new Date("AUGUST 31 2012");
ISO dates can be written with added hours, minutes, and
seconds (YYYY-MM-DDTHH:MM:SSZ) Note: Commas are ignored. Names are case
insensitive.
Example 21
Date Input - Parsing Dates
var d = new Date("2011-12-20T12:00:00Z");
If you have a valid date string, you can use the Date.parse()
Result: method to convert it to milliseconds. Date.parse() returns
the number of milliseconds between the date and
Tue Dec 20 2011 17:30:00 GMT+0530 (India Standard Time) January 1, 1970.
Result: Example 27
Sun Jun 30 2002 00:00:00 GMT+0530 (India Standard var msec = Date.parse("Sep 15, 1996");
Time)
var d = new Date(msec);
Note: In some browsers, months or days with document.getElementById("demo").innerHTML = d;
no leading zeroes may produce an error. The
behavior of "YYYY/MM/DD" is undefined. Some Result:
browsers will try to guess the format. Some
will return NaN. The behavior of "DD-MM-YYYY" Sun Sep 15 1996 00:00:00 GMT+0530 (India Standard
is also undefined. Some browsers will try to Time)
guess the format. Some will return NaN.
JavaScript Get Date Methods
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C 47
Copyright @ NIMI Not to be Republished
Fig 10
Method Description
Example 28
alert(d.getTime());
Result: (Fig 9)
Fig 9 In JavaScript, the first month (January) is month number
0, so December returns month number 11.
You can use an array of names, and getMonth() to return
the month as a name.
Example 31
alert(d.getFullYear());
48 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C
Copyright @ NIMI Not to be Republished
The getDate() Method Fig 15
Example 32
alert(d.getDate());
Example 35
alert(d.getSeconds());
Fig 16
The getHours() method returns the hours of a date as a
number (0-23).
Example 33
alert(d.getHours());
Example 36
alert(d.getMilliseconds());
The getMinutes() Method
Result: (Fig 17)
The getMinutes() method returns the minutes of a date as
a number (0-59). Fig 17
Example 34
alert(d.getMinutes());
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C 49
Copyright @ NIMI Not to be Republished
The getDay() Method
Method Description
The getDay() method returns the weekday of a date as a
getUTCDate() Same as getDate(), but returns
number (0-6).
the UTC date
Example 37
getUTCDay() Same as getDay(), but returns
the UTC day
var d = new Date();
getUTCFullYear() Same as getFullYear(), but
alert(d.getDay());
returns the UTC year
Result: (Fig 18)
getUTCHours() Same as getHours(), but returns
Fig 18 the UTC hour
In JavaScript, the first day of the week (0) means "Sun- getUTCSeconds() Same as getSeconds(), but re
day", even if some countries in the world consider the first turns the UTC seconds
day of the week to be "Monday"
JavaScript Set Date Methods
You can use an array of names, and getDay() to return the
weekday as a name. Set Date methods let you set date values (years, months,
days, hours, minutes, seconds, milliseconds) for a Date
Example 38 Object.
50 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C
Copyright @ NIMI Not to be Republished
Example 39 d.setMonth(2);
<script> alert(d);
var d = new Date();
</script>
d.setFullYear(2020);
Result: (Fig 22)
alert(d);
Fig 22
</script>
Example 42
Note: The setFullYear() method can optionally
set month and day. <script>
var d = new Date();
Example 40
d.setDate(18);
<script> alert(d);
var d = new Date(); </script>
d.setFullYear(2018, 10, 2);
Result: (Fig 23)
alert(d);
Fig 23
<script>
Result: (Fig 21)
Fig 21
Example 41 alert(d);
<script> </script>
If adding days, shifts the month or year, the changes are The setSeconds() Method
handled automatically by the Date object.
The setSeconds() method sets the seconds of a date ob-
ject (0-59).
The setHours() Method
Example 46
The setHours() method sets the hours of a date object
(0-23).
<script>
Example 44 var d = new Date();
d.setSeconds(20);
<script>
alert(d);
var d = new Date();
</script>
d.setHours(20);
Result: (Fig 27)
alert(d); Fig 27
</script>
Result: (Fig 25)
Fig 25
Compare Dates
Dates can easily be compared.
The following example compares today's date with Janu-
ary 14, 2100.
The setMinutes() Method
Example 47
The setMinutes() method sets the minutes of a date ob-
var date1 = new Date(2010, 00, 15); //Year, Month, Date
ject (0-59).
var date2 = new Date(2011, 00, 15); //Year, Month, Date
Example 45
if (date1 > date2)
<script> {
var d = new Date(); alert("Date One is greather then Date Two.");
}
d.setMinutes(15);
else
alert(d);
{
</script> alert("Date Two is greather then Date One.");
}
52 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.101C
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.102A
COPA - JavaScript and creating Web page
JavaScript HTML DOM The HTML DOM model is constructed as a tree of Objects:
With the HTML DOM, JavaScript can access and modify The HTML DOM Tree of Objects
all the elements of an HTML document.
With the object model, JavaScript gets all the power it
The HTML DOM (Document Object Model) needs to create dynamic HTML:
• JavaScript can change all the CSS styles in the page The DOM defines a standard for accessing documents:
• JavaScript can remove existing HTML elements and
attributes "The W3C Document Object Model (DOM) is a platform
and language-neutral interface that allows programs and
• JavaScript can add new HTML elements and attributes scripts to dynamically access and update the content,
• JavaScript can react to all existing HTML events in the structure, and style of a document."
page
53
Copyright @ NIMI Not to be Republished
The W3C DOM standard is separated into 3 different parts: <html>
<body>
• Core DOM - standard model for all document types
<p id="demo"></p>
• XML DOM - standard model for XML documents
<script>
• HTML DOM - standard model for HTML documents
document.getElementById("demo").innerHTML =
What is the HTML DOM? "Welcome to JavaScript!";
</script>
The HTML DOM is a standard object model and
programming interface for HTML. It defines: </body>
</html>
• The HTML elements as objects
In the example above, getElementById is a method, while
• The properties of all HTML elements
innerHTML is a property.
• The methods to access all HTML elements
The getElementById Method
• The events for all HTML elements
In other words: The HTML DOM is a standard for how to The most common way to access an HTML element is to
get, change, add, or delete HTML elements. use the id of the element. In the example above the
getElementById method used id="demo" to find the
HTML DOM Methods element.
HTML DOM methods are actions you can perform (on The innerHTML Property
HTML Elements)
The easiest way to get the content of an element is by
HTML DOM properties are values (of HTML Elements) using the innerHTML property. The innerHTML property is
that you can set or change. useful for getting or replacing the content of HTML elements.
The DOM Programming Interface Note: The innerHTML property can be used to
get or change any HTML element, including
The HTML DOM can be accessed with JavaScript (and <html> and <body>.
with other programming languages).
HTML DOM Document
In the DOM, all HTML elements are defined as objects.The
programming interface is the properties and methods HTML DOM document object
of each object. A property is a value that you can get or
set (like changing the content of an HTML element). A The document object is the owner of all other objects in
method is an action you can do (like add or deleting an your web page. In the HTML DOM object model, the
HTML element). document object represents your web page. If you want to
access objects in an HTML page, you always start with
Example 1 accessing the document object.
The following example changes the content (the innerHTML) Below are some examples of how you can use the
of the <p> element with id="demo": document object to access and manipulate HTML.
Method Description
54 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A
Copyright @ NIMI Not to be Republished
Changing HTML Elements
Method Description
Method Description
Method Description
JavaScript HTML DOM Elements If the element is found, the method will return the element
as an object (in x).
Finding HTML Elements
If the element is not found, x will contain null.
Often, with JavaScript, you want to manipulate HTML Finding HTML Elements by Tag Name
elements.
This example finds the element with id="main", and then
To do so, you have to find the elements first. There are a finds all <p> elements inside "main":
couple of ways to do this:
Example 3
• Finding HTML elements by id
var x = document.getElementById("main");
• Finding HTML elements by tag name
var y = x.getElementsByTagName("p");
• Finding HTML elements by class name
Finding HTML Elements by Class Name
• Finding HTML elements by HTML object collections
If you want to find all HTML elements with the same class
Finding HTML Elements by Id name, use this method get ElementsByClassName()
The easiest way to find HTML elements in the DOM, is by Example 4
using the element id.
document.getElementsByClassName("intro");
This example finds the element with id="demo":
The example above returns a list of all elements with
Example 2 class="intro".
var x = document.getElementById("demo"); Note: Finding elements by class name does not
work in Internet Explorer 5,6,7, and 8.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A 55
Copyright @ NIMI Not to be Republished
Finding HTML Elements by HTML Object Collections
Example 5 • document.anchors
56 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A
Copyright @ NIMI Not to be Republished
Changing the HTML Output Stream Example 8
The easiest way to modify the content of an HTML element Changing the Value of an Attribute
is by using the innerHTML property.To change the content
of an HTML element, use this syntax. To change the value of an HTML attribute, use this syntax.
This example changes the content of a <p> element: This example changes the value of the src attribute of an
<img> element.
Example 7
Example 9
<html>
<!DOCTYPE html>
<body>
<html>
<p id="p1">Hello World!</p>
<body>
<script>
<img id="Image1" src="flower.gif">
document.getElementById("p1").innerHTML = "New text!";
<script>
</script> document.getElementById("Image1").src =
"newflower.jpg";
</body>
</script>
</html>
</body>
Example explained:
</html>
• The HTML document above contains a <p> element
Example explained:
with id="p1"
• We use the HTML DOM to get the element with id="p1" • The HTML document above contains an <img> element
with id="myImage"
• A JavaScript changes the content (innerHTML) of that
element to "New text!" • We use the HTML DOM to get the element with
id="myImage"
This example changes the content of an <h1> element:
• A JavaScript changes the src attribute of that element
from "smiley.gif" to "landscape.jpg"
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A 57
Copyright @ NIMI Not to be Republished
Changing HTML Style A JavaScript can be executed when an event occurs, like
when a user clicks on an HTML element. To execute code
To change the style of an HTML element, use this syntax. when a user clicks on an element, add JavaScript code to
an HTML event attribute
document.getElementById(id).style.property = new style
onclick=JavaScript
The following example changes the style of a <p> element:
Examples of HTML events:
Example 10
• When a user clicks the mouse
<html>
• When a web page has loaded
<body>
• When an image has been loaded
<p id="p2">Hello World!</p>
• When the mouse moves over an element
<script>
• When an input field is changed
document.getElementById("p2").style.color = "green";
• When an HTML form is submitted
</script>
• When a user strokes a key
<p>The paragraph above was changed by a script.</p>
</body> In this example, the content of the <h1> element is
changed when a user clicks on it.
</html>
Example 12
Using Events
<!DOCTYPE html>
The HTML DOM allows you to execute code when an
event occurs. Events are generated by the browser when <html>
"things happen" to HTML elements. <body>
<h1 onclick="this.innerHTML = 'Ooops!'">Click on this
• An element is clicked on
text!</h1>
• The page has loaded
</body>
• Input fields are changed
</html>
This example changes the style of the HTML element with
HTML Event Attributes
id="id1", when the user clicks a button.
To assign events to HTML elements you can use event
Example 11
attributes.
<!DOCTYPE html>
Example 13
<html>
Assign an onclick event to a button element:
<body>
<button onclick="displayDate()">Try it</button>
<h1 id="id1">Heading1</h1>
<button type="button" In the example above, a function named displayDate will
onclick="document.getElementById('id1').style.color = be executed when the button is clicked.
'blue'">
Assign Events Using the HTML DOM
Click Me</button>
The HTML DOM allows you to assign events to HTML
</body> elements using JavaScript.
</html> Example 14
</script>
58 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A
Copyright @ NIMI Not to be Republished
In the example above, a function named displayDate is DOM Event Listener
assigned to an HTML element with the id="myBtn".
The addEventListener() method
The function will be executed when the button is clicked.
Add an event listener that fires when a user clicks a button.
The onload and onunload Events
Example 17
The onload and onunload events are triggered when the
user enters or leaves the page. The onload event can be <!DOCTYPE html>
used to check the visitor's browser type and browser
version and load the proper version of the web page based <html>
on the information.The onload and onunload events can
be used to deal with cookies. <body>
Example 16 document.getElementById("myBtn").addEventListener("click",
displayDate);
<input type="text" id="fname" onchange="upperCase()">
function displayDate() {
The onmouseover and onmouseout Events
document.getElementById("demo").innerHTML = Date();
The onmouseover and onmouseout events can be used to
trigger a function when the user mouses over or out of, an }
HTML element.
</script>
The onmousedown, onmouseup and onclick Events
</body>
The onmousedown, onmouseup and onclick events are
all parts of a mouse-click. First when a mouse-button is </html>
clicked, the onmousedown event is triggered, then, when
the mouse-button is released, the onmouseup event is Result: (Fig 1)
triggered, finally, when the mouse-click is completed, the
Fig 1
onclick event is triggered.
onload
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A 59
Copyright @ NIMI Not to be Republished
• You can add event listeners to any DOM object not 1 WordPress
only HTML elements. i.e the window object.
The official websites for WordPress are
• The addEventListener() method makes it easier to
https://wordpress.com and
control how the event reacts to bubbling.
https://wordpress.org/.
• When using the addEventListener() method, the
JavaScript is separated from the HTML markup, for
2 Kompozer
better readability and allows you to add event listeners
even when you do not control the HTML markup. The official website for Kompozer is
• You can easily remove an event listener by using the https://www.kompozer.net.
removeEventListener() method.
3 Joomla
Open Source Software The official website for Joomla is
You can build a website using these popular free and open https://www.joomla.org/.
source website building tools. Nowadays, whether you
are an individual entrepreneur or representing a business 4 Drupal
organisation, a website is a must for personal and The official website for Drupal is
professional growth. Organisations are spending lots of
money to build attractive websites. The following are some https://www.drupal.org/.
of the open source website building tools that you can
use to build your website on your own, without much 5 OpenCms
knowledge about programming or the Internet.
The official website for OpenCms is
http:// www.opencms.org/en/.
60 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.102B
COPA - JavaScript and creating Web page
KompoZer is suitable for anyone wishing to have a modern, KompoZer Screen Layout
free of charge, program for developing small web sites and
who would like to learn modern web design techniques KompoZer screen layout. (Fig 1)
such as the use of CSS.
Fig 1
Basics :
61
Copyright @ NIMI Not to be Republished
When KompoZer starts the window carries a menu bar To open an existing page
across the top (File, Edit, View etc). Below this are three
'Toolbars'. To ensure that everything is visible, on the Menu 1 Click the OPEN button to access a normal browse
bar selectView > Show/Hide and see that each of the dialogue.
following is checked: 2 Click File > Recent Pages to get rapid access to those
recently worked on.
• Composition Toolbar,
3 Or use the Site Manager which provides a powerful mini-
• Format Toolbar 1
browser and is very easily set up. The Doctype of an
• Format Toolbar 2 existing page will remain the same as before it was
opened. It cannot be changed in KompoZer.
• Edit Mode Toolbar
• Status bar Each page opened starts in a new tab which can be clicked
to select a document to work on.
• Rulers
• Site Manager Editing in KompoZer
The three toolbars across the top of the window carry KompoZer supports all the standard Windows editing
buttons (represented by icons). Hover on any to find its commands and shortcut keys. e.g. Copy Ctrl+C, Paste
function. If any are greyed out they are not functional in the Ctrl+V etc. There are other KompoZer specifics. These are
current mode as they are context sensitive. Across the great time savers. In 'HTML Tags' view KompoZer supports
centre of the window are two panes: the 'Site Manager' on drag and drop editing for block items. (Select an item by
the left and a blank web page on the right. The Site Manager pressing the Control key while clicking on the Tag.) An
is a powerful tool. Since it is not needed yet it may be extreme time saver is KompoZer's double click response.
closed by clicking on its close button or pressing F9. At the In several cases, such as links, images and tables, a very
top of the Page area there is a Page tab which carries the useful editing window is opened. KompoZer supports many
name of the page ('Untitled'). KompoZer Help refers to this levels of Undo and Redo, however changes made in
as the 'Tab Browser' toolbar. If you had several pages open, 'Source' view cannot be undone after you have changed the
as shown in the Fig.1, this tab would allow you to select one view.
them rapidly. At the bottom of the page area is the 'Edit
Mode Toolbar' which carries four tabs which select one of Saving files
four 'Viewing modes' for a page ('Normal', 'HTML Tags',
'Source', 'Preview'.) Go to File > Save as. You are offered a 'Save Page as'
window which allows you to browse to the folder you want
At the bottom of the window is the 'Status Bar'. This is a very to use. You will find the file name already completed with
powerful tool. Once a page is populated, by clicking any your page title. You will probably want to changethis to a
item in the page area its structure appears on the status shorter, all lower case, name. You will find the file extension
bar. Any class or id applied to an element is shown and any completed as 'html' you may prefer to, and may alter it to
bearing an inline style isindicated in italic type. Hovering "htm".
reveals the style declaration. Additionally clicking an
element marker highlights the element in both normal view Printing pages
and, on changing view, in source view thus simplifying
navigation in source view. Note The figure shows the The 'Print' button allows you to print the current page to a
buttons as they appear when KompoZer is first installed. printer. This prints the page view and not the source code.
They may be customised to different arrangements. If this
has been done some of the following may be difficult to Working with text
follow.
Text typed directly onto the KompoZer page defaults to
To restore defaults click View > Show/Hide > Customize appearing in the format for the 'Body' element.
Toolbar > Main Toolbar > Restore Default Set and
repeat similarly for the Format Toolbar. Using KompoZer HTML defines a small number of elements specifically for
right-click any toolbar to customise it. text and it is usually preferable to use these. To format text
in a standard element format select the text and click the
Options for starting a page first drop-down box on the format toolbar. This offers a
selection of standard text formats. Paragraph is the most
There are several ways to start new pages or open existing appropriate for general text.
ones.
Once formatted as a paragraph, when typing in a text area,
To start a new blank page, on the menu bar click File > use of the 'enter' key starts a new block of text i.e. a
New. A window headed 'Create a new document or template' paragraph. To start a new line within the current paragraph
appears. Check the boxes 'A blank document' and 'Strict press Shift+Enter; this generates a line break.
DTD' and clear 'create a XHTML document'.
62 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B
Copyright @ NIMI Not to be Republished
Other standard text formats are Heading formats from Tabs will be rendered as three non-breaking spaces. The
Heading 1, the largest (for the main heading), to Heading contents of tables may be pasted, individual cells will be
6, the smallest (for the least significant). Browsers separated as if by tabs.
generally render headings in bold type. Text can be edited
in any of the viewing modes and KompoZer responds to all Special characters
the normal windows shortcut commands.
By special characters we refer to characters which do not
Formatting text have an equivalent keyboard key. HTML uses a system of
characters known as 'Unicode'. This includes a large range
Text can be formatted in a number of ways using a format of characters including all the international currency symbols
toolbar. The changes listed in the table can be applied and many thousands of others, though the fonts supplied
(hover over a tool to discover what it does). on computers will support only a subset. A number of the
more common, including accented ones, may be inserted
Choose a font , Choose text colour, Choose using Insert > Characters and Symbols.
background colour, Choose highlight colour,
Make text smaller, Make text larger, Checking spelling
Embolden, Italicise, Underline, Format as a
numbered list, Format as a bulleted list, Align In any view, other than Source, click on the 'Spell' button.
left, Align Centre, Align right, Justify, Indent
text, Outdent text,Emphasise, Strongly .The spell checker will work sequentially through the
emphasise.
page.
Numbered and Bulleted lists
To insert an image
KompoZer can format a list of items giving each item a
1 Click the 'Image' button on the Composition toolbar
sequential number in any of several formats or presenting
them bulleted. To start a list from scratch 2 The Image properties window opens. Click 'Choose File'
and browse and select a file
1 Click one of the list buttons (Numbered List or Bulleted
3 Click 'Open'. Leave checked the box 'URL is relative to
list) on the Format toolbar.
page location' this will allow you to move the page and
2 Type the first item. image to another location, as you will have to when you
upload them to a server. (If you de-select this and move
3 Press Enter and type the next item.
the page, it will try to find the image at the original
4 To finish, on the last(blank) item press Enter. location.) Note If the box is 'greyed out' this is probably
because the page has not been saved.
To change existing text into a list
4 In the box labelled 'Alternate text' add a description of
1 Select the text required. the image. (This forms the 'alt' attribute for the image
2 Click one of the list buttons on the Format Toolbar. The and provides text which will appear in place of the image
text will be changed into a list, a new item starting for with user agents (browsers) that cannot display images
each paragraph or other block item encountered. (screen readers and voice synthesisers). It will also be
used by those with visual impairment. The content of
To add items to a list this box must be carefully considered so as to be of
maximum assistance in such cases.) Note Where the
1 Click at the end of the last item in the list. image is purely decorative, and not necessary to
2 Press Enter and type the new item. Numbering and understanding the page, alternative text is not required
format will continue from the previous item. and should be omitted
5 In the box labelled 'Tooltip' you may optionally insert a
Importing text 'Title' attribute for the image. Some browsers will show
Strictly KompoZer does not support importing text from the text provided when the cursor hovers over the image
other applications but it is possible to copy and paste text. 6 Click OK
In normal view content from other web pages may be copied
reliably. The result will be rendered according to any styling Using tables
applied in your document; any reliance on external styles
in the original document will be lost. Tables allow data - images, links, forms, form fields, text,
Text from word processors such as Microsoft Word or etc. - to be arranged into rows and columns of cells.
OpenOffice.org in rtf or doc format or from text editors such Inserting tables
as Windows notepad may also be copied and pasted.
When such text is pasted into KompoZer most formatting 1 On the Composition Toolbar click the Table button. The
is lost. Numbered lists will be retained. 'Insert table' window appears
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 63
Copyright @ NIMI Not to be Republished
2 Leave the 'Quickly' tab selected and drag out a matrix Inserting named Anchors
then click the bottom right cell to define the table
arrangement There is a second type of Anchor element the 'Named
anchor'. Such an anchor is extremely useful as it can act
3 The cells appear on the screen with narrow outlines
as a type of bookmark defining a particular place on a page.
Links can jump to such bookmarks.
Note: If later the table border is set to zero these
outlines disappear but KompoZer in normal
To insert a named anchor
view replaces them with a red outline. This
does not appear in Preview or in a browser.
1 Place the cursor at the point you want to mark.
Tables have resizing boxes similar to those
used with images 2 Click the 'Anchor' button on the Composition toolbar or,
on the Menu Bar, select Insert > Named Anchor. The
Table cell properties named anchor properties window appears.
3 Enter a unique name for the anchor.
Right-click the table and select 'Table Cell properties'. The
Table properties window opens. This has two tabs 'Table' 4 Click OK. In 'Normal' view anchors are marked by a
and 'Cells' which allow overall control of several aspects of picture of an anchor .
either the table or individual cells. This includes
Linking to named anchors
a Alignment of text within cells
b Wrapping of text Start as above for linking to another file. When the 'Link
Properties' window opens, instead of choosing file use the
c Cell spacing - the gap between cells
drop down list. Your anchor name should appear there
d Cell padding - the gap between the edge of the cell and preceded by a "#". Click it and OK. That's it! If you test your
the text within it page on a browser when you click the link the view should
move to show the position of the anchor.
e Size of table and cells
f Background colour Linking images
g Selection of cells as 'Normal' or 'Header' (Cells which
The techniques and possibilities are very similar to those
are headings to rows or columns should be selected as
used with text.
'Header'. Normally this results in them being rendered
in bold type.) To create a link
Linking text 1 Click on the image
2 On the Composition toolbar click on the 'Link' button,
Linking to another file
alternatively Right-click and select 'Create Link'. The
'Image Properties' window opens
To create a link
3 Click on 'Choose File' and browse to the file that you
1 Select (highlight) a few words of text want to link to. (The box 'URL is relative to page location'
is checked. This means that if you move your page to
2 On the Composition toolbar click on the 'Link' button,
a new folder you should move the image to a
alternatively Right-click and select 'Create Link'. The
corresponding new folder. If you clear this box the
'Link Properties' window opens
absolute address of the image on the hard drive is given
3 Click on 'Choose File' and browse to the file that you in full. If you move your page now it will look there for the
want to link to image. As you start to organise a web site you will find
4 Click OPEN that this is not a good arrangement and potentially
disastrous when you upload the page to a server.)
5 Click OK
4 Click OPEN
Inserting an email address
5 Click OK
Instead of linking to a file it is possible to insert an email
address. The result will be that, in use, when the link is Editing Links
clicked the email client on the visitor's machine will be
To change the file to which a link refers, in Normal, Tags or
opened with the correct address selected.
Preview mode double-click on the link. The 'Link properties'
To do so proceed as under the previous heading. When the window opens (for an image the 'Image Properties' window
Link Properties window opens (or if Image Properties click opens - click the Link tab). Edit the link.
the Link tab) enter the email address and check the box
To remove the link delete the link reference in the box.
'The above is an email address'.
64 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B
Copyright @ NIMI Not to be Republished
Frames e.g. against level 1 select h3 and against level 2 select
h4 and for all the others select '--'
If you open a frame document, you get a message 'This
5 If, instead of using headings you wish to use classed
page can't be edited for an unknown reason' but it displays
paragraphs or a div, instead of selecting a heading tag
the frame content rather beautifully. Then you can do
select 'p' or 'div' and in the box in the column headed
nothing with it except click on the 'Source' tab. You then
'Class' enter the class required. (It is, of course, also
see the source code and the system will seem to lock up.
possible to select headings by allocating a class.)
Actually it doesn't lock and you can load another page and
revert to normal operation. 6 If you wish the contents to be numbered check the box
'Number all entries ...'
This is not a great limitation. Though the code for frames
7 Click OK
takes a little getting used to it is usually quite short and can
easily be produced using a text editor. Once established
The Table of Contents will be created.
it probably rarely needs to be altered. You can use
KompoZer to develop the pages that go into the frames. To update a ToC
Forms
After changes have been made to a page. There is no need
to place the cursor.
To set up a form
1 Click Insert > Table of Contents > Update
1 Click the form button.
2 The 'Table of Contents' window appears showing the
2 In the Form properties window give the form a name of
selections previously made
your choosing
3 If desired, changes may be made to the selections
3 Complete the Action box with the correct URL and
select the appropriate method 4 To update the ToC click OK
4 'Encoding' and 'Target Frame' will frequently not be To delete a ToC
required but, if they are, select 'More Properties' and
complete the boxes There is no need to place the cursor.
5 Click OK
1 Click Insert > Table of Contents > Remove
6 On the form place any headings, paragraphs and
images ensuring that there is a placeholder for any Style and stylesheets
controls needed. (If blank placeholders are needed it is
probably sensible to put some dummy text in now and Styles specify how particular elements on a page appear
delete it later.) on the screen, in print or whatever. Style may typically
7 Where controls are needed click the corresponding define aspects of presentation as the font face, size and
placeholder and using the drop down box beside the variant, the font colour, the background colour, whether an
Form button select the required control element is to be aligned right, centre or left, whether
spaced away from other elements, surrounded by a border
8 Give each control a unique name and, if so, what type or colour. Elements may be given an
9 Each control has specific information which needs to be absolute position relative to the page (which allows elements
entered. Enter it into the box in the window which to overlap).
appears Elements such as paragraphs, tables and images are
Table of contents considered to exist within boxes or blocks and the sizes of
these boxes may be specified.
If you have a long document with sections headed using
heading formats Heading 1, Heading 2 etcKompoZer can Classes As well as allowing you to specify the style of
generate a Table of Contents (ToC) automatically. The elements it is possible to define styles and apply them
table reflects the structure of the page, the content of the selectively to only some elements. This is done through
headings forming the text of the table. 'Classes' - a 'Class' is just a style that can be applied as and
when you choose. 'Classes' are applied to 'Tags' (a marker
Inserting a Table of Contents attached to an element). The element to which the class is
applied appears in the format defined by the class. Other
1 Place the cursor where the table is required similar elements without the class applied appear in the
default format i.e. either the default specified by the
2 Click Insert > Table of Contents > Insert
browser or the style that the user has defined for the
3 The 'Table of Contents' window appears corresponding element. On the status bar KompoZer
shows classes along with the tag to which they are applied.
4 In the column headed 'Tag' select the tag for each level
Fig 2 shows Style Nomenclature.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 65
Copyright @ NIMI Not to be Republished
Fig 2 6 You are now presented with a window headed'Selector'
followed by the tag for the element. The window actually
lists the style declarations for that element, but of
course that is now blank.
Saving stylesheets
66 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B
Copyright @ NIMI Not to be Republished
Templates are not altered in use and can be used over and To create a page using Template
over again. The simplest template is probably a blank sheet
which links to a stylesheet for use throughout a site. More 1 Click File > New > A new document based on a
common is a page which has a banner and perhaps a menu template > Choose File.
to appear on every page. Last might be a complete page 2 Select the Template (Note templates have the file
layout for use on all, or many, pages of a site but which extension 'mzt')
includes areas for customising individually. Templates
may be considered as having two parts - the fixed part or 3 Click 'Create'.
'boilerplate' which remains the same for every page and the
'editable part' which changes. To use the page
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 67
Copyright @ NIMI Not to be Republished
Setting Preferences • HTTP address (URL) of your site. From your ISP (see
hints).
You can set up a number of features in KompoZer according
• Publishing address - This is the ftp address to which
to personal preferences. Several of the options are grouped
you will publish.
under the Tools >Optons menu. In addition you can
customise toolbars via the View > Show/hide menu. • User name - From your ISP.
• Password - From your ISP.
Defaults
• If you wish to, check 'Save Password'. If you have
The defaults set by KompoZer will generally be found several sites set up and you have one site that you
satisfactory. (Fig 4) always or usually publish to you may wish to click on
the name of this site then 'Set as default'. This simplifies
Fig 4
uploading. Click OK.
Uploading
68 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B
Copyright @ NIMI Not to be Republished
Other possible problems include Fig 6
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 69
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.102C
COPA - JavaScript and creating Web page
70
Copyright @ NIMI Not to be Republished
<div id ="myContainer"> How it Works
<div id ="myAnimation"></div>
The controls attribute adds video controls, like play, pause,
</div> and volume. It is a good idea to always include width and
height attributes. If height and width are not set, the page
<script>
might flicker while the video loads. The <source> element
function myMove() { allows you to specify alternative video files which the
var elem = document.getElementById("myAnimation"); browser may choose from. The browser will use the first
recognized format. The text between the <video> and </
var pos = 0; video> tags will only be displayed in browsers that do not
var id = setInterval(frame, 10); support the <video> element.
The HTML5 <audio> element specifies a standard way to File Format Media Type
embed audio in a web page.
MP3 audio/mpeg
The HTML <audio> Element
OGG audio/ogg
To play an audio file in HTML, use the <audio> element:
WAV audio/wav
Example
HTML Audio - Methods, Properties, and Events
<audio controls>
HTML5 defines DOM methods, properties, and events for
<source src="horse.ogg" type="audio/ogg"> the <audio> element. This allows you to load, play, and
<source src="horse.mp3" type="audio/mpeg"> pause audios, as well as set duration and volume. There
are also DOM events that can notify you when an audio
Your browser does not support the audio element. begins to play, is paused, etc.
</audio>
HTML5 Audio Tags
HTML Audio - How It Works
Tag Description
The controls attribute adds audio controls, like play,
pause, and volume. The <source> element allows you to <audio> Defines sound content
specify alternative audio files which the browser may
choose from. The browser will use the first recognized <source> Defines multiple media resources
format. The text between the <audio> and </audio> tags for media elements, such as
will only be displayed in browsers that do not support the <video> and <audio>
<audio> element.
72 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102C
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.1.103A & 2.1.103B
COPA - JavaScript and creating Web page
Introduction to IIS and XAMPP, Dynamic Website and Hosting and FTP tool
Filezilla - Projects in JavaScript
Objectives : At the end of this lesson you shall be able to
• describe XAMPP
• describe what is included in XAMPP
• describe FTP
• describe fileZilla
• describe a web project
• follow SDLC.
XAMPP has four primary components. These are: It is offered in both a full, standard version and a smaller
version.
1 Apache: Apache is the actual web server application
that processes and delivers web content to a computer. Use
Apache is the most popular web server online, powering
nearly 54% of all websites. Officially, XAMPP's designers intended it for use only as a
2 MySQL: Every web application, howsoever simple or development tool, to allow website designers and
complicated, requires a database for storing collected programmers to test their work on their own computers
data. MySQL, which is open source, is the world's most without any access to the Internet. To make this as easy
popular database management system. It powers as possible, many important security features are disabled
everything from hobbyist websites to professional by default. In practice, however, XAMPP is sometimes
platforms like WordPress. You can learn how to master used to actually serve web pages on the World Wide Web.
PHP with this free MySQL database for beginners A special tool is provided to password-protect the most
course. important parts of the package.
3 PHP: PHP stands for Hypertext Preprocessor. It is a XAMPP also provides support for creating and manipulating
server-side scripting language that powers some of the databases in MySQL and SQLite among others.
most popular websites in the world, including
WordPress and Facebook. It is open source, relatively Once XAMPP is installed, it is possible to treat a localhost
easy to learn, and works perfectly with MySQL, making like a remote host by connecting using an FTP client.
it a popular choice for web developers. Using a program like FileZilla has many advantages when
installing a content management system (CMS) like
4 Perl: Perl is a high-level, dynamic programming
Joomla or WordPress. It is also possible to connect to
language used extensively in network programming,
localhost via FTP with an HTML editor.
system admin, etc. Although less popular for web
development purposes, Perl has a lot of niche
The default FTP user is "newuser", the default FTP
applications.
password is "wampp". The default MySQL user is "root"
while there is no default MySQL password.
73
Copyright @ NIMI Not to be Republished
XAMPP 1.8.3-4 for Windows, includes the current specification. Several proposed standards
amend RFC 959, for example RFC 2228 (June 1997)
• Apache 2.4.9 proposes security extensions and RFC 2428 (September
• MySQL 5.6.16 1998) adds support for IPv6 and defines a new type of
passive mode.
• PHP 5.5.11
Login
• phpMyAdmin 4.1.12
• FileZilla FTP Server 0.9.41 FTP login utilizes a normal username and password
• Tomcat 7.0.42 (with mod_proxy_ajp as connector) scheme for granting access. The username is sent to the
server using the USER command, and the password is
• Strawberry Perl 5.16.3.1 Portable sent using the PASS command. If the information provided
• XAMPP Control Panel 3.2.1 (from hackattack142) by the client is accepted by the server, the server will
send a greeting to the client and the session will
XAMPP 1.8.3-4 for Linux, includes commence. If the server supports it, users may log in
without providing login credentials, but the same server
• Apache 2.4.9 may authorize only limited access for such sessions.
74 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B
Copyright @ NIMI Not to be Republished
Web browser support Secure FTP
Most common web browsers can retrieve files hosted on Securing FTP transfers may be accomplished by several
FTP servers, although they may not support protocol methods.
extensions such as FTPS. When an FTP-rather than an
HTTP-URL is supplied, the accessible contents on the FTPS
remote server are presented in a manner that is similar to
that used for other Web content. A full-featured FTP client Explicit FTPS is an extension to the FTP standard that
can be run within Firefox in the form of an extension called allows clients to request that the FTP session be
FireFTP. encrypted. This is done by sending the "AUTH TLS"
command. The server has the option of allowing or denying
Syntax connections that do not request TLS. This protocol
extension is defined in the proposed standard: RFC 4217.
FTP URL syntax is described in RFC1738, taking the form: Implicit FTPS is a deprecated standard for FTP that required
ftp://[<user>[:<password>]@]<host>[:<port>]/<url-path> the use of a SSL or TLS connection. It was specified to
The bracketed parts are optional. use different ports than plain FTP.
• Packet capture (sniffing) Otherwise, it is necessary for the SSH client software to
have specific knowledge of the FTP protocol, to monitor
• Port stealing
and rewrite FTP control channel messages and
• Spoof attacks autonomously open new packet forwardings for FTP data
• Username protection channels. Software packages that support this mode
include:
FTP does not encrypt its traffic; all transmissions are in
clear text, and usernames, passwords, commands and • Tectia ConnectSecure (Win/Linux/Unix) of SSH
data can be read by anyone able to perform packet capture Communications Security's software suite
(sniffing) on the network. This problem is common to many • Tectia Server for IBM z/OS of SSH Communications
of the Internet Protocol specifications (such as SMTP, Security's software suite
Telnet, POP and IMAP) that were designed prior to the
creation of encryption mechanisms such as TLS or SSL. • FONC (the GPL licensed)
A common solution to this problem is to use the "secure", • Co:Z FTPSSH Proxy
TLS-protected versions of the insecure protocols (e.g.
FTPSfor FTP, TelnetS for Telnet, etc.) or a different, more Other methods of transferring files using SSH that are not
secure protocol that can handle the job, such as the SFTP/ related to FTP include SFTP and SCP; in each of these,
SCP tools included with most implementations of the the entire conversation (credentials and data) is always
Secure Shellprotocol. protected by the SSH protocol.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B 75
Copyright @ NIMI Not to be Republished
FILEZILLA The SDLC adheres to important phases that are essential
for developers, such as planning, analysis, design, and
FileZilla is a free FTP solution. Both a client and a server implementation, and are explained in the section below. It
are available. FileZilla is open source software distributed includes evaluation of present system, information
free of charge under the terms of the GNU General Public gathering, feasibility study and request approval. A number
License. Using FileZilla files can be uploaded or of SDLC models have been created: waterfall, fountain,
downloaded from client to server and vice-versa. It is very spiral, build and fix, rapid prototyping, incremental, and
user friendly and no commands are required to do upload synchronize and stabilize. The oldest of these, and the
and download operations. Files can be uploaded or best known, is the waterfall model: a sequence of stages
downloaded by simple drag-drop operations. in which the output of each stage becomes the input for
the next. These stages can be characterized and divided
Designing a Web Project: A project in Web should be up in different ways, including the following:
developed after comprehensive enquiry about what exactly
the client/end user want. For this some meeting can be • Preliminary analysis: The objective of phase 1 is to
arranged with clients to find out the exact requirement of conduct a preliminary analysis, propose alternative
the client. This is called SRS(System Requirement solutions, describe costs and benefits and submit a
Specification). preliminary plan with recommendations.
Some methods are followed for SRS, which are giving some • Conduct the preliminary analysis: in this step, you
questions abount the system to the clients and verifying need to find out the organization's objectives and the
the answer to gauge the requirement of the clients. Showing nature and scope of the problem under study. Even if a
them some demo screen to get their response. Collecting problem refers only to a small segment of the
the reports they use to understand the type of data they organization itself then you need to find out what the
use. objectives of the organization itself are. Then you need
to see how the problem being studied fits in with them.
Before development of any system or project, SRS is very
• Propose alternative solutions: In digging into the
important as if you cannot understand the exact user
organization's objectives and specific problems, you
requirement, then the system/project developed by you
may have already covered some solutions. Alternate
with lot of man hours spent on it would be totally wasted
proposals may come from interviewing employees,
and the project would be scraped.
clients, suppliers, and/or consultants. You can also
SDLC: The systems development life cycle (SDLC), also study what competitors are doing. With this data, you
referred to as the application development life-cycle, is a will have three choices: leave the system as is, improve
term used in systems engineering, information systems it, or develop a new system.
and software engineering to describe a process for Describe the costs and benefits.
planning, creating, testing, and deploying an information
system. (Fig 1) • Systems analysis, requirements definition: Defines
project goals into defined functions and operation of
Fig 1 the intended application. Analyzes end-user information
needs.
• Systems design: Describes desired features and
operations in detail, including screen layouts, business
rules, process diagrams, pseudo code and other
documentation.
• Development: The real code is written here.
• Integration and testing: Brings all the pieces together
into a special testing environment, then checks for
errors, bugs and interoperability.
• Acceptance, installation, deployment: The final
stage of initial development, where the software is put
into production and runs actual business.
• Maintenance: During the maintenance stage of the
SDLC, the system is assessed to ensure it does not
become obsolete. This is also where changes are made
The system development life cycle framework provides a to initial software. It involves continuous evaluation of
sequence of activities for system designers and developers the system in terms of its performance.
to follow. It consists of a set of steps or phases in which
each phase of the SDLC uses the results of the previous
one.
76 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B
Copyright @ NIMI Not to be Republished
• Evaluation: Some companies do not view this as an • Disposal: In this phase, plans are developed for
official stage of the SDLC, but is it an important part of discarding system information, hardware and software
the life cycle. Evaluation step is an extension of the in making the transition to a new system. The purpose
Maintenance stage, and may be referred to in some here is to properly move, archive, discard or destroy
circles as Post-implementation Review. This is where information, hardware and software that is being
the system that was developed, as well as the entire replaced, in a matter that prevents any possibility of
process, is evaluated. Some of the questions that need unauthorized disclosure of sensitive data. The disposal
to be answered include: does the newly implemented activities ensure proper migration to a new system.
system meet the initial business requirements and Particular emphasis is given to proper preservation and
objectives? Is the system reliable and fault-tolerant? archival of data processed by the previous system. All
Does the system function according to the approved of this should be done in accordance with the
functional requirements? In addition to evaluating the organization's security requirements.
software that was released, it is important to assess
In the following example (Fig 2) these stages of the
the effectiveness of the development process. If there
systems development life cycle are divided in ten steps
are any aspects of the entire process, or certain stages,
from definition to creation and modification of IT work
that management is not satisfied with, this is the time
to improve. Evaluation and assessment is a difficult products:
issue. However, the company must reflect on the
process and address weaknesses.
Fig 2
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B 77
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.104
COPA - Programming with VBA
Common Uses of VBA As macros are the heart of VBA, there is always a threat
of macro viruses embedded in them. Unless proper steps
• Customizing and extending the functionality of the are taken to prevent this misuse, the application may be
Application in which it is used. targeted in a potentially unsafe manner.This can be tackled
by using proper antivirus products and verifying the
• Automating a task you perform frequently Ex. Monthly certificates of the embedded macros.
reports etc.
• Automating repetitive operations Ex. repeating a set of Common Terms used in Excel VBA
actions on many workbooks
Object oriented programming
• Creating a custom command for ex. one that combines
many commands to make the work faster The word Object is used to describe just about everything
• Creating user interactive forms and controls like buttons in Excel. In Excel, an Object can be Form, Button, Chart
to which macros or code can be assigned or even the Visual Basic Editor (VBE) itself.
• Customizing the Quick Access Toolbar with your own In object-oriented programming, a class is a code element
buttons that execute the macros you write. that defines an object. A good analogy for a class module
• Developing new worksheet functions that can greatly is the specification that defines a Window, Button or a
simplify your formulas. Sheet etc. You create an object using the class as its
specification. A Class is therefore a template from which
• Creating complete, macro-driven applications. objects are created. Objects can be treated as instances
• Creating custom add-ins for Excel of Classes. You add code to the class module to define
the object's properties and methods. Modifying the code
Some of the common applications of VBA are: in a class module modifies how the object defined by the
class module behaves.
• Keeping lists of things such as employees' details,
customers'records, students' grades etc. In the Object Hierarchy, at the top is the Application Object,
ie. Excel here. Next in this order is Workbook Object e.g.;
• Customized data entry with subsequent actions
Book1.xlsx. Directly underneath the Workbook Object
included
comes the Worksheet Object. At the Worksheet Object
• Budgeting and forecasting the Object Hierarchy branches off to incorporate all Objects
of the Worksheet. The first one you will most likely
• Data Analysis
encounter will be the Range Object. Branching from the
78
Copyright @ NIMI Not to be Republished
Range Object there are again many other objects such as Methods
the Areas Object, the Borders Object, Font Object,
Characters, etc. In brief, the hierarchy is as follows: A Method is simply a procedure that acts on an Object. It
makes the Object do something, like opening a Workbook
• Application or deleting a Worksheet etc. Examples of some methods
of VBA objects are the Activate, Copy, Delete, Save
• Workbook
methods of the Worksheet, the Add Item and clear methods
• Worksheet of the combo Box and list box etc.
• Range
Events
When you have a group of Objects that are related, this is
then known as a "Collection". So when we use the term An Event in Excel VBA is the reason or trigger for an
Workbooks, we are referring to all open Workbooks, and action to take place. For example a mouse click is an
when we use the term Workbook, we are only referring to event, Double Clicking an object is an event, closing or
an individual Workbook (the active Workbook). opening of a Workbook are also events. The action to be
taken when the event occurs is written as code in the
Properties event procedure. Examples of events are the Click,
DoubleClick events of Buttons, Scroll, and Change Events
Properties are attributes of an Object. They are used to of the Scroll Bar etc.
define an Objects characteristics. For example; the
Worksheet Object has many Properties, one of which Modules
would be its name. By changing the Visible Property, we
may hide or unhide it. To be able to change the Property Modules are containers for holding VBA code. Modules
of any Object we must first identify the Object whose can contain declarations and procedures. VBA code that
Property we wish to change. Examples of properties are is placed in one or more modules can be called from an
height, width, font color, name etc. to name a few. Office application to perform a specified task.
A macro is a set of commands bundled together under 1 Object navigation box-Used to select the object to work
one name. These logically pre-recorded commands can with
be re executed at any later stage to repeat the task they
2 Declarations/Procedure navigation box-Used to
were designed for. Macros simplify the work by eliminating
navigate to the general declarations section or to a
rewriting the code or repeating the same steps in case of
particular procedure
frequently needed actions. The advantage with macros is
that they can be designed even by a person not knowing 3 Declarations-Contains the declarations for the module
much of programming. The macro recording tool provided
4 Procedures-Contains the sub procedures and functions
in all Office applications facilitates this. All that is needed
for the module
is specifying a name and recording the steps in a
sequence. A person with a knowledge of programming on There are two types of modules: standard modules and
the other hand can either write a macro code directly, or class modules.
even edit code of the existing macros. In VBA, macros
can be assigned to controls like buttons to make the Standard modules are modules that contain procedures
application user friendly. that are not associated with any particular object.
Fig 1
All Excel files containing VBA code or macros must be Debugging is one of the most important skills for a
saved as type "Excel Macro Enabled WorkBook.xlsm" developer. Software development is all about writing code,
for the macros to be preserved. spotting the mistakes, and fixing them.
You may have to sometimes "Enable Macros" on reopening VBA offers very powerful debugging tools during
the files containing Macros when prompted else the code development, with the ability to add error handling routines
will not be effective. to help debug deployed/remote applications.
80 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.104
Copyright @ NIMI Not to be Republished
Debugger Step Out [Ctrl Shift F8]
There are several parts of the debugger that work together Run the current procedure and go to the line after the line
to let you analyze how your code runs: that called the procedure. This is basically a way to simplify
the debugging process by letting you skip the remainder
• Integrated Development Environment (IDE) of the current procedure once you realize you don't need
to step into it any more.
• Breakpoints
• Stepping Through and Over Code Set Next Statement [Ctrl F9]
Integrated Development Environment (IDE)
This command lets you set the next statement as any
line in the current procedure including lines you've already
From the IDE, there are several things you can do:
run. It is particularly useful if you run though some code
Current Definition [Shift F2] and then decide you should repeat it because you missed
something.
Put the cursor on the variable, procedure, or property in
question and press [Shift F2] to see where it's defined. Show Next Statement
You'll jump directly to it. You can do this as often as you
like to understand how your code works. Press [Ctrl Shift Sometimes you examine different procedures as you debug
F2] to go back to where you came. your code, so the Show Next Statement menu command
makes it easy to go to the currently highlighted line.
Run the Current Procedure
Debugging Views
Highlight the procedure you want to run and press [F5] to
run it. If you want to step into it line-by-line, press [F8]. Of In addition to seeing which line of code runs and evaluating
course, running a procedure this way only works if you variables as you debug, there are several other views that
don't have to pass parameters to it. If you need to, consider help you diagnose your development environment:
using the Immediate Window.
• Call Stack
Breakpoints • Immediate Window
Breakpoints are placed on the lines in your code so the • Locals Window
debugger is invoked when the program tries to execute • Watch Window
that line. A breakpoint can be placed on any line that is
actually run (not lines in the General Declarations section, Call Stack [Ctrl L]
or lines that define variables in a procedure). This is an
extremely powerful technique to let you run your code The call stack keeps track of the procedure calling chain
normally until the section you're interested in is so you can easily see how you got to the current procedure
encountered. through all the other procedures. Retrieve it under View,
Call Stack, or press [Ctrl L].
Breakpoints can be added by moving to the line desired
and pressing F9, clicking with the mouse on the left border, From this dialog, you can click on any procedure and
or from the Debug menu. Multiple breakpoints can be jump immediately to it. Before analyzing the details of the
added during your debugging session. Breakpoints are current procedure, it may be more important to understand
temporary and are automatically removed when you close how and why you got there since the problem may be
the VBA. there rather than in the current procedure.
The debugger gives you a variety of techniques to step This is the most basic debugging area. You can use the
through your code: Immediate Window whether your code is running or not.
Open the Immediate Window by pressing [Ctrl+G] or
Step Into [F8] selecting it from the IDE menu under View. The Immediate
window lets you:
Run the current line and go to the next one.
• Evaluate expressions unrelated to your code (e.g. math
Step Over [Shift F8] equations)
• Evaluate variables or expressions in your code (e.g. a
Used for a line that calls a procedure to run that procedure
current variable value)
without going into it. The command lets you run the
procedure (and any procedures it may call), and go to the • Run code
next line in the calling procedure.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.104 81
Copyright @ NIMI Not to be Republished
For items that return a value, use a question mark followed Watch Window
by the expression. For instance:? 14/5 then click Enter to
see the value. If your code is currently running and stopped, The Watch Window is similar to the Locals Window, but
you can use this method to evaluate the current value of a you specify the variables you want to track. You can track
variable: ? pay variables across modules and procedures and keep them
in your Watch Window to see their value no matter where
Locals Window the current line is.
You can see all the local variables by selecting Locals The first step is to add a variable to the Watch Window.
Window from the Views menu. This displays the entire This can be done by placing the cursor in the variable you
list of local variables and their current values. Local variables want to track, and selecting Debug, Add Watch, or from
are variables defined in the current procedure and module the right-click menu, selecting Add Watch. The current
declaration section. variable is added to the Expression section, and the current
procedure and module added to the Context sections. You
You can modify the value held by a variable by clicking on can also add expressions, and options to break when the
the Value column and editing it. This is an alternative to value changes. This is particularly useful when you are
modifying values from the Immediate Window. having trouble determining why a particular situation arises
in your application.
82 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.104
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.105A - 2.2.105D
COPA - Programming with VBA
You can display or view controls and objects alongside You can also run macros by using Form controls. You
associated text that is independent of row and column can attach an existing macro to a control, or write or record
boundaries without changing the layout of a grid or table a new macro. When a user of the form clicks the control,
of data on your worksheet. Many of these controls can the control runs the macro.
also be linked to cells on the worksheet and do not require
VBA code to make them work. You can set properties However, these controls cannot be added to UserForms,
that determine whether a control floats freely or moves used to control events, or modified to run Web scripts on
and resizes together with a cell. For example, you might Web pages. The Summary of form controls is given in
have a check box that you want to move together with its Table 1.
underlying cell when the range is sorted.
ActiveX controls
Excel has two types of controls: Form controls and ActiveX
Controls (Refer Fig 1). ActiveX controls can be used on worksheet forms, with or
without the use of VBA code, and on VBA UserForms. In
Fig 1 general, use ActiveX controls when you need more flexible
design requirements than those provided by Form controls.
ActiveX controls have extensive properties that you can
use to customize their appearance, behavior, fonts, and
other characteristics.
83
Copyright @ NIMI Not to be Republished
Table 1
Label Identifies the purpose of a cell or text box, or displays descriptive text (such
as titles, captions, pictures) or brief instructions.
Group box Groups related controls into one visual unit in a rectangle with an optional
label. Typically, option buttons, check boxes, or closely related contents are
grouped.
Button Runs a macro that performs an action when a user clicks it. A button is also
referred to as a push button.
Check box Turns on or off a value that indicates an opposite and unambiguous choice.
You can select more than one check box on a worksheet or in a group box. A
check box can have one of three states: selected (turned on), cleared (turned
off), and mixed, meaning a combination of on and off states (as in a multiple
selection).
Option button Allows a single choice within a limited set of mutually exclusive choices; an
option button is usually contained in a group box or a frame. An option button
can have one of three states: selected (turned on), cleared (turned off), and
mixed, meaning a combination of on and off states (as in a multiple selection).
An option button is also referred to as a radio button.
List box Displays a list of one or more items of text from which a user can choose.
Use a list box for displaying large numbers of choices that vary in number or
content. There are three types of list boxes:
A single-selection list box enables only one choice. In this case, a list box
resembles a group of option buttons, except that a list box can handle a large
number of items more efficiently.
A multiple-selection list box enables either one choice or contiguous (adjacent)
choices.
An extended-selection list box enables one choice, contiguous choices, and
non-contiguous (or disjointed) choices.
Combo box Combines a text box with a list box to create a drop-down list box. A combo
box is more compact than a list box but requires the user to click the down
arrow to display the list of items. Use a combo box to enable a user to either
type an entry or choose only one item from the list. The control displays the
current value in the text box, regardless of how that value is entered.
Scroll bar Scrolls through a range of values when you click the scroll arrows or drag the
scroll box. In addition, you can move through a page (a preset interval) of
values by clicking the area between the scroll box and either of the scroll
arrows. Typically, a user can also type a text value directly into an associated
cell or text box.
Spin button Increases or decreases a value, such as a number increment, time, or date.
To increase the value, click the up arrow; to decrease the value, click the
down arrow. Typically, a user can also type a text value directly into an
associated cell or text box.
Your computer also contains many ActiveX controls that However, Active X controls cannot be added to chart sheets
were installed by Excel and other programs, such as from the user interface or to XLM macro sheets. You also
Calendar Control 12.0 and Windows Media Player. cannot assign a macro to run directly from an ActiveX
control the same way you can from a Form control. The
Not all ActiveX controls can be used directly on worksheets, summary of the Active X controls is given in Table 2. The
some can be used only on Visual Basic for Applications properties and events of commonly used ActiveX controls
(VBA) UserForms. If you try to add any one of these are shown in Table 3.
particular ActiveX controls to a worksheet, Excel displays
the message "Cannot insert object."
84 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.105A - 2.2.105D
Copyright @ NIMI Not to be Republished
Table 2
IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.105A - 2.2.105D 85
Copyright @ NIMI Not to be Republished
Table 3
Control Name Properties in addition to the Some of the common events for the control
applicable properties mentioned
above
Text box Maxlength, MultiLine, Password Change, DBLClick, GotFocus, LostFocus, KeyPress
C haracter, ScrollBars, Text, etc
TextAlign, WordWrap etc.
Command button Picture,Shadow, WordWrap etc. Click, DBLClick, GotFocus, LostFocus, KeyPress etc
List box BoundColumn, ColumnCount, Change, Click, DBLClick, GotFocus, LostFocus etc.
LinkedCell, ListFillRange, ListStyle,
MatchEntry, Multiselect etc.
Methods: AddItem, Clear, RemoveItem
Combo box BoundColumn, ColumnCount, Change, Click, DBLClick, GotFocus, LostFocus etc.
LinkedCell, ListFillRange, ListStyle,
MatchEntry, Matchrequired,
Multiselect, Style etc.
Toggle button TripleState, Value etc Change, Click, DBLClick, GotFocus, LostFocus etc.
Spin button Delay, LargeChange, Max, Min, Change, SpinDown, SpinUp, GotFocus, LostFocus,
Orientation, SmallChange, Value etc. KeyPress etc.
Scroll bar Delay, LargeChange, Max, Min, Change, Scroll, GotFocus, LostFocus, KeyPress etc.
Orientation, SmallChange, Value etc.
Methods: LoadPicture(RunTime)
The 'Design Time Properties" common to most of the In addition to these Methods certain functions / methods
controls are Name, Autoload, Backcolor, BackStyle, allow setting the properties at "Run Time", ie. through code.
BorderColor, BorderStyle, Enabled, Font, ForeColor,
Height, Left, Top, Visible, Width etc.
86 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.105A - 2.2.105D
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.106A & 2.2.106B
COPA - Programming with VBA
A collection is a series of items where each item has the The Workbook object is a member of the Workbooks
same characteristics. In other words, all items can be collection. The Workbooks collection contains all the
described the same way. Programmatically, a collection Workbook objects currently open in Microsoft Excel.
is a series of items where all items share the same
properties and methods, if any. For example, if you want ‘This’ Workbook Property
to loop through all worksheets in a workbook, you can
refer worksheets collection of the workbook and use the The ThisWorkbook property returns the workbook where
worksheet. Collections are a powerful feature in VBA. One the Visual Basic code is running. In most cases, this is
of the most used, functions of Collections is their ability to the same as the active workbook. However, if the Visual
provide you with a unique list. Basic code is part of an add-in, the ThisWorkbook property
won't return the active workbook. In this case, the active
Collections can hold a lot of data with one variable. The workbook is the workbook calling the add-in, whereas the
data in a Collection does not have to be the same type, ThisWorkbook property returns the add-in workbook. If you'll
like using a Variant array. Also, you don't have to allocate be creating an add-in from your Visual Basic code, you
memory for Collections like you do for arrays. You simply should use the ThisWorkbook property to qualify any
add items to the collection and the memory is allocated statement that must be run on the workbook you compile
dynamically. into the add-in.
A Collection object has four methods (and no properties). Some of the properties of Workbook are shown in
They are Add, Count, Item, and Remove. Charts, Table 1.
Workbooks, Shapes are some of the collections in VBA.
Table 1
Full Name Returns the name of the object, including its path on disk, as a string. Read-only String.
Name Returns a String value that represents the name of the object.
Path Returns a String that represents the complete path to the workbook/file that this workbook
object respresents.
Worksheets Returns a Sheets collection that represents all the worksheets in the specified workbook.
Read-only Sheets object.
Table 2
87
Copyright @ NIMI Not to be Republished
Some of the events of WorkBook are shown in Table 3.
Table 3
Activate Occurs when a workbook, worksheet, chart sheet, or embedded chart is activated.
Application When used without an object qualifier, this property returns an Application object that
represents the Microsoft Excel application. When used with an object qualifier, this property
returns an Application object that represents the creator of the specified object (you can use
this property with an OLE Automation object to return the application of that object). Read-
only.
Cells Returns a Range object that represents all the cells on the worksheet (not just the cells that are
currently in use).
Columns Returns a Range object that represents all the columns on the active worksheet. If the active
document isn't a worksheet, the Columns property fails.
Rows Returns a Range object that represents all the rows on the specified worksheet. Read-only
Range object.
Index Returns a Long value that represents the index number of the object within the collection of
similar objects.
Name Returns or sets a String value that represents the object name.
Visible Returns or sets an XlSheet Visibility value that determines whether the object is visible.
Table 5
88 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.106A & 2.2.106B
Copyright @ NIMI Not to be Republished
Some of the events of WorkSheet are shown in Table 6
Table 6
Activate Occurs when a workbook, worksheet, chart sheet, or embedded chart is activated.
Calculate Occurs after the worksheet is recalculated, for the Worksheet object.
Change Occurs when cells on the worksheet are changed by the user or by an external link.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.106A & 2.2.106B 89
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.107A
COPA - Programming with VBA
90
Copyright @ NIMI Not to be Republished
Table 1
Data Types: In VBA, numeric data are divided into 7 types, depending
on the range of values they can store. Calculations that
Visual Basic classifies data into two major categories, only involve round figures or data that does not need
the numeric data types and the non-numeric data types. precision can use Integer or Long integer in the
computation. Programs that require high precision
Numeric data types are types of data that consist of calculation need to use Single and Double decision data
numbers, which can be computed mathematically with types, they are also called floating point numbers. For
various standard operators such as +, -, x, / and more. currency calculation, you can use the currency data types.
Examples of numeric data types are examination marks, Lastly, if even more precision is required to perform
height, weight, the number of students in a class, share calculations that involve many decimal points, we can use
values, price of goods, monthly bills, fees and others. the decimal data types. These numeric data types
summarized in Table 2.
Table 2
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107A 91
Copyright @ NIMI Not to be Republished
Non Numeric Data Types data types, the Date data types, the Boolean data types
that store only two values (true or false), Object data type
Non-numeric data types are data that cannot be and Variant data type.The non numeric data types are
manipulated mathematically using standard arithmetic summarized in Table 3.
operators. The non-numeric data comprises text or string
Table 3
If you have a set of unchanging values that are logically Literals are values that you assign to data. In some cases,
related to each other, you can define them together in an we need to add a suffix to a literal so that VB can handle
enumeration. This provides meaningful names for the the calculation more accurately. For example, we can use
enumeration and its members, which are easier to pay=12000@ for a Currency type data. Some of the suffixes
remember than their values. You can then use the are displayed in Table 4.
enumeration members in many places in your code.
Table 4
An enumeration has a name, an underlying data type,
and a set of members. Each member represents a Suffix Data Type
constant.
& Long
The Enum statement can declare the data type of an
enumeration. Each member takes the enumeration's data ! Single
type. You can specify Byte, Integer, Long etc..If you do
not specify datatype for the enumeration, each member # Double
takes the data type of its initializer. If you specify both
datatype and initializer, the data type of initializer must be @ Currency
convertible to data type. If neither datatype nor initializer
is present, the data type defaults to Integer.
Note: Enclose string literals within two
Ex. quotations
Public Enum OS Enclose date and time literals within two # symbols. Ex:
92 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107A
Copyright @ NIMI Not to be Republished
If the data type is not specified, VB will automatically Variable = Expression
declare the variable as a Variant.
The variable can be a declared variable or a control's
Named Constants property value. The expression could be a mathematical
expression, a number, a literal value, a string, a Boolean
If you have a value that never changes in your application, value (true or false) , a combination of other variables and
you can define a named constant and use it in place of a constants, a function and more. The following are some
literal value. A name is easier to remember than a value. examples:
You can define the constant just once and use it in many
places in your code. If in a later version you need to redefine Basic = 10000
the value, the Const statement is the only place you need
to make a change. DA = Basic * 0.9
You can use Const only at module or procedure level. First Name = "Uma"
This means the declaration context for a variable must be
a class, structure, module, procedure, or block, and cannot Label1.Caption = "Enter your age"
be a source file, namespace, or interface
Command 1 Visible = false
Example:Const Pi As Single=3.142
Textbox.multiline = True
Assigning Values to Variables
Label 1 Caption = textbox1.Text
After declaring various variables using the Dim keywords
or other keywords, we need to assign values or information A type mismatch error occurs when you try to assign a
to those variables. Assigning a value to a variable means value to a variable of incompatible data type.
storing the value in that variable. The form of an assignment
statement is as follows:
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107A 93
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.107B
COPA - Programming with VBA
The Comparison Operators Table 1 Assume variable A holds 10 and variable B holds
20, the results of various comparison operators as shown
There are following comparison operators supported by
VBA.
Table 2
<> Checks if the value of the two operands are equal or not.
If the values are not equal, then the condition is true (A <> B) is True
> Checks if the value of the left operand is greater than the
value of the right operand. If yes, then the condition is true (A > B) is False
< Checks if the value of the left operand is less than the
value of the right operand. If yes, then the condition is true (A < B) is True
94
Copyright @ NIMI Not to be Republished
The Logical Operators Assume variable A holds 10 and variable B holds 0, the
results on the various logical operators shown in Table 3
Following logical operators are supported by VBA.
Table 3
The Concatenation Operators Assume variable A holds 5 and variable B holds 10, the
result of various concatenation operators shown in
Following Concatenation operators are supported by
Table 4
VBA.
Table 4
When operators have the same precedence they are The rules of precedence tell the compiler which operators
evaluated from left-to-right.Parentheses can be used to to evaluate first.
override the order and to evaluate certain parts of the
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107B 95
Copyright @ NIMI Not to be Republished
Parentheses can obviously be used to change the order Operators are evaluated in the following order:
of precedence. Mathematical, Concatenation, Relational, Logical.
Table 6
1 Exponentiation ^
2 Negation -
3 Multiplication *
3 Division /
5 Modulo Mod
6 Addition +
6 Subtraction -
8 Equal or Assignment =
9 Not NOT
10 And AND
11 Or OR
12 Exclusive OR XOR
13 Equivalence EQV
14 Implication IMP
96 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.107B
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.108
COPA - Programming with VBA
Many applications depend on data input from users to The Msgbox() can be customized by changing the buttons
take the necessary action. Excel VBA has very useful and icons placed on it.
functions that allow you to gather user input for your
applications. VBA allows you to create message boxes, A list of various buttons and icons that can be used in the
user input forms and input boxes to get user input.VBA VBA message box is shown in the Table 1.
message boxes provide a way to give information to a
user and get information from a user while the program is For ex. to add an icon and a title to the Msgbox() we can
running. The input Box function can be used to prompt the write the following code
user to enter a value.
Sub test()
Message Box
Dim n As Integer
In VBA Message Boxes fall into two basic categories, the
MsgBox method and the MsgBox function. n = MsgBox("Congratulations", vbExclamation, "result")
The message box method is used to display a pre- defined This will produce the following result as in Fig 2.
message to the user. It also contains a single command
button "OK" to allow the user to dismiss the message Fig 2
and they must do so before they can continue working in
the program.
Example:
Sub result()
Msgbox("congratulations")
End sub
97
Copyright @ NIMI Not to be Republished
Table 1
Constant Description
vbApplicationModal This suspends the current application till the user responds to the
message box.
vbSystemModal This suspends all the applications till the user responds to the message box.
Return Value: Indicates the action the user took when VBA MsgBox function returns a value based on the user
the message box was shown to him/her. input. These values can be anyone of the ones shown in
Table 2.
Prompt : It is the message contained in the main body of
the message box. A Msgbox function example is shown in the code
mentioned below.
Button and Icon Types : This specifies the set of buttons
& Icons and their placement as they would appear to the Sub test()
user.
Dim n As Integer
Help File : This is the path to a help file that the user can
refer to on this topic. n = MsgBox("Do you want to print this file?", vbYesNo,
"Action on Files")
Help File Context : This is the pointer to that part of the
help file that specifically deals with this message. End Sub
98 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.108
Copyright @ NIMI Not to be Republished
Table 2 Sub test()
1 Specifies that OK button is clicked. n = MsgBox("Did you score more than 50 % ", vbYesNo +
vbQuestion, "Result")
2 Specifies that Cancel button is clicked.
If n = 6 Then
3 Specifies that Abort button is clicked.
MsgBox ("Congratulations")
4 Specifies that Retry button is clicked.
Else
5 Specifies that Ignore button is clicked.
MsgBox ("Better Luck Next Time")
6 Specifies that Yes button is clicked.
End If
7 Specifies that No button is clicked.
End Sub
This will produce the result as in Fig 3.
Input box
Fig 3
For accepting the input from the user the Input box is
used in two ways- The Input Box Function and the Input
Box Method.The InputBox method differs from the InputBox
function in that it allows selective validation of the user's
input, and it can be used with Microsoft Excel objects,
error values, and formulas.
Based on the value returned by the MsgBox(), decisions InputBox(prompt[, title] [, default] [, xpos] [, ypos] [,
can be made. helpfile, context])
For ex, the code mentioned here will display the message In its simplest form , the input box function looks like:n =
box, and when the user clicks "Yes" it will display a Inputbox("Enter your Age")
congratulatory message. If the user clicks "No" another
message "Better Luck Next time" will appear as shown in The InputBox Method
Fig 4.
When we precede the Input Box Function with "Application"
we get an InputBox Method that will allow us to specify
Fig 4
the type of info that we can collect. Ie. Application.InputBox
Type:=0 A formula
Type:=1 A number
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.108 99
Copyright @ NIMI Not to be Republished
Type: = 4 A logical value (True or False) n = Application.InputBox("Enter you age", "Personal
Details", , , , , , 1)
Type: = 8 A cell reference, as a Range object
'Exit sub if Cancel button used
Type: = 16 An error value, such as #N/A
If n > 60 Then
Type := 64 An array of values
MsgBox "You are eligible for senior citizen's concession"
The following is an example of an InputBox method
Else
Sub test()
MsgBox ("No concession")
Dim n As Integer
End If
End Sub
100 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.108
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.109A - 2.2.109C
COPA - Programming with VBA
Decision making structures require that the programmer debug.print "Not Eligible"
specify one or more conditions to be evaluated or tested
by the program, along with a statement or statements to End If
be executed if the condition is found to be true, and other
statements to be executed if the condition is found to be The following example tests the value of the number in the
false.Table 1 shows the commonly used decision making textbox and takes a decision.
statements in VBA.
Private Sub Button1_Click()
The If … Then Statement
Dim n As Integer
It is the simplest form of control statement, frequently used
in decision making and changing the control flow of the 'Enter the number of items sold by the agent
program execution. Syntax for if-then statement is:
n = val(TextBox1.Text)
If CONDITION Then
If n> 100 Then
' code if the condition is met
Label1.Caption = " You are entitled for a commission of
End If Rs. 10000"
101
Copyright @ NIMI Not to be Republished
End If MsgBox "You need not pay any income tax"
The If Then…. Else Statements Msg Box ("You must pay income tax")
The syntax for the If Then … Else statements is as follows Using Multiple If Statements
{
Check condion
/* Executes when the boolean expression 1 is true */
Yes No }
}
Next code to run
else if( boolean_expression 3)
102 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.109A - 2.2.109C
Copyright @ NIMI Not to be Republished
The following is an example of a ladder if structure. If the first condition is not met, the control jumps to the
statement after the End if statement. The following code
Sub grades()
is an example for the mentioned example.
Dim marks As Integer Sub job_test()
Dim experience, marks As Integer
marks = InputBox("Enter you marks")
experience = InputBox("Enter your work experience in
If marks >= 80 Then
years")
MsgBox "Distinction"
If experience >= 5 Then
ElseIf marks >= 70 Then
marks = InputBox("Enter you marks percentage")
MsgBox "A Grade"
If marks >= 75 Then
ElseIf marks >= 60 Then
MsgBox (" You are eligible for the post")
MsgBox "B Grade"
Else
ElseIf marks >= 40 Then
MsgBox (" You are NOT eligible for the post")
MsgBox "C Grade"
End If
Else
Else
MsgBox "Failed"
MsgBox (" You are NOT eligible for the post")
End If
End If
End Sub
End Sub
This program would display the grade based on the marks
Using Logical operators in If Structure
entered by the user.
The Logical operators And, Or and Not can be used in If
Nested If statements structure and produce the same results as those produced
Sometimes it is required to evaluate one condition only if in Nested If Structures.
an earlier condition is met. In such cases an If Then
For ex. the above mentioned condition can be evaluated
statement can be placed inside an outer If Then statement.
using the And operator in the conditional statement.
This type of structure is also called a Nested If
structure.The syntax of a nested if structure is as follows: Sub job_test()
If(Boolean_expression 1) Dim experience, marks As Integer
{ experience = InputBox("Enter your work experience in
years")
//Executes when the Boolean expression 1 is true
marks = InputBox("Enter you marks percentage")
If(Boolean_expression 2)
If experience >= 5 And marks >= 75 Then
{
MsgBox (" You are eligible for the post")
//Executes when the Boolean expression 2 is true Else
} End If
End Sub
For ex. A certain recruitment condition states that a
candidate to be declared eligible must have a minimum of Select...Case
5 years' experience and also must have scored atleast Another way to implement decision making in your VBA
75% marks in the exam. In such a case, the first condition code is to use a Select...Case statement. Select...Case
to be tested is for experience >= 5 years andonly if this statements can be used to easily evaluate the same
condition is met, the second condition is to be evaluated. variable multiple times and then take a particular action
depending on the evaluation.
IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.109A - 2.2.109C 103
Copyright @ NIMI Not to be Republished
It is always a good practice to use Select Case Statement This function is available within VBA code and also as an
when multiple If-Else conditions are involved. As the number Excel function. Usually the IIF function is used to perform
of If-Else conditions increases, debugging and quick logical assessments and can be nested to perform
understanding all the flow becomes a tedious job. more complicated evaluations. It is however important to
remember that nested IF statements can become very
The syntax for a Select...Case statement is: complicated and difficult to support and maintain.
Now let’s look at an example. Let’s assume that we want
Select Case VARIABLE
to calculate the length of the string only if it contains the
Case VALUE1 value Excel Help and Excel. (Fig 3)
Fig 3
' code to run if VARIABLE equals Value1
Case VALUE2
Case Else
End Select
For Ex. This program asks the user to type the name of
the game and displays the number of players for the game.
Sub players() It is important to note that we could have used the IIF
Dim game As String statement in one of our For Next loops to run through all
the rows on a worksheet.
game = InputBox("enter the name of the game")
game = LCase(game) Code
Select Case game
Dim StringToProcess As String’Variable to hold the string
Case "tennis"
to be processed
Debug.Print "2 Players."
StringToProcess = ActiveSheet.Cells(2, 1).Value
Case "cricket"
Debug.Print "11 Players." ActiveSheet.Cells(6, 1).Value = IIf(InStr(StringToProcess,
Case "volleyball" “ExcelHelp”) > 0, IIf(InStr(StringToProcess, “ Excel “) > 0,
Debug.Print "5 Players."
Len(StringToProcess), 0), 0)
Case "baseball"
Debug.Print "9 Players." Output (Fig 4)
IIF Function
IIF function is used to evaluate an expression and perform
one of two actions based on the outcome of the evaluation.
For example:
IIF (Value > 10, Perform this action if Value is <= 10,
Perform this action is Value is > 10)
104 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.109A - 2.2.109C
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.110A & 2.2.110B
COPA - Programming with VBA
Do Until n=10
Dim num As Integer
Debug.print n
Debug.Print "number"; Spc(2); "square"
n=n+1
Do While num < 10
Loop
num = num + 1
Do ….. Loop Until
Debug.Print num; Spc(5); num * num
In this example, the code in the loop is executed at least
Loop
once before testing the condition. If the condition is true,
the looping stops, else the loop is executed again.
Do…. Loop While
Do
In a Do…. Loop While , a set of statements in the loop are
executed once, then the condition is checked. The code
Debug. print n
in the loop is executed only if the condition is met. (Refer
Fig 2 for the flow chart)
n=n+1
In this example, the value 1 is placed in cell (1,1). The row
Loop Until n=10
value is incremented each time the loop code is executed.
The Do While … Loop repeats a statement or group of The incremented value is placed in the cell (row,1). The
statements as long as the condition is true. loop is executed as long as the row value is less than 10
after which the iterations stop. The condition checking is
Like the Do until loop, a Do While loop can be also be done after executing the loop code at least once. (Fig 2)
used in two ways.
106 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.110A & 2.2.110B
Copyright @ NIMI Not to be Republished
Fig 2 Dim Counter
Counter = Counter + 1
Loop code
Debug.Print "hello"
Wend
Debug.Print Counter
In this example the condition checking is done at the In this example, the loop condition stops the loop when
beginning of the loop. This code prints hello 5 times and count=5.
then prints the value of the counter, ie. 5 at the end of the
program.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.110A & 2.2.110B 107
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.111A - 2.2.111C
COPA - Programming with VBA
Arrays in VBA
Objectives: At the end of this lesson you shall be able to
• describe and declare an array in VBA
• differentiate between static and dynamic arrays
• declare, populate and read a multidimensional array
• describe the redim and preserve statements in VBA.
An Array is a group of variables of the same data type and Arrays are also declared in another method where the
with the same name. If we have a list of items which are of type or the variable name with one or more pairs of
similar type to deal with, we need to declare an array of parentheses is added to indicate that it will hold an array.
variables instead of using a variable for each item. For After you declare the array, you can define its size by
example, if we need to enter ten names, instead of using the ReDim Statement.
declaring ten different variables for each name, we need to
declare only one array holding all the names. The individual The following example declares a one-dimensional array
element or item in the array is identified by its index or variable and also specifies the dimensions of the array by
subscript. using the ReDim Statement.
When arrays are used, data is stored in an organized Dim arr As Integer()
way. Apart from this working with the data is easy and
faster when iterations are done using the Loop statements ReDim arr(10)
like For… Next etc. on the Arrays. The following example
declares an array variable to hold ten students in a school. The following example declares a multidimensional array
variable by placing commas inside the parentheses to
Dim students(10) As Integer separate the dimensions.
The array "students" in the preceding example contains Dim arrayName (num1, num2) as datatype
ten elements. The indices of the elements range from 0
through 9 by default. The variables in the Array are now To declare a jagged array variable, add a pair of
identified as students(0), students(1) etc.indicating the first parentheses after the variable name for each level of nested
element and second element etc.respectively. array.
1 Static Arrays In VBA arrays you can specify any value for the lower and
upper bounds of the array. Element 0 need not be the first
2 Dynamic Arrays element in the array. For example, the following is perfectly
Static array legal code (as long as the lower bound is less than or
equal to the upper bound -- an error is generated if the
A static array is an array that is sized in the Dim statement lower bound is greater the upper bound).
that declares the array. E.g.,
If you don't explicitly declare the lower bound of an array,
Dim Students(10) as String the lower bound will be assumed to be either 0 or 1,
depending on value of the Option Base statement, if
Dim StaticArray(1 To 10) As Long present. If Option Base is not present in the module, 0 is
assumed. For example, the code
You cannot change the size or data type of a static array.
When you erase a static array, no memory is freed. Erase Dim Arr(10) As Long
simply sets all the elements to their default value (0,
vbNullString, Empty, or Nothing, depending on the data declares an array of either 10 or 11 elements. The
type of the array). declaration does not specify the number of elements in
the array. Instead, it specifies the upper bound of the array.
Declaring an Array If your module does not contain an "Option Base"
statement, the lower bound is assumed to be zero,
You declare an array variable using the Dim statement. and the declaration above is the same as :
Dim Arr(0 To 10) As Long
108
Copyright @ NIMI Not to be Republished
If you have an Option Base statement of 0 or 1, the lower Here LBound() and UBound() functions return the Lower
bound of the array is set to that value. and Upper Bounds of the Array.
Thus, the code : Dim Arr(10) As Long is the equivalent of Multi dimensional Arrays
either Dim Arr(0 To 10) As Long or Dim Arr(1 To 10) As
Long, depending on the value of the Option Base. Multi dimensional arrays have more than one row or one
column.
It is a good programming practice to specify both the lower
and upper bounds of the array to avoid bugs when copying For ex.Dim MyArray(5, 4) As Integer
and pasting code between modules or elsewhere.
Dim MyArray(1 To 5, 1 To 6) As Integer
Storing values in an array
In the following ex. we will define an array with 3 elements
Arrays can be populated in the following ways each in two rows
arr(1) = 56 Debug.Print
arr(2) = 78 Next m
IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.111A - 2.2.111C 109
Copyright @ NIMI Not to be Republished
E.g. : Dim DynamicArray() As Long A(3) = "MASE"
ReDim DynamicArray(1 To 10) debug.print A(1) & " , " & A(2) & " , " & A(3)
If an array is sized with the ReDim statement, the array is End Sub
said to be allocated( either static array or a dynamic
array).Static arrays are always allocated and never When you use the ReDim keyword, you erase any existing
empty.You can change the size of a dynamic array, but data currently stored in the array.
not the data type. When you Erase a dynamic array, the
memory allocated to the array is released. You must For ex. add another element to the array mentioned in
ReDim the array in order to use it after it has been Erased. the example above using the redim statement as follows
and assign a value to it.
If a dynamic array has not yet been sized with the ReDim
statement, or has been deallocated with the Erase ReDim A(4) As String
statement, the array is said to be empty or unallocated.
Static arrays are never unallocated or empty. A(4) = "CHNM"
ReDim Statement: Now when the array values are displayed again, the earlier
values will all be blank, since they are erased by the redim
You may declare a dynamic variable with empty statement. The example below shows this:
parentheses ie. leave the index dimensions blank. You
can thereafter size or resize the dynamic array that has Sub arr_test()
already been declared, by using the ReDim statement. To
resize an array, it is necessary to provide the upper bound, 'declare a dynamic array
while the lower bound is optional. If you do not mention
the lower bound, it is determined by the Option Base Dim A() As String
setting for the module, which by default is 0. You can
specify Option Base 1 in the Declarations section of the ReDim A(3) As String
module and then index will start from 1. This will mean
that the respective index values of an array with 3 elements A(1) = "COPA"
will be 1, 2 and 3. Not entering Option Base 1 will mean
A(2) = "DTPO"
index values of 0, 1 and 2.
A(3) = "MASE"
The following example declares an array called A1 as a
dynamic array. The array's size is not set and then it is
ReDim A(4) As String
resized to 3 elements (by specifying Option Base 1)
A(4) = "CHNM"
Sub arr_test()
Debug.Print A(1) & " , " & A(2) & " , " & A(3) & "," & A(4)
'declare a dynamic array
End Sub
Dim A() As String
The result of this program will be , , ,CHNM
ReDim A(3) As String
To resize the array without losing the existing data, you
A(1) = "COPA"
should use " Preserve " along with Redim. For ex. ReDim
Preserve A(4) As String.
A(2) = "DTPO"
110 IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.111A - 2.2.111C
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.112
COPA - Programming with VBA
Debug.Print "The payment for "& person & " is " & pay
111
Copyright @ NIMI Not to be Republished
Left() RTrim()
Returns a string containing a specified number of Returns a string containing a copy of a specified string
characters from the left side of a string. with no trailing spaces.
Trim()
Right()
Returns a string containing a copy of a specified string
Returns a string containing a specified number of with no leading or trailing spaces.
characters from the right side of a string.
Syntax : Trim(String)
Syntax: Right(String, Int)
Examples: Dim A as String
Mid()
A=" Adjustment "
Returns a string that contains characters from a specified Debug.Print "For everyone" <rim(A) & "is a must"
string.
Debug.Print "For everyone"; RTrim(A) & "is a must"
Syntax:Mid(String, Int, Int)
Debug.Print "For everyone"; Trim(A) & "is a must"
Returns a string that contains all the characters starting
from a specified position in a string This will print : For everyoneAdjustment is a must
debug.print right(s, 5) Debug.Print "The second string starts at position no. "
&InStr(1, A, B) "
This will print : TALLY
3 Dim s AsString This will print : The second string starts at position no. 5
112 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.112
Copyright @ NIMI Not to be Republished
Val() CStr()
The VAL() function accepts a string as input and returns The CStr() function is used to convert any type of value to
the numbers found in that string.The VAL function will stop a string.
reading the string once it encounters the first non-numeric
character. This does not include spaces. Syntax: Str(number as variant)
This will print : 6 The Asc() function returns an Integer value representing
the ASCII code corresponding to a character or the first
5 character in a string
LCase() Chr()
Returns a string or character converted to lowercase. The Chr() Function returns the character associated with
the specified ASCII code.
Syntax :LCase(String)
Syntax :Chr(Integer)
UCase()
Example :Chr(68) will return the character "D"
Returns a string or character converted to uppercase.
Reversing a String
Syntax :UCase(String)
StrReverse(String)
Example:
StrReverse() returns a string in which the character order
Dim A, B as String of a specified string is reversed.
A="IF YOU FEAR YOU WILL BECOME WEAK" Example: Dim A As String
This will print: if you fear you will become weak Format() function
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.112 113
Copyright @ NIMI Not to be Republished
Syntax(for FormattingStrings) : Format(String, Format) You can use any of the following characters to create a
format expression for strings:
User-Defined String Formats (Format Function)
Example :Dim x As String
Character Description
@ Character placeholder. Display a character or a space. If the string has a character in the
position where the at symbol (@) appears in the format string, display it; otherwise,
display a space in that position. Placeholders are filled from right to left unless there is an
exclamation point character (!) in the format string.
& Character placeholder. Display a character or nothing. If the string has a character in the
position where the ampersand (&) appears, display it; otherwise, display nothing.
Placeholders are filled from right to left unless there is an exclamation point character (!)
in the format string.
! Force left to right fill of placeholders. The default is to fill placeholders from right to left.
x = "change case"
114 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.112
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.113
COPA - Programming with VBA
Table 1
ISDATE Returns TRUE if the expression is a valid date. Otherwise, it returns FALSE.
ISERROR Checks for error values.
ISNULL Returns TRUE if the expression is a null value. Otherwise, it returns FALSE.
ISNUMERIC Returns TRUE if the expression is a valid number. Otherwise, it returns FALSE.
Table 3
116 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.113
Copyright @ NIMI Not to be Republished
Examples 2 Format Date
12 End Sub
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.113 117
Copyright @ NIMI Not to be Republished
Table 6 Table 7
vbUseSystem 0 Uses the NLS API setting vbUseSystem 0 Uses the NLS API setting
The result will be Table 8. below lists some of the common Built in Functions
in the Data Type Conversion category.
1/1/1990
Table 8
Example Debug.PrintCDate(b)
CDate function c = "1:23:45 PM"
Sub test() Debug.PrintCDate(c)
Dim lNum As Long End Sub
Dim a As String This will display
a = 12345 10/18/1933
Debug.PrintCDate(a) 1/1/1990
b = "January 1, 1990" 1:23:45 PM
118 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.113
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.114 & 2.2.115
COPA - Programming with VBA
Introduction b = 20
In Excel Visual Basic too, like in most programming Debug.Print "area Is " & l * b
languages, a set of commands to perform a specific task
is placed into a procedure, which can be a function or a End Function
subroutine. The main difference between a VBA function
and a VBA subroutine is that a function (generally) returns When executed from the immediate window this function
a result, whereas a subroutine does not. displays the area.
Therefore, if you wish to perform a task that returns a Alternately this function can be called by another
result (ex. summing of a group of numbers), you will subroutine, for ex.
generally use a function, but if you just need a set of actions
to be carried out (ex. formatting a set of cells), you might Sub test_fn()
choose to use a subroutine.
Call area
User Defined Functions
End Sub
One of the most power features of Excel VBA is that you
can create your own functions or UDFs. A UDF (User Returning a value from the procedures
Defined Function) is simply a function that you create
yourself with VBA for your own defined tasks. UDFs are In the example given below, the area() function calculates
often called "Custom Functions". A UDF can remain in a l*b.
code module attached to a workbook, in which case it will
always be available when that workbook is open. The subroutine that calls this function is returned this value.
Alternatively you can create your own add-in containing
one or more functions that you can install into Excel. Here Sub test_fn()
the user-defined functions can be entered into any cell or
Debug.Print "The function has returned the value " & area
on the formula bar of the spreadsheet just like entering
the built-in formulas of the MS Excel spreadsheet.
End Sub
Custom functions, like macros, use the Visual Basic for
Function area()
Applications (VBA) programming language. They differ from
macros in two significant ways. First, they use function
Dim l, b, A
procedures instead of sub procedures. They start with a
Function statement instead of a Sub statement and end l = 10
with End Function instead of End Sub. Second, they
perform calculations instead of taking actions. Certain b = 20
kinds of statements (such as statements that select and
format ranges) are generally excluded from custom area = l * b
functions.
End Function
A simple function may look like this:
The result will be:The function has returned the value 200
Function area()
Passing Arguments to functions
Dim l, b
We can pass the arguments in two different ways:
l = 10
119
Copyright @ NIMI Not to be Republished
1 By Value (ByVal): We pass the copy of the actual value Function Modify(ByRef A As Integer)
to the arguments
A=A*2
2 By Reference (ByRef): We pass the reference to the
arguments
Modify = A
By Ref is the default method of passing argument type in
VBA. This means, if you are not specifying any type of End Function
the argument it will consider it as ByRef type. However, it
is always a good practice to specify the ByRef even if it is The result will be:
not mandatory.
The function has returned the value 20
The following example shows the method of passing
variables to a function byVal. A is now 20
Dim a, b As Integer You call the user defined functions as similar to the built-
in excel function. To do this type the arguments in the
a=4 cells and type the name of the function as is done with
normal functions in Excel.
b = multiply(a)
Passing Arrays to User Defined functions
Debug.Print "a is " & a
A Function can accept an array as an input parameter.
Debug.Print "The function has returned the value " & b Arrays are always passed by reference (ByRef). You will
receive a compiler error if you attempt to pass an array
End Sub ByVal. This means that any modification that the called
procedure does to the array parameter is done on the
Function multiply(ByVal a As Integer) actual array declared in the calling procedure.
a = a * 10 (If you need to pass an array ByVal then you would need
to use the Variant data type.)
multiply = a
An example of passing an array to a function is as follows:
End Function
Sub test()
The result of this program will be :
Dim arr(1 To 10) As Integer
a is 4
Dim i As Integer
The function has returned the value 40
'populates the array with the values 1 to 10
a is 4
For i = 1 To 10
This means that the value of the variable that was passed
is not disturbed by the function. arr(i) = i
A = 10 For i = 1 To 10
Debug.Print "The function has returned the value " & Debug.Print arr(i); Spc(2);
Modify(A)
Next i
Debug.Print "A is now " & A
End Sub
End Sub
120 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115
Copyright @ NIMI Not to be Republished
'prints the values in arrIntegers to column A For Example the following subroutine has been created in
Module1 code.
Sub fn1(ByRef arr() As Integer)
Sub disp()
Dim i As Integer
Dim s As string
For i = LBound(arr) To UBound(arr)
s="hello"
arr (i) = arr (i) * 2
MsgBox s
Cells (i,1) = arr (i)
End Sub
Next i
Run the subroutine "disp" in Module1 and it will display
End Sub
the message "Hello" in the message box.
Scope of variables
Now the following subroutine has been created in Sheet1
The term Scope is used to describe how a variable may code to call the disp() subroutine from Module1.
be accessed. Depending on where and how a variable is
declared, it may be accessible only to a single procedure, Sub Button1_Click()
to all procedures within a module, and so on up the
hierarchy of a project or group of related projects. The disp
term visibilty is also is sometimes used to describe scope.
End Sub
There are four levels of Scope:
This will generate an error since the subroutine disp() and
• Procedure-Level Scope
the variable s are local to Module1 and cannot be accessed
• Module-Level Scope from elsewhere.
• Global-Level Scope A local variable declared with the Static statement remains
in existence the entire time Visual Basic is running. The
Fig 1 shows the various scopes and their levels.
variable is reset when any of the following occur:
Fig 1
• The macro generates an untrapped run-time error.
Global scope • Visual Basic is halted.
Project scope • You quit Microsoft Excel.
Module scope • You change the module.
Procedure scope
For example, in the FindTotal example, the Accumulate
variable retains its value every time it is executed. The
first time the module is run, if you enter the number 2, the
message box will display the value "2." The next time the
module is run, if the value 3 is entered, the message box
will display the running total value to be 5.
Sub FindTotal()
Procedure (local) scope
Static Total
A local variable with procedure scope is recognized only
Dim n as integer
within the procedure in which it is declared. A local variable
can be declared with a Dim or Static statement.
n =InputBox("Enter a number: ")
When a local variable is declared with the Dim statement,
Total = Total + n
the variable remains in existence only as long as the
procedure in which it is declared is running. Usually, when
MsgBox "The total is " &n
the procedure is finished running, the values of the
procedure's local variables are not preserved, and the
End Sub
memory allocated to those variables is released. The next
time the procedure is executed, all of its local variables
are reinitialized.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115 121
Copyright @ NIMI Not to be Republished
Module scope End Sub
Note If you use Private instead of Dim for module-level Project scope variables are those declared using the Public
variables, your code may be easier to read (that is, if you keyword. These variables are accessible from any
use Dim for local variables only, and Private for module- procedure in any module in the project. In Excel, a Project
level variables, the scope of a particular variable will be is all of the code modules, userforms, class modules, and
more clear). object modules (e.g. ThisWorkbook and Sheet1) that are
contained within a workbook.
In the following example, two variables, A and B, are
declared at the module level. These two variables are In order to make a variable accessible from anywhere in
available to any of the procedures on the module sheet. the project, you must use the Public keyword in the
The third variable, C, which is declared in the Example3 declaration of the variable. However, this makes the variable
macro, is a local variable and is only available to that accessible to any other project that reference the project
procedure. containing the variable. If you want a variable to be
accessible from anywhere within the project, but not
Note that in Test4, when the macro tries to use the variable accessible from another project, you need to use Option
C, the message box is empty. The message box is empty Private Module as the first line in the module (above and
because C is a local variable and is not available to Test4, outside of any variable declaration or procedure). This option
whereas variables A and B are. makes everything in the module accessible only from within
the project. The project variables that should not be
Dim A As Integer ' Module-level variable. accessible to other projects should be declared in a module
that has the Option Private Module directive. Variables
Private B As Integer ' Module-level variable. that should be accessible to other project should be
declared in a different module that does not use the Option
Sub Test1() Private Module directive. In both cases, however, you need
to use the Public keyword.
A = 10
Global Scope
B = A * 10
Global scope variables are those that are accessible from
End Sub anywhere in the project that declares them as well as any
other project that references the first project. To declare a
Sub Test2() variable with global scope, you need to declare it using
the Public keyword in a module that does not use the
MsgBox "The value of A is " & A Option Private Module directive. In order to access variables
in another project, you can simply use the variable's name.
MsgBox "The value of B is " & B If, however, it is possible that the calling project also has a
variable by the same name, you need to prefix the variable
End Sub name with the project name. For example, if Project1
declares a global variable named x, and Project2 references
Sub Test3() Project1, code that is in Project2 can access x with either
of the following lines of code:
Dim C As Integer ' Local variable.
x = 78
C=A+B
Project1.x = 78
MsgBox "The value of C is " & C
122 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115
Copyright @ NIMI Not to be Republished
If both Project1 and Project2 have variables with at least of a subroutine (usually at the very top of your module).
project scope, you need to include the project name with You can use this type of variable when you have one
the variable. For clarity and maintainability, you should subroutine generating a value and you want to pass that
always include the project name when accessing a variable value on to another subroutine in the same module.
that is declared in another project. Even if this is not
necessary, it makes the code more readable and Dim[variable] is used to state the scope inside of a
maintainable. subroutine (you cannot use Private in its place). Dim can
be used either inside a subroutine or outside a subroutine
There is no way to give some variables project, but not (using it outside a subroutine would be the same as using
global, scope and give others in the same module global Private).
scope. Project versus global scope is handled only at the
module level, not at the variable level. Example of Public, Private Variables and Procedures.
One of the techniques in object-oriented programming is Dim x As Integer ' This is a Private Variable since it is
encapsulation. It concerns the hiding of data in a class declared using Dim.
and making them available only through its methods. Most
programming languages implementing OOPS allow you to Public y As Integer
control access to classes, methods, and fields via so-called
access modifiers. The access to classes, constructors, Sub First_Sub()
methods and fields are regulated using access modifiers
i.e. a class can control what information or data can be x = 10
accessible by other classes. The VBA access specifiers
are: y = 20
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115 123
Copyright @ NIMI Not to be Republished
The Third_Sub() has been designed to display the values trying to call a private subroutine " Second_Sub" from here.
of x and y in the immediate window. When you try to print The following changes can be done to avoid this:
variable x it outputs nothing. This is because x does not
exist in Module 2. Therefore, a new variable x is created 1 We could remove the word "Private" from
in Module 2 and since we did not give this new x a value, Display_Message
nothing is printed for the statement Debug.Print x 2 We could replace "Private" with "Public" in
Second_Sub()
When we print the value of the variable y, 12 is displayed
in the Immediate Window. This is because Module 2 3 We can use the Application level and instead of using
subroutines have access to the public variables declared Call we could write Application.Run "Second_Sub " (this
in Module 1.But the statement "Call Second_Sub()" in the method serves as an override in case we wanted to
Third_Sub() will result in an error. This is because we are keep Second_Sub private for subroutines outside the
module.)
124 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.116
COPA - Programming with VBA
Macros offer a powerful and flexible way to extend the 4 Absolute versus Relative Macros
features of Excel. They allow the automation of repetitive
An “Absolute” macro will always affect the same cells
tasks such as printing, formatting, configuring, or
each time whereas a “Relative” macro will affect those
otherwise manipulating data in Excel. In its’ simplest form,
cells relative to where the cursor is positioned when
a macro is a recording of your keystrokes. While macros
invoke the macro. It is crucial that understand the
represent one of the stronger features found in Excel, they
difference.
are rather easy to create and use. There are six major
points that I like to make about macros as follows.
5 Editing Macros
1 Record, Use Excel, Stop Recording Once created, you can view and/or edit your macro
using the View Macros option. This will open the macro
To create a macro, simply turn on the macro recorder, subroutine in a Visual basic programming window and
use Excel as you normally do, then turn off the recorder. provide you with a plethora of VB tools.
Presto – you have created a macro. While the
process is simple from the user’s point of view, 6 Advanced Visual Basic Programming
underneath the covers Excel creates a Visual Basic
subroutine using sophisticated Visual Basic For the truly ambitious CPA, in the Visual Basic
programming commands. Programming window, you have the necessary tools
you need to build very sophisticated macros with dialog
2 Macro Location boxes, drop down menu options, check boxes, radio
buttons – the whole works. To see all of this power,
Macros can be stored in either of two locations, turn on the “Developer Tab” in “Excel Options”.
as follows: Presented below are more detailed comments and
stepbystep instructions for creating and invoking
The workbook you are using, or the Personal Macro
macros, followed by some example macros.
Workbook (which by default is hidden from view) If
the macro applies to all workbooks, then store it
Page Setup Macro Start recording a new macro called
in the Personal Macro Workbook so it will always be
page setup. Select all of the worksheets and then choose
available in all of the Excel workbooks; otherwise store
Page Setup and customize the header and footers to
it in the current workbook. A macro stored in the current
include page numbers, date and time stamps, file locations,
workbook will embedded and included in the
tab names, etc. Assign the macro to an Icon onthe toolbar
workbook, even if you email the workbook to
or Quick Access Bar and insetting headers and footers
another user.
will be a breeze for the rest of your life.
3 Assign the Macro to an Icon, Text or a Button
Print Macros Do you have a template that print frequently
To make it easy to run your macro, you should assign from? If so, insert several macro buttons to print each
it to a toolbar icon so it will always be available no report, a group of reports, and even multiple reports and
matter which workbooks you have open. If the macro reporting will be snap in the future.
applies only to the current workbook, then assign it to
Text or a macro Button so it will be quickly available in Delete Data Macro create a macro that visits each cell
the current workbook. and erases that data, resetting the worksheet for use in a
new set of criteria. Assign the macro to a macro
button and will never again have old assumptions
mixed in with your newer template
125
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.117
COPA - Programming with VBA
A form is a document designed with a standard structure A VBA form can be created from the code window. To
and format that makes it easier to enter, organize, and create a Form in VBA,click on Insert menu in the code
edit information. Forms contain labels, textboxes, drop window and then click 'UserForm'. A UserForm1 appears
down boxes and command buttons too. in the project window.
By using forms and the many controls and objects that When you create or add a form, a module is also
you can add to them, you can significantly enhance data automatically created for it. To access the module
entry on your worksheets and improve the way your associated with a form, you can right-click the form and
worksheets are displayed. click View Code.Double Clicking on the Form or pressing
F7 will also open the Code window. Using Shift F7 will
Types of Excel forms again switch back to the Design Window.
There are several types of forms that you can create in The design time properties of the Form can be set by right
Excel: data forms, worksheets that contain Form and clicking on the form and selecting 'Properties'. The same
ActiveX controls, and VBA UserForms. can be achieved by Clicking "F4" or the properties button
on the Form.Controls can be placed on the form from the
Data form ToolBox as per requirement.
A data form provides a convenient way to enter or display In addition, Controls can be added on the Form
one complete row of information in a range or table without programmatically / at run time using the "Add" method.
scrolling horizontally. You may find that using a data form Similarly the controls can be removed from the form at run
can make data entry easier than moving from column to time / programmatically using the "Remove" method. As
column when you have more columns of data than can be an example to add a checkbox control, we can write
viewed on the screen. Excel can automatically generate a
built-in data form for your range or table. Set cb1 = Controls.Add("Forms.CheckBox.1")
Worksheet with Form and ActiveX controls Some of the events and methods connected with the form
object are:
A worksheet can be considered to be a form that enables
you to enter and view data on the grid. Events, Activate, Deactivate, Add Control, Remove Control,
Click, DblClick, Initialize, KeyPress, Resize, Scroll,
For added flexibility, you can add controls and other drawing Terminate, Zoom etc.
objects to the worksheet, and combine and coordinate
them with worksheet cells. For example, you can use a Methods Copy, Paste, Hide, Move, Print Form, Repaint,
list box control to make it easier for a user to select from Scroll, Show etc .
a list of items. Or, you can use a spin button control to
make it easier for a user to enter a number. The code needed to perform various operations on Forms
is given in Table 1.
You can display or view controls and objects alongside
associated text that is independent of row and column A sample Form for data entry of students' details, marks
boundaries without changing the layout of a grid or table and results is shown in Fig. 1.
of data on your worksheet. Many of these controls can
also be linked to cells on the worksheet and do not require Necessary code can be attached to the Command Buttons
VBA code to make them work. For example, you might and other controls shown. After the user enters the data,
have a check box that you want to move together with its the total is calculated and the result is displayed. The
underlying cell when the range is sorted. However, if you records can then be stored appropriately.
have a list box that you want to keep in a specific location
at all times, you probably do not want it to move together
with its underlying cell.
126
Copyright @ NIMI Not to be Republished
Table 1
To Display a UserForm1.Show Displays the UserForm with name UserForm1. This code should be
UserForm inserted in a Standard VBA Module and not in the Code Module of the
UserForm. You can create a button in a worksheet, then right click to
assign macro to this button, and select the macro which shows the
UserForm.
Load a UserForm Load UserForm1 Load statement is useful in case of a complex UserForm that you
into memory but do want to load into memory so that it displays quickly on using the
not display Show method, which otherwise might take a longer time to appear.
Remove a User Unload UserForm1 Note: The Hide method (UserForm1.Hide) does not unload the
Form from memory UserForm from memory. To unload the UserForm from memory, the
/ Close UserForm Unload method should be used.
Unload Me Use the Me keyword in a procedure in the Code Module of the UserForm.
Hide a UserForm UserForm1.Hide Using the Hide method will temporarily hide the UserForm, but will not
close it and it will remain loaded in memory.
Print a UserForm UserForm1.PrintForm The PrintForm method sends the UserForm directly for printing.
Display UserForm UserForm1.Show False If the UserForm is displayed as Modeless, user can continue working
as Modeless in Excel while the UserForm continues to be shown. Omitting the
Boolean argument (False or 0) will display the UserForm as Modal, in
which case user cannot simultaneously work in Excel. By default
UserForm is displayed as Modal.
Close a UserForm Unload UserForm1 The Unload method closes the specified UserForm.
Unload Me The Unload method closes the UserForm within whose Code Module
it resides.
End Use the End statement in the "Close" CommandButton to close the
form. The "End" statement unloads all forms.
Specify UserForm UserForm1.Caption Caption is the text which describes and identifies a UserForm and will
Caption = "Bio Data" display in the header of the Userform.
Set UserForm UserForm1.Height
size = 250 Set Height of the UserForm, in points.
UserForm1.Width
= 350 Set Width of the UserForm, in points.
Set UserForm Position:
Left & Top UserForm1.Left = 30 Distance set is between the form and the Left or Top edge of the
properties UserForm1.Top = 50 window that contains it, in pixels.
Move method UserForm1.Move Move method includes two arguments which are required - the Left
200, 50 distance and the Top distance, in that order.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.117 127
Copyright @ NIMI Not to be Republished
Necessary code can be attached to the Command Buttons
and other controls shown. After the user enters the data,
the total is calculated and the result is displayed. The
records can then be stored appropriately.
Fig 1
128 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.117
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.118
COPA - Programming with VBA
Methods
129
Copyright @ NIMI Not to be Republished
Fig 3 When we change content of any Cell the following message
will be displayed as shown in Fig 4.
Fig 4
130 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.118
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.119
COPA - Programming with VBA
In Excel 2010, VBA’s debugging environment allows the First, you need to open the VBA environment. The quickest
programmer to momentarily suspend the execution of VBA way to do this is by pressing Alt+F11 while the Excel
code so that the following debug tasks can be done: database file is open.
To set a breakpoint, find the line of code where to suspend
1 Check the value of a variable in its current state.
your program. Left-click in the grey bar to the left of the
2 Enter VBA code in the Immediate window to view the code. A red dot should appear and the line of code should
results. be highlighted in red.
3 Execute each line of code one at a time.
Clear Breakpoint in VBA
4 Continue execution of the code.
5 Halt execution of the code. A breakpoint in VBA is indicated by a red dot with a line
of code highlighted in red.
These are just some of the tasks that you might perform To clear a breakpoint in Excel 2010, left-click on the red
in VBA’s debugging environment. (Fig 1) dot next to the line of code that has the breakpoint.
Fig 1
(Fig 2)
Fig 2
Breakpoint in VBA
In Excel 2010, a breakpoint is a selected line of code that In this example, we want to clear the breakpoint at the
once reached, the program will momentarily become
following line of code:
suspended. Once suspended, and to use VBA’s debugging
environment to view the status of program, step through
LChar = Mid(pValue, LPos, 1) (Fig 3)
each successive line of code, continue execution of the
code, or halt execution of the code.
Now, the breakpoint is cleared and the line of code should
And create as many breakpoints in the code as you want. look normal again. (Fig 4)
Breakpoints are particularly useful when suspend the
program where you suspect a problem/bug exists.
131
Copyright @ NIMI Not to be Republished
Fig 3 Fig 5
Debug Mode
Fig 4
Now that we know how to set and clear breakpoints in
Excel 2010, let’s take a closer look at the debug mode
in VBA.
132 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.119
Copyright @ NIMI Not to be Republished
Now we are in debug mode in our Excel spreadsheet. In this example, we typed print pValue in the Immediate
Now we can do any of the following: window and pressed ENTER.
Print pValue
1 Check the value of a variable in its current state.
2 Enter VBA code in the Immediate window to view the The Immediate window displayed the result in the next
results. line. In this case, the print pValue command returned 123
3 Execute each line of code one at a time. Main St.
4 Continue execution of the code. You can also type more complicated expressions in the
Immediate window. (Remember to press ENTER.) For
5 Halt execution of the code.
example: (Fig 10)
Fig 8
We’ve found the Immediate window to be the most help The Immediate window displayed the result of 1 in the
when we need to find out the value of a variable, expression, next line.
or object at a certain point in the program. This can be
done using the print command. The Immediate window can be used to run other kinds of
VBA code, but bear in mind that the Immediate window
For example, if you wanted to check the current value of can only be used when debugging so any code that you
the variable called pValue, you could use the print run is for debugging purposes only. The code entered in
command as follows: (Fig 9) the Immediate window does not get saved and added to
the existing VBA code
Fig 9
Adding a Watch Expression
The Watch Window displays the value of a watched
expression in its current state. This can be extremely
useful when debugging VBA code. Let’s explore how to
add an expression to the Watch Window.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.119 133
Copyright @ NIMI Not to be Republished
Fig 11 Fig 12
Watch Expression To display the value of the watched expression in its current state
Break When Value Is True To stop the execution of the code when the value of the watched expression is
True
Break When Value Changes To stop the execution of the code when the value of the watched expression
changes
When return to the VBA window, the Watch Window will As you can see, the expression Mid(pValue, LPos, 1)
automatically appear if it was previously hidden. Within now appears in the Watch Window with a value of “1”.
the Watch Window, all of the watched expressions should Adding a watch is a great way to keep track of variables or
be listed including the one that we just added. (Fig 13) expressions of interest when debugging the VBA code.
Fig 13
134 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.119
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.2.120
COPA - Programming with VBA
VBA Class Modules allow the user to create their own With most things in life there are pros and cons. Using
objects. In languages such as C# and Java, classes are VBA class modules is no different. The following are the
used to create objects. Class Modules are the VBA disadvantages of using class module to create objects
equivalent of these classes. The major difference is that 1 It takes more time initially to build applications*.
VBA Class Modules have a very limited type of
Inheritance* compared to classes in the other 2 It is not always easy to clearly define what an object
languages. In VBA, Inheritance works in a similar way is.
to Interfaces in C#\Java. 3 People new to classes and objects can find them
difficult to understand at first.
In VBA we have built-in objects such as the Collection,
Workbook, Worksheet and so on. The purpose of VBA If create an application using objects it will take longer to
Class Modules is to allow us to custom build our own create it initially have to spend more time planning and
objects. designing it. However, in the long run it will save a huge
amount of time. The code will be easier to manage, update
Let’s start this post by looking at why we use objects in
and reuse.
the first place.
Creating a Simple Class Module
Inheritance is using an existing class to build a new
class. Let’s look at a very simple example of creating a class
Interfaces are a form of Inheritance that forces a class module and using it in our code.
to implement specifics procedures or properties.
To create a class module we right-click in the Project
Objects window and then select Insert and Class Module. (Fig 1)
Using objects allows us to build our applications like we Fig 1
are using building blocks.
135
Copyright @ NIMI Not to be Republished
Let’s change the name of the class module to Dim oItem AsNew Class1
clsCustomer. Then we will add a variable to the class
module like this Dim oCustomer1 AsNewclsCustomer
People who are new to using classes and VBA class Debug.Print “Sample Output”
modules, often get confused between what is a class and
what is an object. End Sub
Let’s look at a real-world example. Think of a mass- You will note the code for both is exactly the same.
produced item like a coffee mug. A design of the mug is
created first. Then, thousands of coffee mugs are created To use the PrintCustomer sub from the class module,
from this design. you must first create an object of that type
This is similar to how class modules and objects work. ‘ Other Module
The object can be thought of as the item that is created Dim oCust AsNew clsCustomer
from the design.
oCust.PrintCustomer
The New keyword in VBA is what we use to create an
object from a class module. For example EndSub
‘ Creating objects using new To use Print Customer from the normal module you can
call it directly
136 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120
Copyright @ NIMI Not to be Republished
‘ Other Module Private dBalance As Double
Whencreate a variable in a normal module there is only Property Let Balance(dValueAs Double)
one copy of it. For a class module, there is one copy of
the variable for each object you create. dBalance = dValue
And can see they are all either functions, subs or variables. ‘ Public procedures can be called from outside the object
Let’s have a quick look at some examples before we deal Public Sub PrintText (sTextAs String)
with them in turn
‘ CLASS MODULE CODE Debug.PrintsText
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120 137
Copyright @ NIMI Not to be Republished
Public Function Calculate (dAmountAs Double) As In the above example we cannot access Balance because
Double it is declared as Private. We can only use a Private
variable within the class module. We can use in a function/
Calculate = dAmount - GetDeduction sub in the class module e.g.
‘ private procedures can only be called from within the Private Balance As Double
Class Module
Public SubSetBalance()
Private Function GetDeduction () As Double
Balance = 100
GetDeduction = 2.78
Debug.Print Balance
EndFunction
End Sub
We can use the clsSimple class module like this
It is considered poor practice to have public member
Sub Class Members () variables. This is because the code allowing outside the
object to interfere with how the class works. The purpose
Dim oSimple As New clsSimple of the using classes is so that hide what is happening
from the caller.
oSimple.PrintText “Hello”
To avoid the user directly talking to the member variables
Dim dTotal As Double we use Properties.
Note: Dim and Private do exactly the same Public PropertySet (varnameAsType )
thing but the convention is to use Dim in sub/
functions and to use Private outside sub/ EndProperty
functions.
We have seen already that the Property is simply a type
The Public keyword means the variable can be accessed
of sub. The purpose of the Property is to allow the caller to
from outside the class module. For example
get and set values.
Dim oAccount AsNew clsAccount
Use of Properties
‘ Valid - AccountID is public
Imagine we have a class that maintains a list of Countries.
oAccount.AccountID = “499789” We could store the list as an array
138 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120
Copyright @ NIMI Not to be Republished
‘ Set size of array when class is initialized Count = collCountries.Count
Private Sub Class_Initialize()
End Function
ReDim arrCountries (1 To 1000)
The caller is oblivious to how the countries are stored. All
the caller needs to know is that the Count function will
End Sub
return the number of countries.
When the user wants to get the number of countries in the
As we have just seen, a sub or function provides a solution
list they could do this
to the above problems. However, using a Property can
‘ NORMAL MODULE CODE provide a more elegant solution.
‘ Get the number of items Instead of the creating a Count Function we can create a
Count Property. As you can see below they are very similar
NumCountries = UBound(oCountry.arrCountries) + 1
‘ Replace this
There are two major problems with the above code
Public Function Count() As Long
1 To get the number of countries you need to know how
the list is stored e.g. Array. Count = UBound(arrCountries) + 1
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120 139
Copyright @ NIMI Not to be Republished
The second difference is that using Let and Get allows Set coll2 = coll1
us to use the same name when referencing the Get or
Let property. So we can use the property like a variable. • Let is used to assign a value to a basic variable type.
This is the purpose of using Properties over a sub and
function. • Set is used to assign an object to an object variable.
In the following example, we use Get and Let properties
oAccount.TotalCost = 6
for a string variable
dValue = oAccount.TotalCost
‘ CLASS MODULE CODE
If we used a function and a sub then we cannot get the
‘ SET/LET PROPERTIES for a variable
behaviour of a variable. Instead we have to call two different
procedures e.g. Private m_sName As String
oAccount.SetTotalCost 6 ‘ Get/Let Properties
dValue = oAccount.GetTotalCost Property Get Name() As String
You can also see that when we used Let we can assigned Name = m_sName
the value like a variable. When we use Set Total Cost,
we had to pass it as a parameter.
End Property
The Property in a Nutshell
Property Let Name (sNameAs String)
1 The Property hides the details of the implementation
from the caller. m_sName = sName
2 The Property allows us to provide the same behaviour End Property
as a variable.
We can then use the Name properties like this
Types of VBA Property
Sub Test Let Set()
There are three types of Properties. We have seen Get
and Let already. The one we haven’t looked at is Set. Dim sName As String
Set is similar to Let but it is used for an object(see Dim coll As New Collection
Assigning VBA Objects for more detail about this).
Dim oCurrency As New clsCurrency
Originally in Visual Basic, the Let keyword was used to
assign a variable. In fact, we can still use it if we like. ‘ Let Property
140 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120
Copyright @ NIMI Not to be Republished
End Property Msg Box “Class is being terminated”
Let’s create a very simple class module called clsSimple ‘ CLASS MODULE - clsSimple
with Initialize and Terminate events
Public Sub Init (Price As Double)
‘ CLASS MODULE CODE
EndSub
Private SubClass_Initialize()
‘ NORMAL MODULE
Msg Box “Class is being initialized”
Sub Class EventsTerm () ‘ oSimple is deleted when we exit this Sub calling Terminate
EndSub
142 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.120
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.121
COPA - Using Accounting Software
Introduction to Tally : Tally is an complete accounting mats in to the current data format. This is possible though
software. It is a versatile and massive software package, Import of Data Facility.
being used by various types of business Organisations.
Tally 6.3: Tally 6.3 is extended enterprise systems whereby
History of Tally it interacts with other system through ODBC (Open Data
Base Connectivity) you and e-mail upload your financial
Tally is a complete business solution for any kind of Busi- records form tally.
ness Enterprise. It is a full fledged accounting software.
Tally 7.2: This version is an integrated enterprise system
The Initial Release of Tally was Tally 4.5 version. This is provides different kind of taxes like VAT, TDS & TCS and
DOS (MS-DOS) based software released in the beginning Service Tax modules is introduced in this version.
of 1986's. It had Basic Financial Accounting / Book Keep-
ing Tools. Personal computers had gaining popularity in Tally 8.1: Tally 8.1 is multi language support software. It
India those days. supports 10 Languages includes is introduced in this ver-
sion.
Peutronics (The Company that develops Tally) used this
opportunity and put their Tally Version 4.5 on the market. Tally 9.0: This version is an improved model over the ver-
sion 8.1. it supports 13 Languages (Includes Foreign Lan-
Auditors and Accountants who used to maintain large vol- guages). Payroll, POS (Point of Sales) modules is intro-
umes of hard-bound notebooks were amazed at the abil- duced in this version.
ity of Tally to calculate Balance sheets and Profit Loss
accounts within seconds. All you need to do is just create Tally.ERP9: This is the latest version which provides dif-
Ledgers and enter vouchers. Tally will do the rest. It will ferent features like remote access,much powerful data
create all the statements, Trial Balance and Balance Sheet security, tally.net and many more.
For you.
Tally ERP9 is considered as the latest version.
The subsequent Tally releases are Tally 5.4, Tally 6.3,
Tally 7.2, Tally 8.1 and Tally 9.0, Tally ERP (Enterprise Features of Tally
Resources Planning). These release Include support for
Inventory used to stock maintenance of the company, 1 Accounting Features
Payroll which used to employee salary calculation and
wages payments and Multi Lingual support in Many In- i Handles different types of vouchers
dian languages Hindi, Tamil, Telugu, Kannada, Malayalam, - Payments Receipt
Gujarati, Marathi and more.
- Journals
Versions of Tally: - Debit Notes
Tally 4.0 & Tally 4.5: This version MS-DOS support finan- - Credit Notes
cial accounting system. It takes care of accounting activi- - Sales Notes
ties only such as Ledgers Classification Vouchers Entry.
It provides simple financial reports and bill wise analysis - Purchase Notes
of debtors and creditors in the business. - Receipt Notes
Tally 5.0: This version is an upgraded version to tally 4.5 - Delivery Notes etc.
and it works in windows operating system Inventory mod- ii Handles Primary Books of Accounts
ules is introduced in this version, which involves detailed
inventory, structure invoicing and integrating accounting - Cash Book
and Inventory records. - Bank Book
Tally 5.4: This version is an improved module over the ver- - Ledger
sion 5.0 where it is capable of converting earlier data for-
143
Copyright @ NIMI Not to be Republished
- Purchase registers 5 Technological features
- Sales Registers etc.,
- Tally allows importing data from other software as
iii Used to prepare Statement of Accounts well as exporting data from tally.
- Trial Balance - ODBC connectivity is available in Tally. We can
connect applications like MS Word, MS Excel,
- Profit and loss Accounts
Oracle and can use data from tally directly.
- Trade Accounts
- While working with tally, we can e-mail, browse a
- Balance Sheet website. We can send a report on document directly
- Funds Flow from tally.
- Funds flow and cash flow statements to track 1 Simple and Rapid Installation
movement of cash and funds in the company.
- Tally.ERP9's installation is a wizard driven, simple
- Tally computes interests as per book date. and speedy process involving minimal user-
- Tally provides Budgeting option. intervention. The software occupies tiny space and
can be installed on any drive. Tally.ERP9 supports
- Ratio Analysis provides important performance ratios installation on multiple systems connected to a
that give the pulse of the corporate health. network with different operating systems
(Windows98, NT, 2000, XP and Windows7)
3 Inventory Management Features
2 Auto Backup and Restore
- Flexible invoicing and billing terms.
- Flexible units of measure. - Tally.ERP9 provides automatic backup facility to
secure your company from any kind of data loss /
- Stock Transfer-Tally provides stock journal. corruption and helps in smooth functioning of your
- Stock query provides all relevant information for any business. Tally.ERP9 safeguards your data from any
stock item in a single screen. loss due to power failure or improper shutdown of
the system.
- Multiple stock valuation methods like FIFO, LIFO
and average methods are enhanced in Tally. 3 Tally Audit
144 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.121
Copyright @ NIMI Not to be Republished
6 Graphical Analysis of Data Tax, TCS (Tax Collected all Source), TDS (Tax
Deducted at Source), FBT (Fringe Benefit Tax), GST
- Tally.ERP9 allows easy analysis of results / reports (Goods and Service Tax).
with graphical representation of values.
8 E-Mail Facility
7 Duties and Taxes
- Tally.ERP9 supports mailing of required information
- Tally.ERP9 allows Statutory Reporting for VAT to intended recipients and also mass mailing facility
(Value Added Tax), CST (Central Sales Tax), Service for certain reports like Payslip etc.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.121 145
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.122
COPA - Using Accounting Software
Fig 1
1 Product info Button Bar: Buttons appearing in the button bar (at right
of the screen) provide quick access to different options.
2 Button bar
Buttons on the button bar is context sensitive, different
3 Calculator buttons appear at different screens.
4 Work area
Calculator: By default the work area becomes active and
calculator remains inactive. Press Ctrl + N that would
Product info: Product info bar in Tally.ERP9 consisting
activate the calculator when calculator is active, we can
of the information about the product.
enter value and operators.
1 Developer company
The calculator follows BODMAS rule that indicates the
2 Software version and Release execution sequence: Bracket, Power, Division,
3 Software Serial Number Multiplication, Addition and Subtraction.
146
Copyright @ NIMI Not to be Republished
Work area remain inactive and by default cursor would appear on
Create Company option.
The work at Gateway is broadly separated into two
sections. Buttons at gateway
1 The right hand side contains the popup menu, where Help (Hotkey: Alt+H): This button launches "Tally Reference
we would select instructions to Tally. Manual. This is a compiled HTML Help file. Normally on
clicking this button, the relevant content in respect of the
2 The left hand side displays list of selected companies.
screen would be displayed. If no context sensitive Help
On left part of the screen exists, contents would be displayed. We can select the
topic we wish to view.
Current Period
Web browser (Hot key: Alt+W)
Financial period with which we are working is displayed
for reference. To change the Financial period click This button launches the default installed web browser.
"F2:period" button in the button bar or press <Alt> + <F2>. For example, internet explorer is the default web browser,
on clicking the button IE will be loaded. The browser will
Current Date appear within the work area of the tally screen. All other
areas of Tally screen still remains in the screen.
It is not the calendar date but the date we worked last
during the current period. Vouchers will have the same F1- Select cmp (Hoy key: F1)
date as of current date. To change current date click
"F2:Date" button in the button bar or press F2. This button will display the list of companies. Move the
highlight bar and press <Enter> key to select a particular
List of selected companies company. Or simply press F1 key on the keyboard.
Name of all selected companies with last date voucher Introduction to Accounting
entry is displayed here. If we select more than one
company, the active company is shown at the top of list in It is the language of business through which normally a
bold face and others appear next in normal fonts. business house communicates with the outside world.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 147
Copyright @ NIMI Not to be Republished
Management Accounting Current Asset means the things and properties for resale
ie. The asset converts into cash. Eg. A cloth shop owner
The term management accounting refers to accounting for buys cloth for resale. Stock of cloth is current asset.
the management. The management accounting provides
information to the management so that planning, organis- Liabilities
ing directing and controlling of business operations can be
done in an orderly manner. All the amounts payable by a business concern to outsid-
ers are called liabilities.
Scope of Management Accounting
Capital
Following areas are identified within management ac-
counting Capital is the amount invested for starting a business by a
person.
1 Financial accounting
Debtor
2 Cost accounting
3 Revaluation accounting Debtor is the person who receives benefit without giving
money or moneys worth immediately, but liable to pay in
4 Budgetary control
future. i.e. the person owes amounts to the businessman.
5 Inventory control
Creditor
6 Statistical methods
7 Interim Reporting Creditor is the person who gives benefit without receiving
money or money's worth immediately but ot claim in fu-
8 Taxation
ture. i.e. the personto whom amounts are owed by the
9 Office services businessman.
10 Internal Audit
Debit: The receiving aspect of a transaction is called debit
or Dr.
Accounting terms
Credit: The giving aspect of a transaction is called credit
Business transaction
or Cr.
A business transaction is "The movement of money and
Drawings
money's worth form one person to another" or exchange
of values between two parties.
Drawings are the amounts withdrawn (taken back) by the
businessman from his business for his personal, private
Purchase means goods purchased by a businessman
and domestic purpose. Drawings may be made in the form
from suppliers.
cash, goods and assets of the business.
Sales is goods sold by a businessman to his customers.
Receipts
Purchase Return or Rejection in or Outward Invoice
It is a document issued by the receiver of cash to the giver
Purchase return means the return of the full or a part of of cash acknowledging the cash received voucher.
goods purchased by the businessman to his suppliers.
Account
Sales Return or Rejection out or Inward Invoice
Account is a summarized record of all the transactions
Sales return means the return of the full or a part of the relating to every person, everything or property and every
goods sold by the customer to the businessman. type of service.
Assets Ledger
Assets are the things and properties possessed by a busi- Ledger is the main book of account. It is the book of final
nessman in business. entry where accounts lie.
Fixed Asset means the asset remain in business of Journal is a book of first entry. Transactions are entered in
use and not for resale. Eg. A shop owner purchase the journal before taken to the appropriate ledger accounts.
buildings, typewriter, showcases
148 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122
Copyright @ NIMI Not to be Republished
Trial Balance Personal Accounts
Fig 1
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 149
Copyright @ NIMI Not to be Republished
GOLDEN RULES OF ACCOUNTING
Account Layout The benefits received by the account are recorded on the
left hand side. The benefits imparted by the account are
An account has two sides. The left hand side is known as recorded on the right hand side.
‘Dr’ or ‘Debit’ side. The right hand side is known as ‘Cr’ or
‘Credit’ side. The layout of an account looks like as under.
ACCOUNT
Dr Cr
Benefits Benefits
received Imparted
The receiving aspect which is known as ‘Debit’ is entered Double Entry : A business transaction is a transfer of
on the Debit side of the account. The giving aspect which money or money’s worth from one account to another. A
is known as ‘Credit’ is entered on the Credit side of the transfer requires two accounts. A business transaction
accounts. affects two account’s in the opposite directions. If one
account receives a benefit, the another account should
The principle under which both Debit and Credit aspects impart the benefit.
are recorded is known as the principle of Double entry.
Every debit must have a credit and vice versa. If the The principle of Double entry is based on the fact that,
accounts are not maintained under double entry system,
then the records are incomplete and known as single entry. There is no giving without receiving and
There is no receiving without giving
Sl.
No. Double Entry Single Entry
1 For every Debit there is a corresponding credit and There are no credits and Debits here
vice versa
3 A balance sheet and profit and loss statement can A balance sheet and profit and loss statement cannot
be prepared conveniently, since the books of be conveniently prepared since the accounting
accounts present a complete picture records are incomplete
4 Double Entry is a complete, scientific system of Single Entry is not a system. It is incomplete
keeping books of accounts and unscientific
150 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122
Copyright @ NIMI Not to be Republished
Personal Account - Examples: Cash goes out of the business and hence cash account
should be credited
1 Sold goods to Selvan on credit Rs.1,100/-
6 Paid rent Rs.250/-
Selvan account receives a benefit and hence should be
Cash goes out of the business and cash should be
debited
credited
2 Returned damaged goods to Sami.
In the above examples Sales Account Cash Accounts
Sami account receives a benefit and hence should be are real accounts. They are credited as per Rule.
debited
Nominal Accounts Examples:
3 Proprietor Thiru Anbu withdraws cash Rs.500 for house
hold expenses
1 Paid Rent Rs.250/-
Anbu - Drawing account receives a benefit and hence
Rent is an expense account. Hence rent account
should be debited
should be debited
In the above examples selvan a/c, Sami a/c, and Anbu
2 Paid salary Rs.1,200/-
- Drawings a/c are Personal accounts. They are
receivers of benefits and hence should be debited. Salary is an expense account. Hence salary account
should be debited
4 Anbu started business with cash Rs.50,000/-
3 Purchase of paper, pencils, ink, cover’s etc., for
Anbu - Capital a/c gives benefit in the form of cash to
Rs.250/-
business. Hence capital a/c should be credited
These are stationary items and expense items. Hence
5 Bought goods from Somu on credit for Rs.1,700/-
stationery account should be debited
Somu a/c gives a benefit and hence should be credited
In the above three examples Rent account, salary
6 Received five chairs from Godrej Co. at Rs.45 per chair account and stationery account all are nominal ac-
on credit basis counts. They are debited since they are expense items
Godrej Co a/c gives benefit in the form of 5 chairs. 4 Received commission Rs.500/-
Hence godrej co a/c should be credited.
Here commission is income to the business and hence
In the above examples capital a/c, Somu a/c and Godrej commission account should be credited.
a/c are personal accounts. They are giving benefits.
5 Received interest on loan given to B Rs.100/-
Hence their accounts should be credited.
Interest is income to the business. Hence interest
Real Account - Examples Account should be credited.
1 Bought five chairs [ furniture] from Godrej Co. at Rs.45 In the above two examples commission account and
per chair on credit basis. interest account are Nominal accounts. They have been
credited since they are incomes.
Furniture worth Rs.225 have come into the business as
per Rule, Debit what comes in. Since Furniture has
Books of Accounts
come in, Furniture Account should be debited.
2 Anbu started business with cash Rs.50,000/- Books of accounts can be generally classified into three
categories.
Cash of Rs.50,000 has come into the business and
hence cash account should be debited
1 Journal
3 Purchased goods from Somu on credit for Rs.1,700/-.
2 Ledger
Goods are bought in the aspect of purchases. Hence
3 Subsidiary Books
purchases account should be debited.
In the above examples, Furniture Account, cash ac- Journal : Journal is a book of prime entry. When a
count and purchases account are real accounts. Since transaction takes place, it is recorded in the Journal.
they have come into business, the accounts are deb- Layout of a Journal
ited.
4 Sale of goods to Selvan on credit Rs.1,100/- Date Particulars L.F. Dr. Cr.
(1) (2) (3) (4) (5)
Goods have gone out of the business hence sales
account is credited
5 Paid cash to Somu Rs.1,700/-
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 151
Copyright @ NIMI Not to be Republished
L.F means Ledger Folio. The L.F column is meant for Example 2
recording the page number of the concerned account in the
Ledger. The transactions recorded in the journal will be July 7, 2003 : Bought goods for cash Rs.1543.
posted to the appropriate accounts in the Ledger.
1 Purchase Account and Cash Account are affected.
Journalising : Journalising is the process of analysing the
2 Purchase Account and cash accounts are Real ac-
business transaction under the heads of debit and credit
counts.
and recording them in the journal.
3 Purchase Account should be debited since goods have
When journalising a transaction the following steps to be come into business. Cash account should be credited
followed. since cash has gone out.
3 Apply the rules for debit and credit. 2003 Purchase Account Dr. 35 1543 00
July 7th To cash Accounts 4 1543 00
Account type Debit Credit (Being cash
purchases of goods)
Personnal The Receiver The Giver
Accounts
Ledger
Real Accounts What comes in What goes out
The ledger is the main book of business containing
Personal, Real and Nominal accounts of the business. But
Nominal Accounts Expenses and Incomes and
transactions are not recorded in the Ledger directly. These
Losses Gains
are first entered in the Journal and then posted to the
In Journalising a transcation, the debit aspect is shown first concerned accounts in the Ledger.
with observation “Dr” after the name of the account. The
Layout of Ledger account
credit aspect is shown as a second item with the word “To”
at the beginning. A brief description of the transaction
An account is divided in the middle and the two sides are
known as “Narration” is given at the end of every entry in the
called debit side and credit side respectively.
journal.
Kannan Account (Personal Account)
Example 1
Dr. Cr.
1st July 2003 : Received cash from Muthu Rs.500
1 What are the accounts affected? Debit Kannan when he Credit Kannan when he
receives goods, money or gives goods, money or
Cash Account and Muthu Account value from the business value to the business
2 Types of Accounts
Cash account is a Real account Furniture Account (Real Account)
152 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122
Copyright @ NIMI Not to be Republished
The account end with “Dr” is to be debited in the Ledger. The
Interest received account (Nominal a/c) account starts with “To” is to be credited in the Ledger. It
is customary to write “To” on the debit side and “By” on the
Dr. Cr. credit side.
CAPITAL ACCOUNT
Dr. Cr.
2003
July 1 By cash 75,000 00
JOURNAL VS LEDGER
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 153
Copyright @ NIMI Not to be Republished
Layout of purchase book
2 Sales Book – Cash sales are not recorded in this sales book
– Sale of an old asset on credit is not recorded in the
This book is also called as “Sales Journal”, “Sold Book”,
sales book
“Sales Day Book”
154 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122
Copyright @ NIMI Not to be Republished
Layout of Cash Book
Dr Cr
Accounts Information - Grouping Expenditure incurred during current year but the amount
on which is not yet paid. (Added to the expenditure on the
Current Asset: It is converted into cash with in a year. debit side and entered on the liability side.)
Ex. Bills receivable.
Income received in advance or Income received but
Direct Expenses: These are the expenses which are di- not earned.
rectly related to manufacturing of goods. Ex. Wages, fac-
tory rent, heating, lighting etc., Income received during the currentyear but not earned or
a part of which relates to the next year. (Deducted from
Indirect Expenses: These are the expenses which are the concerned income on the credit side and entered on
indirectly related to manufacturing of goods. Ex. Salary, the liability side)
rent, stationery, advertisement, printing.
Prepaid advance or Expenses
Depreciation: Decrease the value of the asset.
Expenditure paid during current year but not incurred or a
Sundry debtors: The person who is the receiver or cus- part of which related to the next year is called expenditure
tomer. prepaid.
Sundry creditors: The person who gives or supplier. Income outstanding means income earned during the cur-
rent year but the amount on which is not yet received.
Expenses Outstanding or Unpaid expenses or Expenses
due:
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 155
Copyright @ NIMI Not to be Republished
Accounts information - Ledger - Grouping
Ledger Group
156 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122
Copyright @ NIMI Not to be Republished
Rates and taxes Indirect Expenses
Shortcut Keys
F11 Company features Alt+E To export the report in ASCII, SDF, HTML
or XML Format
F12 Configuration optionsare applicable to all
the companies in a data directory. Alt+I To insert a voucher
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 157
Copyright @ NIMI Not to be Republished
Journalize the following transactions 8 Paid cash to Mr. X Rs.1,000/-
5 Purchased goods form Mr. X on credit Rs.2,000/- 13 Purchased goods for cash Rs.1,500/-
6 Sold goods to Mr. Y on credit Rs.3,000/- 14 Sold goods for cash Rs.1,500/-
158 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122
Copyright @ NIMI Not to be Republished
Gateway of Tally - Account info - Ledger - Create
Gateway of Tally - Account voucher
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 159
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.123
COPA - Using Accounting Software
Introduction: The accounting for revenues, expenses, Trading Account : Trading refers to buying and selling of
assets and liabilities that is commonly carried on in the goods. Trading account shows the result of buying and
general offices of a business is termed as Financial selling of goods. This account is prepared to find out the
Accounting. difference between the selling price and cost price.
Its aim is to ascertain the profit or loss of the business and – If the selling price exceeds the cost price, it will bring
states the financial position of the business as at a Gross Profit. For example, If the goods of cost price
particular date. Rs.50,000 are sold for Rs.60,000 that will bring in Gross
Profit of Rs.10,000.
Financial accounting includes the following activities. – If the cost price exceeds the selling price, it will bring
Gross loss. For example, if the goods of cost price
i Book keeping Rs.60,000 are sold for Rs.50,000, that will result in
ii Preparation of Trading Account Gross Loss of Rs.10,000
iii Preparation of profit and loss account Thus Gross Profit or Gross Loss is indicated in Trading
Account.
iv Preparation of Balance Sheet
Items appearing in the Debit side of Trading account
Book-keeping : Book-keeping is the art of recording 1 Opening Stock : Stock on hand at the commence-
business transactions in a systematic manner. Main ment of the year or period is termed as the opening
objective of book-keeping is to calculate the profit or loss stock
of a business accurately.
2 Purchases : It indicates total purchases both cash and
We have discussed various types of Books of accounts in credit made during the year
the previous chapter. 3 Purchases returns or Returns outwords : Purchases
Advantages of Book-Keeping Returns must be subtracted from the total purchases to
get the net purchases. Net purchases will be shown in
1 Book-keeping provides reliable record of transactions
the trading account.
essential for ready reference.
4 Direct Expenses on Purchases : Some of the Direct
2 Profit or loss is ascertained using Books of accounts
Expenses are
3 Calculation of due amount the businessman has to pay
a Wages: It is also known as productive
others is done using Books of accounts
wages or Manufacturing wages
4 Borrowings and Assets are controlled.
b Carriage or carriage Inwards:
5 Financial position and growth of business is ascer-
c Octroi Duty : Duty paid on goods for
tained
bringing them within municipal limits
6 Do’s and Don’ts are identified
d Customs duty, Dock duty, clearing
7 Book-keeping is used for taxation and fixing selling charges, Import duty etc.,
price.
e Fuel, Power, Lighting charges related to
Final Account : Trading, Profit and Loss account, Balance production
sheet are prepared at the end of the year or at the end of
f Oil, Grease and Waste
the part. So it is called Final Account.
g Packing charges: Such expenses are
– Trading, Profit & loss account is prepared to find out
incurred with a view to put the goods in a
profit or loss of the organisation
saleable condition.
– Balance sheet is prepared to find out the financial
Items appearing on the credit side of trading account
position of the organisation
1 Sales: Total sales (Including both - cash and credit)
made during the year or period
160
Copyright @ NIMI Not to be Republished
2 Sales Returns or Return Inwards: Sales returns 3 Closing stock: Generally, closing stock does not
must be subtracted from the Total sales to get Net appear in the Trial Balance. It appears outside the Trial
sales. Net sales will be shown Balance. It represents the value of goods at the end of
the trading period.
xxxx xxxx
25,000 25,000
Example 2
ii Purchases Rs.16,100
Prepare a Trading Account from the following informations
iii Sales Rs.30,600
of a trader.
iv 2002 Dec 31 Closing Stock Rs.3,500
i 2002 Jan 1 Opening stock Rs.5,000
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 161
Copyright @ NIMI Not to be Republished
Trading Account for the year ending 31-12-2002
Dr Cr.
PROFIT and LOSS Account : Trading account reveals 2 Office Expenses : Expenses incurred on running an
Gross profit or Gross loss. Gross profit is transferred to office such as office salaries, rent, tax, postage,
credit side of profit and loss account. Gross loss is stationery etc.
transferred to debit side of the profit and loss account. Thus
3 Maintenance Expenses : Maintenance expenses of
profit and loss account is commenced. This profit & loss
assets. It includes repairs and renewals, depreciation
account reveals Net Profit or Net loss at a given time of
etc.,
accounting year.
4 Financial Expenses : Interest paid on loan, discount
Items appearing on Debit side of the P& L Account:
allowed etc., are few examples for Financial expenses.
The expenses incurred in a business is divided into two
Items appearing on credit side of P & L account :
parts. One is Direct expenses which are recorded in the
Gross profit is appeared on the credit side of Profit and Loss
trading account. Another one is indirect expenses which
account. Also other gains and incomes of the business are
are recorded on the debit side of profit & loss account.
shown on the credit side. Typical of such gains are items
Indirect Expenses are grouped under four heads: such as Interest received, Rent received, Discounts earned,
Commission earned.
1 Selling Expenses : All expenses relating to sales
Specimen Form:
such as carriage outwards, travelling expenses,
advertising etc.,
Profit & Loss Account for the year ended 31st March 2002
Dr Cr.
Particulars Amount Particulars Amount
Rs. P. Rs. P.
162 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123
Copyright @ NIMI Not to be Republished
Example 3 iii Tax, Insurance Rs.1,400 Discount allowed Rs.600
iv Discount received Rs.400
Prepare profit and loss account from the following balances
of Dharani Enterprises for the year ending 31.12.2012 v Travelling expenses Rs.2,600
vi Advertisement Rs.3,600
i Office rent Rs.3,000 Salaries Rs.8,000
vii Gross profit transferred from the trading account
ii Printing expenses Rs.2,200 Sationeries Rs.2,400
Rs.25,000
Profit and Loss Account of Dharani Enterprises for the year ending 31st Dec 2012
Dr Cr.
Particulars Amount Particulars Amount
Rs. P. Rs. P.
Prepare trading and Profit - Loss account for the year Postage 300
ending 31st March 2012 from the books of Swamy & Co., Salaries 5,000
Discount received 500
Rs.
Stationaries 1,000
Stock (15-01-1994) 15,000
Bad debts 100
Carriage Outwards 4,000
Interest 800
Purchases 1,65,000
Sales 3,00,000
wages 10,000
Insurance 400
Purchase returns 10,000
Closing stock 80,000
Trading and Profit and Loss account of Swamy & Co., for the year ending 31st March 2012
Dr Cr.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 163
Copyright @ NIMI Not to be Republished
If trial balance shows trading expenses as well Definition : The word “Balance Sheet’ is defined
as office expenses, the Trading expenses should as “ a statement which sets out the assets and
be shown in the trading account and office liabilities of a business firm and which serves to
expenses should be shown in profit and loss ascertain the financial position of the same on
account. On the otherhand if the trial balance any particular date”.
shown only a trading expenses, it should be
shown in the profit and loss account – On the left hand side of this statement, the liabilities and
capital are shown
In the trial balance, wages are clubbed with
salaries as ‘wages and salaries’. This item is – On the right hand side of this statement, all the assets
shown in Trading account. On the other hand, are shown
it appears as salaries and wages and this item – Hence both the sides of the balance sheet must be
is shown in the profit & Loss account. equal
Income tax : Income tax paid by a proprietor – Capital arrives assets exceeds the liabilities
is considered as personal expenses. So instead
of debited to Profit and Loss account, it should Objectives of Balance sheet
be debited to the capital account.
1 It shows accurate financial position of a firm
Balance sheet
2 It shows various transactions took place at a given
– Trading account provides the details of Gross Profit or period
Gross Loss 3 It indicates that, whether the firm has sufficient assets
– Profit and Loss account provides the details of the Net to repay in liabilities
Profit or Net Loss 4 The accuracy of final accounts is verified by this
– Besides the above, the proprietor wants statement
i to know the total assets invested in business 5 It shows the profit and loss arrived, through profit & Loss
account
ii To know the position of owner’s equity
iii To know the liabilities of business
SPECIMEN FORM OF A BALANCE SHEET:
BALANCE SHEET OF SUNIL ENTERPRISES AS AT 31.12.2012
Dr Cr.
Liabilities Amount Amount Assets Amount Amount
Rs. p. Rs. P. Rs. P. Rs. P
xxxx xxxx
The Balance sheet contains two parts. Assets : Assets represent everything which a business
owns and has money value. Assets are always shown as
1 Left hand side the liabilities debit balance in the ledger. Assets are classified as
2 Right hand side the assets follows:
164 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123
Copyright @ NIMI Not to be Republished
1 Tangible Assets : Assets which can be seen and felt Equation of Balance sheet
by touching are called Tangible assets. Tangible as-
sets are classified into two: Capital = Assets - Liabilities
a Fixed Assets : Assets which are durable in nature Liabilities = Assets - Capital
and used in business over and again are known as Assets = Liabilities + Capital
Fixed assets. E.g., Land and building, machinery,
trucks, etc., Trial Balance : When the transactions are recorded under
b Floating Assets or Current Assets : Current Assets double entry system, there is a credit for every debit. When
are one account is debited, another account is credited with
equal amount.
i Meant to be converted into cash
ii Meant for resale If a statement is prepared with debit balances on one side
and credit balances on the other side, the totals of the two
iii Likely to undergo change sides will be equal such a statement is called Trial
E.g: Cash, Bank Balance, stock, sundry debtor Balance.
2 Current Liabilities : Liabilities which are redeemed Sundry Creditors : There are a number of parties from
within a year are called current liabilities or short term whom the Trader buys goods on credit basis. All these
liabilities e.g., Trade creditors, Bank Loan creditors names are not written in the Trial Balance. A list
3 Contingent Liabilities : Liabilities which have the of creditors with the balances due to them is prepared and
following features are called contingent liabilities. They totalled. The total is written under the heading “sundry
are :- creditors” which appears in the Trial Balance.
a Not actual liability at present Preparation of Balance sheet : Once the Trial Balance
b Might become a liability in future on condition that is arrived, using that Trading account, Profit and Loss
the contemplatted event occurs. e.g., Liability in account and Balance Sheet can be casted.
respect of pending suit
Trial Balance Vs Balance sheet
1 It shows the balances of all ledger accounts It shows the balances of personal and real accounts only
2 It is prepared after the completion of the ledger It is prepared after the completion of trading and
accounts or arrival of the balances profit and loss account
3 Its object is to check the arithmetical accuracy Its object is to reveal the financial position of the business
4 Items shown in the trial balance are not in order Items shown in Balance sheet must be in order
5 It shows Opening Stock It shows Closing Stock
6 It has the headings, debit and credit. It has the headings of Assets and Liabilities
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 165
Copyright @ NIMI Not to be Republished
Example 5
5,23,400 5,23,400
Trading, Profit & Loss account of Sundar & Sons for the year ending 31-12-2012
Dr Cr.
Particulars Amount Particulars Amount
Rs. P. Rs. P.
166 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123
Copyright @ NIMI Not to be Republished
Balance sheet of Sundar & Sons as at 31.12.2012
Dr Cr.
2,78,200 2,78,200
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 167
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.124
COPA - Using Accounting Software
Costing Systems
Objectives: At the end of this lesson you shall be able to
• understand costing, its types and cost classification
• differentiate budgeting and standard costing
• cost centre, cost category, cost centre reports
• inventory accounting with tally
• inventory report, inventory books, statement of inventory.
Introduction : Costing refers to fixing the costs of a Cost classification : Cost classification is the process of
product. The factors which determines the cost of a product grouping costs according to their common characteristics.
are known as elements of cost.
Costs may be classified according to their nature and
number of characteristics such as function, variability,
Elements of cost : There are three cost elements exist
controllability and normality.
in costing. They are
1 Nature : Costs are classified according to their nature
1 Material cost
as
2 Labour cost
a Materials cost
3 Expenses
b Labour cost
– Material cost refers to the cost of raw materials used
c Expenses
for production of a product.
– Labour cost refers to the wages paid to the workers 2 Function : According to the divisions of activity, costs
in the manufacturing department. can be classified as
– Expenses refers to the expenditure by the way of
a Production cost
rent depreciation and power cut.
b Admistrative cost
Concept of Direct and Indirect costs : The total expendi-
c Selling cost
ture may be classified as Direct cost and Indirect cost.
d Distribution cost
Direct cost : The expenditure which can be conveniently
allocated to a particular job or product or unit of service is 3 Variability : According to their behaviour in relation to
known as direct cost. changes in the volume of production cost can be
classified as
Direct expenditure is made up of
a Fixed cost
1 Direct materials
b Semi fixed cost
2 Direct labour
c Variable cost
3 Direct expenses
4 Controllability : Costs are classified according to their
Indirect cost : The expenditure which cannot be conven- influences by the action of a given member of an
iently allocated to a particular job or product or unit of undertaking as
service is known as indirect cost.
a Controllable cost
In a firm producting a larger variety of articles most of the
b Uncontrollable cost
expenditure apart from materials and labour will be indirect.
5 Normality : Costs are classified according to the costs
Indirect expenditure is made up of
which are normally incurred at a given level of output as
1 Works of factory expenses
a Normal cost
2 Office and administrative expenses
b Abnormal Cost
3 Selling and distributive expenses
Presentation of total cost : The presentation of total cost
according to their nature is shown here.
168
Copyright @ NIMI Not to be Republished
Statement of total cost Add: Variable expenses ......................
“B” Marginal cost ......................
Rs.
Add: Fixed overhead ......................
Direct material cost ------------------
“C” Total cost ......................
Direct wage ------------------
Fixed and variable costs : Fixed costs are those costs
Direct expenses ------------------
which remain constant at all levels of production within a
“A” Prime cost ------------------ given period of time. In other words, a cost that does not
change in total but become, progressively smaller per unit
Add : Works on cost or when the volume of production increases is known as Fixed
Factory expenses ------------------ Cost. It is also called “Period Costs”.
“B” works cost ------------------ E.g., Rent, salary, Insurance charges, etc.,
Add: Office and administrative Variables costs are those costs which vary in accordance
Expenses ------------------ with the volume of output.
“C” cost of production ------------------ Absorption costing and Marginal Costing : Absorption
Add: Selling and Distribution costing is also termed as Traditional or Full Cost method.
In this method, the cost of a product is determined after
expenses ------------------ considering both fixed and variable costs. In absorption
“D” Cost of sale ------------------ costing all costs are identified with the manufactured
products.
Add: Profit or Less: loss ------------------
Marginal costing is a technique where only the variable
__________ costs are considered while computing the cost of a
“E” Selling price ------------------ product. The marginal cost of a product is in variable cost.
In this method only variable costs are changed to the cost
__________ units. Fixed cost is written against contribution for that
period.
The presentation of total cost according to their variability
is shown under. Hence we can derive a formula for contribution as under:
Statement of total costs Contribution = sale price - marginal cost
Rs. Standard costing : Standard costing is a specialised
technique of costing. In this costing standard costs are pre-
Direct Material cost ...................... determined. Actual costs are compared with pre-deter-
Direct wages ...................... mined costs. The variations between the two are noted and
analysed. Measures are taken to control the factors
Direct Expenses ...................... leading to unfavourable variations. Standard costing serves
“A” prime cost ...................... as an effective tool in the hands of the management for
planning, coordinating and controlling of various activities
of the business.
Budgeting Vs Standard costing
1 Budgeting considers operation of the business as a Standard costing considers only the control
whole Hence it is more extensive. of the expenses. Hence it is more intensive.
2 Budget is a projection of financial accounts. Standard cost is the projection of cost accounts.
4 Budgeting can be operated in part also. It is not possible to operate this system in parts.
5 Budget can be operated without any standards. Standard costing cannot exist without budget.
6 Budgets are maximum target of expenses above Standards are minimum targets which are to be attained
which actual expenses should not rise. by actual performance at specific efficiency level.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.124 169
Copyright @ NIMI Not to be Republished
Cost Centres : Cost Centre is a location, person or item For example, a company has three departments such as
of equipment, in relation to which costs may be ascertained Marketing, Finance and Production. Each department has
and used for the purposes of cost control. been identified as a cost centre. The wages paid to the
respective workers of the department concerned is the
Any raw material, labour or other input used by an direct cost of that particular cost centre(department).
organisation for the manufacturing process is cost which However, if the rent of the building in which the production
is allocatable as direct or indirect costs to cost centres. departments are located is apportioned to the departments
on a scientific basis, then it is termed as an indirect cost
1 Direct Cost : A cost which is allocated to a cost centre of the cost centre.
is a direct cost of that particular cost centre.
This is the example of use of Cost Categories. The
2 Indirect Cost : A cost which is apportioned to different
Salesmen A, B and C can be Cost Centres under a
cost centres on a suitable basis is an indirect cost of
Category Executive. Similarly, you can create a new Cost
that particular cost centre.
Category projects under which Cost Centres such as
Cost Category: Cost Categories are useful for Airport construction, Road construction and Buildings may
organisations that require allocation of Revenue and Non- be created. So that the classification appears as following
Revenue Items to parallel sets of Cost Centres. The
examples of Cost Categories can be Region-wise, Grade-
wise, Department-wise and so on.
Analysis using Cost Centres : Cost centre performance Ledger Break-up: This report displays the summary
can be measured using volume or relative percentage. For information of all Cost Centers for the selected Ledger.
example. Direct variable cost can be monitored as a
percentage of sales or even as a percentage of cost of Group Break-up: This report displays the summary
production if there are effective process controls. Indirect information of all Cost Centers for the selected Group.
expenses can be monitored by creating a reasonable limit
on the amount to be spent. Inventory Accounting With Tally : Inventory accounting
includes recording stock details, the purchase of stock,
The following elements have to be kept in mind while the sale of stock, stock movement between storage
measuring cost performance. Location or Godowns, and providing information on stock
availability. With Tally it is possible to integrate the inventory
1 Overall objective of the business. and accounting systems so that financial statements
reflect the closing stock value from the inventory system.
2 Changes in the business environment.
3 Ground realities. The inventory system operates in much the same way as
the accounting system.
Cost Centres in Tally : In Tally's cost centre allow for
multi dimensional analysis of financial information. The • First you set up the inventory details, which is a similar
cost centre feature in Tally allows you to allocate a operation to creating the chart of accounts although,
transaction to a particular cost entre, gives the cost centre in this case, there are No pre-defined set of stock
break-up of each transaction as well as details of groups.
transaction for each cost centre. A Profit and Loss
• Second, you create the individual stock items, which
Statement of every cost centre can also be obtained.
is similar to setting up the ledgers.
Cost Centre Reports : These are the following reports - • Finally, you are ready to use vouchers to record the
various stock transaction.
Category Summary : This report displays the summary
The Inventory features comprises of configurations/
of all the cost centers under a cost category.
functionality pertaining to Inventory transactions and
reports. The Inventory features are further sub-divided into
Cost Centre Break-up: This report displays Ledger and
seven sections:
Group summary information for the selected cost centre.
170 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.124
Copyright @ NIMI Not to be Republished
General 4 Stock Transfers : Stock transfer report display entries
made using stock journal vouchers.
Storage & Classification
5 Physical Stock Register : Physical stock register is
used to record actual stock available, i. e. Stock found
Order Processing
on conducting a stock check. It is not unusual to find a
Invoicing discrepancy between the actual stock and the computer
recorded stock figure. If inventory vouchers have been
Purchase Management configured to ignore physical stock differences, these
physical stock vouchers will be useful for recording
Sales Management purposes.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.124 171
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.125 & 2.3.126
COPA - Using Accounting Software
Introduction : Planning has become the primary function 1 Budget controller : The chief executive is ultimately
of management these days. Budgets are nothing but the responsible for the budget programme. But large part of
expressions, largely in financial terms of management’s the supervisory responsibility is deligated to an official
plan for operating and financing the enterprise during designated as budget controller or budget director. The
specific periods of time. budget controller should have knowledge of the techni-
cal side of the business and should report direct to the
A budget is a detailed plan of operations for some specific president of the organisation.
future period. It is an estimate prepared in advance of the
2 Budget committee : The Budget controller will be
period to which it applies. It acts as a business barometer
assisted in his work by the Budget committee. The
as it is complete programme of activities of the business for
budget committee will consists of heads of the various
the period covered.
departments as production, sales, finance, etc., Budget
controller is the chairman of the committee. It will be the
Essentials of a Budget
duty of the budget committee to submit, discuss and
a It is prepared in advance and is based on a future plan finally approve of the budget figures. Each Head of the
of actions Department will have his own sub-committee with
b It relates to a future period and is based on objectives executive working under him as in members.
to be attained
Fixation of the Budget Period : Budget period means
c It is a statement expressed in monetary and / or the period for which a budget is prepared and employed.
physical units prepared for the implementation of policy
formulated by the management. The budget period will depend upon the following:
Budget manual : The budget manual is a written docu- 1 The nature of the business and
ment or booklet which specifies the objectives of the
2 The control techniques to be applied
budgeting organization and procedures.
For example, a seasonal industry will budget for each
The following are the important matters covered in a budget
season. An industry requiring long periods to complete
manual
work will budget for 3 or 4 or 5 years. But Budget period
should not be longer than that of what is necessary.
1 A statement regarding the objectives of the organisa-
tion and how they can be achieved through budgetary
Budget Procedure
control.
2 A statement regarding the functions and responsibili- Determination of key factor : Key factor indicates whose
ties of each executive regarding preparation of budget influence must first be assessed in order to ensure the
and execution of budget. accomplishment of the functional budgets. Functional
budget is related to different functions of a business, e.g.,
3 Procedures to be followed for obtaining the necessary
sales, production, purchases, cash, etc.,
approval of budgets.
4 Time table for all stages of budgeting. The budget related to the key factor should be prepared
first. Then the other budgets.
5 Reports, statements, forms and other records to be
maintained.
General list of key factors in different industries are given
6 The accounts classification is to be employed. below:
Responsibility for Budgeting : There are two things Industry Key factor
responsible for budgeting. They are the budget controller
1 Motor car Sales demand
and the budget committee.
2 Aluminium power
172
Copyright @ NIMI Not to be Republished
3 Petrolium Refinery Supply of crudeoil d Purchase Budget : This budget forecasts the quantity,
and value of purchases required for production. It gives
4 Electro optics Skilled technicians
quantity -wise, money-wise and period - wise informa-
5 Hydral power generation Monsoon tion about the materials to be purchased
Making of forecasts : A forecast is the statement of facts e Personnel Budget : This budget anticipates the quan-
likely to occur that may affect the flow of budget. Forecast tity of personnel required during a period for production
is done before the budgeting starts. Forecasts are made activity
regarding sales, production cost and financial require- f Research Budget : This budget relates to the research
ments of the business. works for improvement in quality of products or research
for new products.
Consideration of alternative combination of forecasts:
g Capital Expenditure Budget : This budget provides a
Alternative combinations of forecasts are considered with
guidance regarding the amount of capital that may be
a view to obtain the most efficient overall plan so as to
required for procurement of capital assets during the
achieve maximum profit.
budget period
Preparation of Budgets : After finalising the forecasts, h Cash Budget : This budget forecasts the cash position
the actual budgets will be prepared. One budget may be by time period for a specific duration of time
prepared on the basis of the other budget. For example
i Master Budget : This is a summary budget incorporat-
production budget will be prepared on the basis of the sales
ing all functional budgets in a capsule form.
budget.
Flexibility based Budget
Classification of Budgets
a Fixed Budget : A budget prepared on the basis of a
Budgets can be classified into three most common types
standard or a fixed level of activity is called a fixed
1 Time based Budget budget. It does not change with the change in the level
2 Function based budget of activity
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.125 & 2.3.126 173
Copyright @ NIMI Not to be Republished
Several Scenarios are demonstrated in a scenario analysis standard amount and the actual amount incurred/sold.
to show possible future outcomes. It is useful to generate Variance analysis is usually associated with explaining
a combination of an optimistic, a pessimistic and a most the difference (or variance) between actual costs and the
likely scenario. standard costs allowed for the good output. For example,
the difference in materials costs can be divided into a
Variances : Variances can be computed for both costs materials price variance and a materials usage variance.
and revenues. The difference between the actual direct labor costs and
the standard direct labor costs can be divided into a rate
The concept of variance is connected with planned and variance and an efficiency variance. The difference in
actual results. It is effect to the difference between those manufacturing overhead can be divided into spending,
two on the performance of the company. efficiency, and volume variances. Mix and yield variances
can also be calculated.
Variance Analysis : Variance analysis is a tool of budg-
etary control by evaluation of performance by means of Variance analysis helps the management to understand
variances between budgeted amount, planned amount or the present costs and thereafter control the future costs.
174 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.125 & 2.3.126
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.127 & 2.3.128
COPA - Using Accounting Software
Introduction : In a trading business one of the current 250 units @ Rs.11.50 Rs.2,875
assets is stock. It represents goods owned by the company
50 units @ 11.00 Rs. 550
that are for sale to customers. The owners always aware
of stock. Once a year the stock is counted and valued.
Total Rs.3,425
The system used for counting stock and evaluating the
LIFO : In this case the latest consignments are used first.
value of the stock is known as Inventory system. When
Hence the closing stock is supposed to be out of the
business has a more extensive stock, Inventory system is
earliest lots on hand. For the above example, the stock will
used. Stock is controled with the Inventory system.
be valued at Rs.3,100, as under:
Closing stock and its valuation : Closing stock means
200 units @ Rs.10 Rs.2,000
closing stock of raw materials or goods manufactured. The
closing stock must be valued and an entry passed at the 100 units @ Rs.11 Rs.1,100
end of the year. Rs.3,100
– Suppose an article is purchased for Rs.100. If the article Average Method : In this case all the lots are merged
remains unsold at the end of the year, it will be included together and value of the closing stock is calculated
in the closing stock at Rs.100 even if the selling price accordingly. The average may be simple or weighted.
is more
– But if the article can now be sold at Rs.95only, it should Simple average Method : In this method, the average
be included in the closing stock at Rs.95 only price for single unit is
– Goods which cannot be sold at all should not be = Rs.10 + Rs.11 + Rs.11.50
included in the closing stock. 3
= 32.50
Casting stock Value : Stock value can be calculated in 3
four methods. They are
= Rs.10.83
1 First in First out (FIFO)
The value for closing stock is = 300 x 10.83 = Rs.3,249
2 Last In First Out (LIFO)
3 Average Weighted Average method : Weighted average method
is most suitable, since the quantities are also taken into
4 Base stock method
account.
FIFO : In this case the earliest lots are exhausted first. The
In this method the average price for single unit is Rs.10.90,
stock on hand is out of the latest consignments received
calculated as under.
and is valued accordingly.
Suppose following lots were received: Number of units price Amount
16th October 200 units @ Rs.10 Rs. Rs.
20th November 300 units @ Rs.11
200 10 2,000
15th December 250 units @ Rs.11.50
300 11 3,300
The closing stock consists of 300 units . The value will be
250 11.50 2,875
175
Copyright @ NIMI Not to be Republished
Unit cost = 8,175 2 Sales made during these two weeks amounted to
Rs.3000. The firm makes a gross profit of 33 1/3% on
750
sales. Find out the value of closing stock on 30th June,
= 10.90 2001.
The value of 300 units = 300 x 10.90 For this case the statement of stock can be calculated as
under:
= Rs. 3,270
Statement of stock
Base Stock Method : In this method, the minimum stock
carried by the factory is valued at the price originally paid Stock on 30th June 2001
for it. The excess of actual stock over the minimum level is
Rs.
valued according to the current cost, calculated in one of
the three methods given above. Sales 3,000
Less 33 1/3% on sales 1,000
Suppose the minimum stock is 200 units and the original
price paid was Rs.8 per unit. Sales at cost 2,000
Value of stock two weeks after 22,500
The value of stock of 200 units @ Rs.8 = Rs.1,600
30th June 2001
The value of remaining 100 units is calculated with the unit
Less:purchases during 2 weeks 500
price of Rs.11.50 or Rs.11.00 or 10.83 or 10.90
Value of stock on 30th June 2001 22,000
Statement of stock : M/s. Nanda & Bose close their
financial books on 30th June 2001. Stock taking continues
for two weeks after this date. In 2001, the value of stock Inventory control and Reordering : Inventory control
came to Rs.20,500, without making adjustments for the system always monitors the availability of stock. In any
following:- business minimum stock should be maintained for
uninterupted sale. If the minimum stock level falls, then the
1 Purchases made during the two weeks after 30th June purchase order for that product is to be made.
2001 were Rs.500
The minimum stock level below which purchase order is to
be made is known as reorderlevel. If the stock level falls
below the reorder level purchase order is proposed.
Example
Purchase order should be made for the items 10284, In Accounting, there are many standard ratios used to try
10286, 10287, 10288. Hence the purchase order can be to evaluate the overall financial condition of a corporation or
proposed using the inventory control system. other organization. It are also compared across different
companies in the same sector to see how they stack up,
Ratio Analysis : Ratio Analysis is used to evaluate various and to get an idea of comparative valuations.
aspects of a company's operating and financial perform-
ance such as its efficiency, liquidity, profitability and Types of Ratios :
solvency.
1 Financial Ratios : These are categorized according to
the financial aspect of the business which the ratio
176 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.127 & 2.3.128
Copyright @ NIMI Not to be Republished
measures. It allow for comparisons between compa- Fund Flow Accounting : These statements give the
nies, between industries, between different time peri- information of funds on a particular date. The purpose of
ods for one company, between a single company and preparation of funds flow statements is to know about from
its industry average. where funds are coming and where being invested. The fund
flow stalemates is generally prepared from the data iden-
2 Liquidity Ratios : It is measure that the availability of
tifiable and profit and loss account and balance sheets.
cash to pay debt.
Fund Flow statement is also called as sources and
3 Activity Ratios : It is measure how to quickly a firm application of funds. It shows the detail of funds business
converts non-cash assets to cash assets. received from sources and the amount of funds the busi-
4 Debt Ratios : It is measure the firm's ability to repay ness used for different purpose in the year.
long-term debt.
Invoice : While making a sale, the seller prepares a
5 Profitability Ratios : It is measure the firm's use of its statement giving the particulars such as the quantity, price
assets and control of its expenses to generate an per unit, the total amount payable, any deductions made
acceptable rate of return. and shows the net amount payable by the buyer. Such a
6 Market Ratios : It is measure the investor response to statement is called invoice.
owning a company's stock and also the cost of issuing
An invoice is a statement of list of goods with their quantity
stock.
and price.
Cash Flow Accounting : In accounting cash flow is the
An invoice is a business document which is prepared by
difference between the amount of cash available at the
sellers and given to buyers. Usually the invoice are pre-
opening balance (beginning of a period) and the amount at
pared in triplicate one copy will be issued to the buyer. The
the closing balance (end of that period).
after two copies will be retained by the seller.
When Cash is coming in from customers or clients who are
Inward Invoice : To the buyer, he calls the invoice as
buying your products is called accounts receivable and
'inward invoice'. He enters the details of the invoice in his
when the cash is going out of your business in the form of
purchase book.
payments for expenses like rent, loan payment is called
accounts payable.
Outward Invoice : To the seller, he calls the invoice as
'outward invoice'. He enters the details of the invoice in his
The net cash flow of a company over a period is equal to the
sales book.
change in cash balance over this period : positive if the cash
balance increases, negative if the cash balance decreases.
Details of the Invoice : The invoice should give the
The total net cash flow is the sum of cash flows that are
following details:
classified in three areas:
1 Name and address of the seller
1 Operational Cash Flows : Cash received or expended
as a result of the company's internal business activi- 2 Name and address of the buyer
ties. It includes cash earnings plus changes to working
3 Invoice Number
capital.
4 The Date
2 Investment Cash Flows : Cash received from the sale
of long-life assets, or spent on capital expenditure. 5 Quantity, description, unit price, amount of the goods
sold
3 Financing Cash Flows : Cash received from the issue
of debt and equity, or paid out as dividends, share 6 Trade discount and cash discount, if necessary
repurchases or debt repayments. 7 Expenditure
In financial accounting, a cash flow statement is also 8 Net amount
known as statement of cash flows which is a financial 9 Signature of the invoicing authority
statement that shows how changes in balance sheet
accounts and income affect cash and cash equivalents, 10 E. & O. E. at the left bottom corner of the invoice
and breaks the analysis down to operating, investing and
financing activities. The cash flow statement is concerned E. & O. E. means Errors and Omission Excepted. This
with the flow of cash in and out of the business. indicates that if errors and omissions are found out, the
matter can be reported and settled and the seller under
takes to correct them.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.127 & 2.3.128 177
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.129
COPA - Using Accounting Software
178
Copyright @ NIMI Not to be Republished
• Employee stock option plans (ESOPs) have also been Invoice
brought under fringe benefits tax from the fiscal year
2007-08. Rule 4A prescribes that taxable services shall be provided
and input credit shall be distributed only on the basis of a
Indirect Taxes : Indirect Tax, imposed on commodities, bill, invoice or challan. Such bill, invoice or challan will
is indirectly borne by the people. It includes value added also include documents used by service providers of
tax, sales tax, customs duty, excise duty. In the case of banking services (such as pay-in-slip, debit credit advice
indirect taxes, the person on whom the incidence to pay etc.) and consignment note issued by goods transport
the tax falls is different from the person who carries the agencies. Rule 4B provides for issuance of a consignment
burden of paying the tax. note to a customer by the service provider in respect of
goods transport booking services.
Service Tax
Value Added Tax : The Government of India has, after
Service Tax is a tax imposed by Government of India on committing to the World Trade Organization regime,
services provided in India. The service provider collects decided to modernize and streamline its indirect taxation,
the tax and pays the same to the government. It is charged in the light of the experience of other WTO member
on all services except the services covered in the negative countries. The Government has availed of the services of
list (Section 66d of Finance Act'1994) of services & services the international management consulting firm for drafting
covered under Mega Exemption Notification (Notification of rules, procedures and forms for introduction of VAT. VAT
NO. 25/2012 ST dated 20.06.2012). The current rate is is prevalent in over 140 countries including India.
12.36% on gross value of the service. Introduction of VAT would be a historic reform of the
domestic trade tax system. It is expected to facilitate the
Dr.Raja chelliah committee on tax reforms recommend states and union territories to transit successfully from
the introduction of service tax. Service tax had been first the erstwhile sales tax system to modern domestic system.
levied at a rate of five per cent flat from 15 July 1994 till 13
May 2003, at the rate of eight percent flat w.e.f 1 plus an A Value Added Tax (VAT) is applies the equivalent of a
education cess of 2% thereon w.e.f 10 September 2004 le sales tax to every operation that creates value. The example
services provided by service providers. The rate of service is a Toy manufacturer company imported plastic. That
tax was enhanced to 12% by Finance Act, 2006 w.e.f company will pay the VAT on the purchase price, remitting
18.4.2006. Finance Act, 2007 has imposed a new that amount to the government. The company will then
secondary and higher education cess of one percent on use the plastic into a toy, selling the toy for a higher price
the service tax w.e.f 11.5.2007, increasing the total to a wholesale distributor. The company will collect the
education cess to three percent and a total levy of 12.36 VAT on the higher price, but will remit to the government
percent. The revenue from the service tax to the only the excess related to the "value added". The wholesale
Government of India have shown a steady rise since its distributor will then continue the process, charging the
inception in 1994. The tax collections have grown retail distributor the VAT on the entire price to the retailer,
substantially since 1994-95 i.e. from Rs. 410 crores in but remitting only the amount related to the distribution
1994-95 to Rs.132518 crores in 2012-13. The total number mark-up to the government. The last VAT amount is paid
of Taxable services also increased from 3 in 1994 to 119 in by the retail customer who cannot recover any of the
2012. However, from 1 July 2012 the concept of taxation previously paid VAT. For a VAT and Sales Tax of identical
on services was changed from a 'Selected service approach' rates, the total tax paid is the same, but it is paid at differing
to a 'Negative List regime'. This changed the taxation points in the process.
system of services from tax on some Selected services to
tax being levied on the every service other than services VAT is usually administrated by requiring the company to
mentioned in Negative list. complete a VAT return, giving details of VAT it has been
charged (input tax) and VAT it has charged to others
Service Tax Return (output tax). The difference between output tax and input
tax is payable to the Local Tax Authority.
According to Rule 5 of Service Tax Rules, 1994, records
include computerized data and means the record as If input tax is greater than output tax the company can
maintained by an assessee in accordance with the various claim back money from the Local Tax Authority.
laws in force from time to time. Records maintained as
such shall be acceptable to Central Excise Officer. Every Mechanism of tax credit:
assessee is required to furnish to the Central Excise Officer
at the time of filing his return for the first time a list of all For the VAT auditors, the knowledge of tax credit is utmost
accounts maintained by the assessee in relation to Service important. Therefore it is necessary to understand the
Tax including memoranda received from his branch offices. mechanism of tax credit.
This intimation may be sent along with a covering letter
while filing the service tax return for the first time. WHAT is Tax Credit ?
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129 179
Copyright @ NIMI Not to be Republished
2 It is available to registered Purchasing Dealer. Tally.ERP 9 ensures you generate GST invoices and
transactions as per the GST format.
3 Availability of the credit of tax paid on purchases of
taxable goods.
Able to file GSTR-1, GSTR-3B and GSTR-4 on your own
4 Tax credit is available at the point of purchases. by exporting data to the Excel Offline Utility tool or in
JSON format as per the GST portal. The unique error
5 Purchases of goods should be intended for the specific
detection and correction capability ensures that you file
purposes.
returns accurately.
6 Original Tax Invoice is must stating separate amount
of tax charged. When it comes to e-Way Bills, Tally.ERP 9 helps you to
easily generate and manage e-Way Bills. You can capture
7 Tax credit is not dependent or related either sale of
all the required information at invoice level itself, export
very goods or it is used in manufacturing.
the data in JSON format and upload the data in the e-Way
8 Tax Credit is adjustable against payment of tax / liability portal to generate the e-Way Bill.
of tax.
In the year 2005, VAT was introduced to overcome
GST (Goods and Services Tax) cascading affect (tax on tax). While VAT did eliminate the
cascading tax effect on the indirect taxes within a state,
- Goods and Services Tax (GST) is an indirect tax levied the cascading effect of other indirect taxes across the
in India on the supply of goods and services. country, still remained. For example, the Central Sales
- GST has been introduced to replace multiple indirect Tax (CST) applicable on interstate trade was non-creditable,
taxes levied by State and Central Governments in order leading to a break in the input credit chain. Similarly, a
to simplify the indirect tax. manufacturer charging Excise Duty on sale to a dealer
caused the chain to break. This uncreditable tax found its
- GST is levied at every step in the production process, way into the product cost.
but is refunded to all parties in the chain of production
other than the final consumer. GST on the other hand, allows for seamless flow of tax
- GST is a comprehensive Value Added Tax (VAT) on credit, and eliminates the cascading effect of all indirect
goods and services. taxes across the supply chain from manufacturers to
retailers, and across state borders.
- France was the first country to introduce this system
in 1954. Today it has spread to over 140 countries. A quick comparison of the taxes one paid in the previous
- Comprehensive dual GST has been implemented in regime and in the current regime, will able to understand
India Since 1st July 2017. the aspect of GST vs VAT clearly.
GST means different things to different stakeholders. • Previous Regime-Taxes paid by the dealer (Excise)
Businesses registered as regular dealers need to file their to the manufacturer is added to the cost. When the
GSTR-1 on a monthly basis if their aggregate turnover dealer sells down the chain, VAT keeps getting charged
exceeds 1.5 Cr. Businesses with aggregate turnover less on the sum of actual product cost + excise component,
than 1.5 Cr have to do GSTR-1 return filing on a quarterly and the VAT keeps getting levied at every point of sale,
basis. Also, both the businesses need to file their GSTR- till it reaches the end customer.
3B on a monthly basis.
• GST Regime- Taxes paid by dealer (CGST + SGST)
On the other hand, composite dealers have to file GSTR- to manufacturer is not added to cost. This is because
4 on a quarterly basis. Also, going forward, as e-Way bill GST allows the dealer to set off the tax liability of CGST
becomes mandatory for interstate and intrastate + SGST. This is one of the fundamental features of
movement of goods worth Rs. 50,000/- GST, which allows seamless credit from manufacturer
to dealer, and eliminates the cascading effect of taxes.
Components of GST? At the 26th GST Council meeting, it has been decided to
implement he inter-state e-way bill from 1st April, 2018.
There are 3 taxes applicable under GST: CGST, SGST & For intra-state movement, the e-way bill will be rolled out
IGST. in a phased manner starting from 15th April, 2018, such
that all states are covered by 1st June, 2018.
CGST: Collected by the Central Government on an intra-
state sale (Eg: Within the same State) Eway bill - Introduction
SGST: Collected by the State Government on an intra- In its 22nd meeting, the GST Council decided and
state sale (Eg: Within the same State ) recommended that the e-way bill under GST shall be
introduced in a staggered manner from 1st January, 2018,
IGST: Collected by the Central Government for inter-state and will be rolled out nationwide from 1st April, 2018.
sale (Eg: one state to another state)
180 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129
Copyright @ NIMI Not to be Republished
However, at the recently concluded 24th GST Council If the recipient of goods doesn’t communicate acceptance
meeting held on 16th December, 2017, it was announced or rejection within 72 hours, it will be deemed as accepted
that the e-way bill will be launched from the 1st of February, by the recipient. The facility of generation and cancellation
2018 – a full two months ahead of the earlier plan. of E-Way Bill will be made available through SMS.
The GST Council, reviewed the readiness of the hardware HSN stands for Harmonized system of Nomenclature which
and software required for the nationwide rollout of e-way was developed by world customs organisations (WCO)
bill, and has announced the renewed date, post discussions with the vision of classifying goods all over the world in a
with all the States. systematic manner.
The E-Way Bill is applicable for any consignment value HSN Contains six digit uniform code that classifies
exceeding INR 50,000. Even in case of inward supply of 5000 + products and which is accepted world wide. HSN
goods from unregistered person, E-Way Bill is applicable. code describes the commodity/product.
The E-Way Bill needs to be generated before the
commencement of movement of goods. Form GST EWB- India has already been using HSN system in the central
01 is an E-Way Bill form. It contains Part A, where the excise and customs regime.
details of the goods are furnished, and Part B contains
vehicle number. For multiple Consignments the transporter Tax payers whose turnover is below Rs.1.5 crores are not
should generate a consolidated E-Way Bill in the Form required to mention HSN code in their invoices. The list of
GST EWB 02 and separately indicate the serial number HSN codes are available in public domain.
of E-Way Bill for each of the consignment.
The E-Way Bill format in GST comprises of 2 parts – Part
Upon generation of the E-Way Bill, on the common portal, A and Part B.
a unique E-Way Bill number called ‘EBN’ will be made
available to the supplier, the recipient and the transporter.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129 181
Copyright @ NIMI Not to be Republished
GST E-Way Bill Format A.7 : Reason for Transportation : The reason for
transportation is pre-defined and you need to select the
FORM GST EWB-01 most appropriate option from the list.
A.6 : HSN Code :enter the HSN code of goods which are PART-B
transported. If your turnover is up to INR 5 crores, you
need to mention the first 2 digits of HSN code. If it is more B.1 : Vehicle Number : the vehicle number in which goods
than INR 5 crores, 4 digits of HSN code are required. are transported needs to be mentioned. This will be filed
by the transporter in the common portal.
182 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.130
COPA - Using Accounting Software
Utilities
Objectives: At the end of this lesson you shall be able to
• utilities in Tally
• split company data
• export master data
• import master, vouchers
• enable Tally vault password.
• Back Up / Restore
• Tally.ERP 9 Vault
• Importing Data
• Consolidation of Accounts
• Credit Limits
• Interest Calculations
Splitting Company Data based on Financial Years • The company data is verified to ensure that no errors
occur during splitting using the Verify Company Data
Prerequisites for splitting company data option.
Before splitting the data, the user must ensure that: To split the company data
• A backup of the data exists. 1 Go to Gateway of Tally > F3 : Cmp Info . > Split
Company Data > Select Company .
• All unadjusted forex gains/losses have been fully 2 Select the required company from the List of
adjusted by recording journal entries. Companies .
• No purchase/sales bills are due. Check the Profit & 3 Enter the required date in the Split from field.
Loss A/c and inventory statements (purchase/sales
bills pending). You have to account them in the
respective party accounts or in the bills pending
account.
183
Copyright @ NIMI Not to be Republished
The Split Company Data screen appears as shown below: Fig 2
(Fig 1)
Fig 1
Importing Masters
184 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.130
Copyright @ NIMI Not to be Republished
Importing Vouchers 2 In the Change Tally Vault screen select the required
company from the List of Companies.
Importing vouchers from one company to another in
3 Enter the Password in the New Password field.
Tally.ERP 9 could be due to the following reasons:
Tally.ERP 9 displays the strength of the password
entered depending on the combination - Alphabets,
• Data corruption/loss.
Numbers and Special Characters.
• Migrating into a later release.
4 Re-enter the password to confirm in the Repeat New
• Importing data from third party. Password field.
To import vouchers 5 Accept to Change the Tally Vault password.
1 Go to Gateway of Tally > Import Data > Vouchers . 6 Tally.ERP 9 displays a message Created New
Company followed by the new Company Number, press
2 Enter the name of the .xml file to be imported, in the any key to return to Company Info menu.
Import Vouchers screen, as shown below: (Fig 4)
Once the company data is encrypted the Name of the
Fig 4
Company and Financial Year will not be visible in the Select
Company screen.
The user can enter the Tally Vault password while creating
the company or execute the following steps to provide the
TallyVault password for existing companies.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.130 185
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.131
COPA - Using Accounting Software
You can create users, assign security levels, restrict/allow Taking backup is easy in tally and you just provide the
remote access and local TDLs for the users created. source and destination location of the backup data.
To create the user and assign a password execute the You can create a main backup directory with subdirectories
following steps: to take daily backup, for example, you can create a
directory named tally backup with the subdirectories
Go to Gateway of Tally > F3: Company Info > Security named.
Control
Perform the following steps to take the backup of data in
1 Select Users and Passwords Tally ERP 9
2 The List of Users for Company screen is displayed as
- Click the F3 Comp info: button on the button bar in the
shown Fig 1.
gateway of tally screen the company info menu appears
Fig 1 - select the backup option from the company info menu
as shown in Fig 3
Fig 3
Fig 2
Tally.erp 9 provides the mechanism of taking a back up To activate a backup option of auto backup
data from on store medium into another storage 1 Go to a gateway of Tally > Alt + F3: comp info > Alter
medium.You can take a backup on the local drive or in an and select company from the list.
external media.
186
Copyright @ NIMI Not to be Republished
2 Company Alternation screen appears. To restore Auto Backup Data
3 Enable auto backup? set to Yes
1 Go to Gateway of Tally > ALt + F3: Comp info >Restore.
4 Accept the company
2 In destination, field type the path in which you want to
5 Press ESC to come on Gateway of Tally Screen restore the back up data.
6 GO to Gateway of tally F12: Configuration > Date 3 In source, field type the path: D:\autobackup.
Configuration
4 In auto Backup section list of auto, backup appears
7 In location of auto backup files type the path in which select company from the list.
path you want to get back up D:\autobackup
5 In backup version select the latest backup.
8 Accept the data configuration Screen.
9 Message appears that do you want to restart Tally for
the change to have effect press Y.
10 Now when you close the Company Tally take the
backup automatically.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.131 187
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.3.132
COPA - Using Accounting Software
List of Accounts : Tally.ERP9 gives great flexibility in list • E-Mailing : with this option you can configure the e-
of accounts which displays the list as groups in mailing facility.
alphabetical order. The groups are in bold and begin on
• Data Configuration : with this option you can configure
the extreme left. The sub-groups are also in bold and the
the path where the language, data and configuration
ledger accounts are in italic and in the lowest level. The
files reside.
report is drill down and if press the enter key and then it
display ledger Alteration (Secondary) screen through the • Advanced Configuration : with this option you can
ledger accounts. configure the Client / Server, ODBC, Connection, Log,
Tally.NET.
Configuration in Tally : Tally.ERP9 allows you to modify
• Licensing : with this option you can configure the
these when your requirements to change the configurations.
update, surrender, reset license.
In Configuration consists of the following menus. Multilingual Capability in tally : Tally.ERP9 allows you
to record, view, print information in any one of the 9 Indian
• General : with this option you can configure the language (like Hindi, Gujarati, Punjabi, Tamil, Telugu,
Country Details, Style of Names, Style of Dates. Marathi, Kannada, Malayalam and Bengali), besides few
international languages such as Arabic, Bahasa Indonesia,
• Numeric Symbols : with this option you can configure
Bahasa Malayu etc. Tally enables you to enter data in
the number styles.
one language and have it transliterated into different
• Accts / Inventory Info. : with this option you can languages.
configure the details in Accounts Masters and Inventory
Masters. Some others features :
• Voucher Entry : with this option you can configure the
• It is a user friendly.
vouchers entries in Accounting and Inventory Vouchers.
• It offers concurrent multilingual support.
• Invoice / Orders Entry : with this option you can
configure the invoice, delivery notes, sales & purchase • It maintain your books of accounts while the data is
orders. accepted, sorted, maintained, displayed and printed
in any one of the language.
• Payroll Configuration : with this option you can
configure the statutory details, passport details, • It generate bill, invoices, vouchers, ledgers, receipts,
contract details and deactivated employees. reports, purchase orders or delivery notes in the
language of your choice after entering data for in any
• Banking Configuration : with this option you can
one of the specified languages.
configure the settings related to Bank reconciliation
statement. • It has easy to use keyboards layouts - inscript and
• Printing : with this option you can configure the printing phonetic.
parameters of a voucher, invoice and statement layouts
before final printing.
188
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.4.133
COPA - E Commerce
There are four main areas in which companies conduct E- 1 Reduction in buyer's sorting out time.
commerce these areas are: 2 Better buyer descisions.
• Direct marketing, selling, and service. 3 Less time is spent in resolving invoice and order
discrepancies.
• Online banking and billing.
4 Increased opportunities for buying alternative
• Secure distribution of information. products.
• Value chain trading and corporate purchasing.
• The strategic benefit of making a business 'E Commerce
• Filling tax return to government. enabled', is that it helps reduce the delivery time, labour
cost and the cost incurred in the following areas:
The field of E-Commerce is very broad. There are many
applications of E-Commerce such as home banking, 1 Document preparation
shopping in electronic malls, buying stocks, finding a job, 2 Error detection and correction
conducting an auction, collaborating electronically with
business partners around the globe, and providing customer 3 Reconciliation
service. The implementation of various E-Commerce 4 Mail preparation
applications depends on four major support categories such
5 Telephone calling
as people, public policy, and marketing/advertising and
supply chain logistics. In addition there has to be an 6 Credit card machines
Infrastructure support. The E-Commerce management
7 Data entry
within each organization co-ordinates the applications and
infrastructure. In order to explain the relationships I have 8 Overtime
explained below the applications in the case of B2C E-
9 Supervision expenses
Commerce.
• Operational benefits of e commerce include reducing
Benefits of E Commerce:
both the time and personnel required to complete
business processes, and reducing strain on other
• E Commerce allows people to carry out businesses
resources. It's because of all these advantages that
without the barriers of time or distance. One can log
one can harness the power of ecommerce and convert
on to the Internet at any point of time, be it day or night
a business to E Business by using powerful E
and purchase or sell anything one desires at a single
Commerce solutions made available by E Business
click of the mouse.
solution providers.
• The direct cost-of-sale for an order taken from a web
site is lower than through traditional means (retail, paper Technology Requirements for E Commerce
based), as there is no human interaction during the
The requirements for E Commerce needs Web based
on-line electronic purchase order process. Also,
application with an HTML front end compatible with a variety
electronic selling virtually eliminates processing errors,
of browsers. The application will require a database to
as well as being faster and more convenient for the
store user transactions (such as items ordered by the
visitor.
user) and to list items available through the electronic store.
190 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.133
Copyright @ NIMI Not to be Republished
The application must also include a middle tier-the Web Middle Tier
server and scripts executed by the server-to process
requests sent from Web browsers. A Web browser will The middle tier produces run time HTML output by
send HTTP requests to the middle tier. The middle tier will generating data in the middle tier itself or by retrieving
then retrieve information stored in the database, process data from the database. For example, in order to display a
it appropriately, and send a reply back to the client. list of items offered on a site, the middle tier would return
(Fig 1) the required information from the database, manipulate it
appropriately, then dynamically generate an HTML
Fig 1 document that displays the items of interest.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.133 191
Copyright @ NIMI Not to be Republished
The flow chart below describes the typical interactions of
site visitors with the shopping cart application. (Fig 2)
Fig 2
192 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.133
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.4.134
COPA - E Commerce
Different E Commerce sites Internet Banking, Debit Card, Credit Card and various other
options. The buyer chooses the proper option for payment
Some of the world's most popular E Commerce sites are: and after successful payment, it is notified to the buyer
Crate & Barrel, Symantec, Amway, Microsoft, Amazon, and finally products are delivered to buyer address.
HP etc.
Authorization and chargeback
In India, after some initial hiccups, E Commerce is
gradually picking pace. Some of the popular web sites Authorization or authorization is the function of specifying
are: access rights to resources related to information security
and computer security in general and to access control in
Amazon, FlipKart, Jabong, Naaptol etc. particular.
On line catalogue, shopping carts and checkout Chargeback refers to paying the money back to the buyer
pages after the price has been deducted from his. It happens in
various situations. For an example, suppose someone buy
On line catalogues are list of products given on a web site a ticket in irctc web site and paid the price of the ticket
for sell. Buyer chooses the product by browsing through successfully, but later the ticket was not booked. Then
the products and choosing the product which suits him/ charge back will occur and the money would be refunded
her. back to the customer.
Shopping cart is a bucket full of products chosen by buyer Other payment options
before finally paying the price. It is used in retail stores
but the same concept has been implemented in Web site Apart from the above discussed payment option there are
by making a virtual bucket which shows the product some other ways for payment exists like mobile payment.
chosen by the buyer. Recently Airtel Money or Vodafone mpesa etc. mobile
payment methods has evolved so that, persons can pay
After choosing the desired product the buyer finally click by their mobile also.
checkout to pay the price for the products.
Various E Commerce transactions like paying utility bills,
Payment and order processing shopping from web sites, recharging etc can be done by
mobile.
After clicking checkout a payment option is shows which
normally has various options like COD (Cash on Delivery),
193
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.4.135
COPA - E Commerce
194
Copyright @ NIMI Not to be Republished
Brute Force Attacks Another way to determine if a Web site is secure is to
look for a closed padlock displayed on the address bar of
A brute force attack is a method of defeating a your screen.
cryptographic scheme by trying a large number of
possibilities; for example, a large number of the possible If that lock is open, you should assume it is not a secure
keys in a key space in order to decrypt a message. Brute site. Of course, transmitting your data over secure channels
Force Attacks, although perceived to be low-tech in nature is of little value to you if the merchant stores the data
are not a thing of the past. unscrambled. You should try to find out if the merchant
stores the data in encrypted form. If a hacker is able to
Non-Technical Attacks intrude, it cannot obtain your credit data and other personal
information. Be sure to read the merchant's privacy and
Phishing is the criminally fraudulent process of attempting security policies to learn how it safeguards your personal
to acquire sensitive information such as usernames, data on its computers.
passwords and credit card details, by masquerading as a
trustworthy entity in an electronic communication. Phishing Research the Web Site before You Order
scams generally are carried out by emailing the victim
with a 'fraudulent' email from what purports to be a Do business with companies you already know. If the
legitimate organization requesting sensitive information. company is unfamiliar, do your homework before buying
When the victim follows the link embedded within the email their products. If you decide to buy something from an
they are brought to an elaborate and sophisticated unknown company, start out with an inexpensive order to
duplicate of the legitimate organizations website. Phishing learn if the company is trustworthy.
attacks generally target bank buyers, online auction sites
(such as eBay), online retailers (such as amazon) and Reliable companies should advertise their physical
services providers (such as PayPal). According to business address and at least one phone number, either
community banker, in more recent times cyber criminals buyer service or an order line. Call the phone number and
have got more sophisticated in the timing of their attacks ask questions to determine if the business is legitimate.
with them posing as charities in times of natural disaster. Even if you call after hours, many companies have a "live"
answering service, especially if they don't want to miss
Social Engineering-Social engineering is the art of orders. Ask how the merchant handles returned
manipulating people into performing actions or divulging merchandise and complaints. Find out if it offers full refunds
confidential information. Social engineering techniques or only store credits.
include pretexting (where the fraudster creates an invented
scenario to get the victim to divulge information), Interactive You can also research a company through the Better
voice recording (IVR) or phone phishing (where the fraudster Business Bureau, or a government consumer protection
gets the victim to divulge sensitive information over the agency like the district attorney's office or the Attorney
phone) and baiting with Trojans horses (where the fraudster General. Perhaps friends or family members who live in
'baits' the victim to load malware unto a system). Social the city listed can verify the validity of the company.
engineering has become a serious threat to e-commerce Remember, anyone can create a Web site.
security since it is difficult to detect and to combat as it
involves 'human' factors which cannot be patched akin to Payment gateways
hardware or software, albeit staff training and education A payment gateway is an e-commerce application service
can somewhat thwart the attack. provider service that authorizes credit card payments for
e-businesses, online retailers, bricks and clicks, or
How to be secure traditional brick and mortar.
Shop at Secure Web Sites
It is the equivalent of a physical point of sale terminal
located in most retail outlets. Payment gateways protect
Secure sites use encryption technology to transfer
credit card details by encrypting sensitive information, such
information from your computer to the online merchant's
as credit card numbers, to ensure that information is passed
computer. Encryption scrambles the information you send,
securely between the buyer and the merchant and also
such as your credit card number, in order to prevent
between merchant and the payment processor.
computer hackers from obtaining it en route. The only
people who can unscramble the code are those with A payment gateway facilitates the transfer of information
legitimate access privileges. Here's how you can tell when between a payment portal (such as a website, mobile
you are dealing with a secure site: phone or interactive voice response service) and the Front
End Processor or acquiring bank.
If you look at the top of your screen where the Web site
address is displayed (the "address bar"), you should see Transaction process
https://. The "s" that is displayed after "http" indicates
• When a buyer orders a product from a payment
that Web site is secure. Often, you do not see the "s"
gateway-enabled merchant, the payment gateway
until you actually move to the order page on the Web site.
performs a variety of tasks to process the transaction.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.135 195
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.5.136
COPA - Cyber Security
196
Copyright @ NIMI Not to be Republished
occurrence of bottle necks, implementing emergency emphasizes the importance of information security. Assets
backup power systems, keeping current with all necessary held on internal Intranets may increase the interest of
system upgrades, and guarding against malicious actions potential misusers. Hence, protecting Intranets and the
such as denial-of-service (DoS) attacks. data and information transmitted via them against various
threats endangering the confidentiality, integrity and
In addition to the above mentioned three members, availability of information is an extremely important
Authenticity and Non-repudiation are also considered to consideration.
be members of the CIA model.
Using the Internet as a part of an Intranet poses a serious
threat, because the Internet is inherently nonsecure. As a
Authenticity
result, users must be very careful particularly in encrypting
Authenticity is the process of ensuring that the data, their communications. Imitation (spoofing), reply (rapid fire),
transactions, communications or documents are genuine. alteration of message contents (superzapping), prevention
It is also important for authenticity to validate that the of service availability and active and passive wiretapping
parties involved are genuine. Some information security are among the most malicious threats. Wiretapping, for
systems incorporate authentication features such as example, could lead to a situation where strategic
"digital signatures", which give evidence that the messaged knowledge regarding an organization gets in the hands of
data is genuine and was sent by someone possessing outsiders, if communication encryption is not implemented
the proper signing key. by means of strong encryption methods.
Hacker tools, although developed for the Internet, are also
Non-repudiation usable on Intranets. They can be software or hardware
based or a combination of both. Their authorized use
Non-repudiation means a person's intention to fulfill his includes finding and correcting information security
obligations to a contract. It also implies that one party of a weaknesses on Intranets. However, they also enable
transaction cannot say that they have not received a insiders to hack such communication systems and access
transaction nor can the other party deny having sent a information which they are not authorized to access.
transaction.
Relation Between information Security and
It is important to note that while technology such as Cybersecurity
cryptographic systems can assist in non-repudiation
efforts, the concept is basically a legal concept. It is not, Information Security, mentioned in the earlier sections is
for instance, sufficient to show that the message matches the protection of information and information systems from
a digital signature signed with the sender's private key, unauthorized access, use, disclosure, disruption,
and thus only the sender could have sent the message modification, or destruction in order to provide
and nobody else could have altered it in transit. The alleged confidentiality, integrity, and availability.
sender could in return demonstrate that the digital signature Cybersecurity on the other hand can be defined as the
algorithm is vulnerable or flawed, or allege or prove that ability to protect or defend the use of cyberspace from
his signing key has been compromised. The fault for these cyber-attacks. Cyberspace is "the environment in which
violations may or may not lie with the sender himself, and communication over computer networks occurs."
such assertions may or may not relieve the sender of
liability, but the assertion would invalidate the claim that Cyber security involves anything security-related in the
the signature necessarily proves authenticity and integrity cyber domain or realm (or cyberspace). Information security
and thus prevents repudiation. involves the security of information or information systems
regardless of the realm it occurs in (e.g., risk of exposure
With all activities that give us almost unlimited freedom, in physical world). Since anything that occurs in the cyber
there are risks. Because the Internet is so easily accessible realm would involve the protection of information and
to anyone, it can be a dangerous place. Know who you're information systems in some way, you can conclude that
dealing with or what you're getting into. Predators, cyber information security is a super-set of cyber security.
criminals, bullies, and corrupt businesses will try to take (Fig 1) At times the two terms are used interchangeably
advantage of the unwary visitor. too.
Although the difference between Intranets and the Internet 1 IT Security is assigned a low priority
is not great in terms of technology, the transmission of
information is completely different from the organizational • The organization have not instilled the right focus
point of view. on implementing IT security practices.
2 Ad hoc Security Governance
Information security threats between Intranets and other
networks and information systems are rather similar. The • Absence of an Information Security Management
use of Intranets as internal information channels System (ISMS) or a structured governance
mechanism. (Fig 1)
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136 197
Copyright @ NIMI Not to be Republished
Fig 1
• Ambiguities exist on the roles and responsibilities • Protect networks, computers and data from
of the different players (Business, teams in SSO, unauthorized access to minimize the impact from
etc.) in an SSO. Single sign-on (SSO) is a property external threats of various cybercrime
of access control of multiple related, but • Improved information security and business continuity
independent software systems. With this property management to implement technical, management,
a user logs in once and gains access to all systems administrative and operational controls, which is the
without being prompted to log in again at each of most cost effective way of reducing risk.
them
• Improved stakeholder confidence in information security
4 Inadequate Separation of Duties arrangements.
• Overlapping and shared responsibilities in an SSO • Improved company credentials with the correct security
makes it difficult to implement appropriate level of controls in place Organization will improve credibility
separation in duties. and trust among internal stakeholder and external
5 Varied Interpretations of Security Requirements vendors. The credibility and trust are the key factors to
win a business.
• In the absence of standard interpretations, the
different individuals and teams have their own • Faster recovery times in the event of disruption
interpretations.
Techniques to enforce IS in an organization
6 Tendency to reduce Risk level
• The teams show a tendency to reduce the 'Risk Identifying tools to enforce Information Security
Level' to bypass the rigors of the governing
processes. A successful information security policy provides several
benefits to corporations. Enforceable policies ensure that
7 Multiple vendors vulnerabilities are identified and addressed. This results in
• Relentless competition and sense of insecurity have protecting business continuity and strengthening the IT
led to reluctance in sharing responsibility and little infrastructure. When employees throughout an organization
or no collaboration among the vendors. follow a security policy, ensuring that information is safely
shared within the organization as well as with customers,
8 Business/Operations spread across multiple partners and vendors, the risk is reduced.
geographics
• The organization is based out of and functions from 1 The first step to creating an effective information
multiple locations spread all across the globe. security policy is evaluating information assets and
identifying threats to those assets.
9 Lack of Training/Awareness
Some assets within an organization will be more
• Inadequate training and awareness on security valuable than others, but monetary value should not be
practices.
198 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136
Copyright @ NIMI Not to be Republished
the only factor. Determining both the monetary value members are expected to follow. Security policy applies
and the intrinsic value of an asset is essential in to all hardware, software, data, information, network,
accurately gauging its worth. To calculate an asset's personal computing devices, support personnel, and users
monetary value, an organization should consider the within an organization.
impact if that asset's data, networks or systems are
compromised in any way. To calculate intrinsic value, For an IT security system to work, a well-defined framework
an organization must consider a security incident's needs to be developed involving all stakeholders, and it
impact on credibility, reputation and relationships with needs to be updated over time to be useful. The information
key stakeholders. security frameworks facilitate the management process
in considering the handling of data and implementation of
2 Creating a policy is for organizations to perform system/ process in the form of identifying assets,
a risk assessment determining security requirement, risk assessment, control
evaluation, control implementation, process monitoring and
After the identification of assets and threats, the next
update.
step in creating a policy is for organizations to perform
a risk assessment. This assessment allows an The commonly used terms in Information Security
organization to decide whether information is under Framework are:
protected, overprotected or adequately protected. The
goal for this risk assessment should be to minimize • Policy: General Management Statements
expenses without exposing an organization to
• Standards: Specific Mandatory Controls
unnecessary risk. This assessment will help in
determining the proper allocation of resources once • Guidelines: Recommendations / Best Practices
the security policy is effectively in place. • Procedures: Step by Step Instructions
The Information Security Framework The detailed activities involved in actually implementing a
The Information Security Framework establishes security Security Framework, the sequence of practice to be
policy and practices for an organization. Policies provide followed, corrrective actions to be taken are shown in the
guidance on matters affecting security that an organization's Figure shown below. (Fig 2).
Fig 2
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136 199
Copyright @ NIMI Not to be Republished
The major heads and the practices under each head in a
Framework are as shown below.
Thus the security framework becomes the technology that New technologies and new networks can plug into the
turns security policies into practice. It achieves it by the security framework and Security costs become more
four steps cycle of plan, do act and check cycle. The predictable and manageable.
PPT triad, ie. people, process and technology needs to
be given equal importance in achieving this.
200 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.5.137
COPA - Cyber Security
Introduction 8 Phishing
A form of social engineering, involving the sending of
A Threat is any circumstance or event with the potential to
legitimate looking emails aimed at fraudulently
cause harm to the system or activity in the form of
extracting sensitive information from recipients, usually
destruction, disclosure, and modification of data, or denial
to gain access to systems or for identity theft.
of service. A threat is a potential for harm. The presence of
a threat does not mean that it will necessarily cause actual 9 System Compromise
harm.
A system that has been attacked and taken over by
malicious individuals or 'hackers', usually through the
Some of the common terms associated with threats and
exploitation of one or more vulnerabilities, and then often
their description are as follows:
used for attacking other systems.
1 Unauthorized Access 9 Spam
The attempted or successful access of information or Unsolicited email sent in bulk to many individuals,
systems, without permission or rights to do so. usually for commercial gain, but increasingly for
spreading malware.
2 Cyber Espionage
10 Denial of Service
The act of spying through the use of computers,
involving the covert access or 'hacking' of company or An intentional or unintentional attack on a system and
government networks to obtain sensitive information. the information stored on it, rendering the system
unavailable and inaccessible to authorized users.
3 Malware
11 Identity Theft
A collective term for malicious software, such as
viruses, worms and trojans; designed to infiltrate The theft of an unknowing individual's personal
systems and information for criminal, commercial or information, in order to fraudulently assume that
destructive purposes. individual's identity to commit a crime, usually for
financial gain.
4 Data Leakage
The intentional or accidental loss, theft or exposure of Categories of threats
sensitive company or personal information.
Security Threats can be classified in many ways. A few of
5 Mobile Device Attack
the popular classifications are as follows:
The malicious attack on, or unauthorized access of,
mobile devices and the information stored or processed 1 Based on the sophistication, Security threats can be
by them; performed wirelessly or through physical classified into three categories.
possession.
• Simple first-generation threats are generic virus-type
6 Social Engineering
attacks spread by users opening infected e-mail
Tricking and manipulating others by phone, email, and inconspicuous file attachments.
online or in-person, into divulging sensitive information,
• The second-generation threats are more
in order to access company information or systems.
sophisticated and pose bigger problems. Created
7 Insiders with automated tools, these worms attack
vulnerabilities without human interaction.
An employee or worker with malicious intent to steal
Replication, identification, and targeting of new
sensitive company information, commit fraud or cause
victims is automatic.
damage to company systems or information.
201
Copyright @ NIMI Not to be Republished
• The third generation threats are blended threats, Threats based on technology
are common and incorporate viruses, Trojans and
automation. These worms pre-compile targets for 1 Threats based on WWW technology
hyper-propagation, exploit known vulnerabilities and 2 New features in browser software
enable targeted use of hidden vulnerabilities. They
also target multiple attack wireless links, virtual 3 Browser software test versions
private networks and attack inside perimeter 4 Server software
defences such as firewalls and intrusion detection
systems. 5 CGI scripts
6 Cookies
2 The top threats according to OWASP (Open Web
Applications Security Project) are as follows: 7 Threats based on Unix and TCP/IP tools
8 Difficulties in firewall management
• Injection
9 Use of cryptographic software
• Cross Site Scripting (CSS)
10 Hacker tools
• Broken Authentication and Session Management
11 Other software based threats
• Insecure Direct Object References
12 Intranet application software
• Cross - Site Request Forgery (CSRF)
13 Java language
• Security Misconfiguration
14 ActiveX
• Insecure Cryptographic Storage
15 Threats based on communications
• Failure to Restrict URL Access
16 Threats based on viruses
• Insufficient Transport Layer Protection
17 Threats based on human activities
• Unvalidated Redirects and Forwards
Identification of Information Security Threats
3 Categorization by Microsoft according to the kinds of
Exploits that are used (or motivation of the attacker) The success of an information security management
ie. STRIDE system. The STRIDE acronym is formed program is based on the accurate identification of the
from the first letter of each of the following categories. threats to the organization's information systems.
• Spoofing identity. An example of identity spoofing Identification of Information Security Threats is an essential
is illegally accessing and then using another user's first step for security planners. Proper threat and
authentication information, such as username and vulnerability identification should include security testing
password. and inspections, which are geared to promoting and
ensuring that equipment is operating properly, is readily
• Tampering with data. Data tampering involves the available when needed, and that employees are proficient
malicious modification of data. in the use of the equipment.
• Repudiation. Repudiation threats are associated
with users who deny performing an action without To accomplish this, systems must design a testing
other parties having any way to prove otherwise-for program that not only assesses the current state of
example, a user performs an illegal operation in a security, but can also be used to upgrade staff effectiveness
system that lacks the ability to trace the prohibited through training.
operations.
The two major methods of identifying security threats are
• Information disclosure. Information disclosure Probing and Scanning.
threats involve the exposure of information to
individuals who are not supposed to have access Probing is an attempt to gain access to a computer and
to it. its files through a known or probable weak point in the
• Denial of service. Denial of service (DoS) attacks computer system. It is an action taken for the purpose of
deny service to valid users. learning something about the state of the network.
• Elevation of privilege. In this type of threat, an Scanning is a method to go through all the files, or network
unprivileged user gains privileged access and elements with an intention to detect something unusual.
thereby has sufficient access to compromise or File scanning inspects files that users attempt to download
destroy the entire system. or open remotely for viruses and other malicious content.
File scanning returns some information for policy
enforcement.
202 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.137
Copyright @ NIMI Not to be Republished
There are 2 types of file scanning. They can be used Infection
together.
Infection is the means used by the threat to get into the
• Advanced detection applies techniques to discover device. It can either use one of the faults previously
known and emerging threats, including viruses, Trojan presented or may use the gullibility of the user. Infections
horses, worms, and others. may ask for permission, or may interact with the gullible
user or may not even do any of these two and directly
• Anti-virus scanning uses anti-virus definition files to
attack the system.
identify virus-infected files.
Network scanning is a procedure for identifying active hosts Accomplishment of the goal
on a network for the purpose of network security
assessment. Scanning procedures, such as ping sweeps Once the threat has infected a device it will also seek to
and port scans, return information about which IP accomplish its goal, which is usually one of the following:
addresses map to live hosts that are active on the Internet hardware damage, denial of service(DoS), monetary
and any suspicious activity etc. damage, damage data and/or , device, and concealed
damage etc.
Modus Operandi of Threats in attacking a system
Spreading to other systems
Typically an attack on a device takes place in 3 phases:
Once the threat has infected a device, it always aims to
• The infection of a host, spread one way or another.
• The accomplishment of its goal, and
It can spread through networks, wired or wireless, through
• The spread of the malware to other systems. the internet, proximate devices using Wi-Fi, Bluetooth and
infrared light and through shared devices etc.
Threats often use the resources offered by the infected
devices. They use the output devices such as Bluetooth Sources of Threats (Fig 1)
or infrared, but may also use the address book or email
address of the person to infect the user's acquaintances. Primary sources of threats are employees/insiders,
They exploit the trust that is given to data sent by an malicious hackers, natural disasters, foreign adversaries,
acquaintance. and hostile attacks. In several cases, the areas for sources
Fig 1
of threats may overlap. For example, hostile attacks may Human Threats
be performed by foreign adversaries or a disgruntled
A Employees/Insiders
employee.
Intentional and accidental errors and malicious acts by
Natural Disasters employees and insiders cause a considerable amount of
damages and losses experienced in the
Earthquakes, hurricanes, floods, lightning, and fire can telecommunications industry.
cause severe damage to computer systems. Information
can be lost, down time or loss of productivity can occur, Disgruntled employees can create both mischief and
and damage to hardware can disrupt other essential sabotage on a computer system. Staff removed from their
services. Few safeguards can be implemented against jobs in both public and private sectors has created a group
natural disasters. The best approach is to have disaster of individuals with important organizational knowledge who
recovery plans and contingency plans in place. may retain potential system access. System managers
can limit this threat by invalidating passwords and deleting
system accounts in a timely manner.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.137 203
Copyright @ NIMI Not to be Republished
Malicious Hackers Hostile Attacks
Malicious threats consist of inside attacks by disgruntled Through hostile attacks, it is possible to affect the
or malicious employees and outside attacks by non- availability of the networks. The primary impact of hostile
employees just looking to harm and disrupt an attacks such as coordinated nuclear attacks, limited/
organization. Malicious attackers normally will have a uncoordinated nuclear attacks, nuclear accidents,
specific goal, objective, or motive for an attack on a system. terrorism, electronic warfare, sabotage, and civil disorder
These goals could be to disrupt services and the continuity on the a nation's network is disruption and denial of service.
of business operations by using denial-of-service (DoS) Such disasters impact the timeliness and quality of the
attack tools. They might also want to steal information or delivered services.
even steal hardware such as laptop computers. Hackers
can sell information that can be useful to competitors. B Non-Malicious Employees
Attackers are not the only ones who can harm an
The most dangerous attackers are usually insiders (or
organization. The primary threat to data integrity comes
former insiders), because they know many of the codes
from ignorant users. These are authorized users who are
and security measures that are already in place. Insiders
not aware of the actions they are performing. Errors and
are likely to have specific goals and objectives, and have
omissions can lose, damage, or alter valuable data.
legitimate access to the system. Employees are the
people most familiar with the organization's computers
Users, data entry clerks, system operators, and
and applications, and they are most likely to know what
programmers frequently make unintentional errors that
actions might cause the most damage. Insiders can plant
contribute to security problems, directly and indirectly.
viruses, Trojan horses, or worms, and they can browse
Sometimes the error is the threat, such as a data entry
through the file system.
error or a programming error that crashes a system. In
other cases, errors create vulnerabilities.
However, disgruntled current employees actually cause
more damage than former employees. Common examples
Best Practices or Guidelines used to Identify Threats
of computer-related employee sabotage include:
Different mechanisms and methodologies can be used to
• Changing data
successfully identify threats/attacks depending on their
• Deleting data type. In other words, depending on the threat, you can
use specific techniques to identify and classify them
• Destroying data or programs with logic bombs
accordingly. Following are the most common
• Crashing systems methodologies:
• Holding data hostage
• The use of anomaly detection tools
• Destroying hardware facilities
• Network telemetry using flow-based analysis
• Entering data incorrectly
• The use of intrusion detection and intrusion prevention
Foreign Adversaries systems (IDS/IPS)
• Analyzing network component logs (that is, SYSLOG
Computer intruder activities have occurred internationally,
from different network devices, accounting records,
with the number of attempted intrusions through
application logs, Simple Network Management Protocol
international gateways is increasing at an alarming rate.
(SNMP) etc.
There have been few indications that computer
undergrounds within foreign countries carry over political Best Practices or Guidelines used in mitigation of
agendas. Sometimes intelligence services of one country threats
directly target, penetrate, or compromise the
Communications systems of other countries. The following are some of the practices which when
implemented are likely to reduce the threats to the security
Outside Attackers or 'Crackers' of an organization's information, data and credibility.
People often refer to "crackers" as "hackers." The term Security Awareness Training
hacker refers to people who either break in to systems for
• Most security breaches actually originate inside
which they have no authorization or intentionally overstep
companies by disgruntled or negligent employees. So
their bounds on systems for which they do not have
educate everyone in your company so they can help
legitimate access. Common methods for gaining access
identify a variety of security risks.
to a system include password cracking, exploiting known
security weaknesses, network spoofing, and social • Employees should be able to spot and identify email
engineering. phishing and spoofing attacks. They should also be
trained not to store, send or copy sensitive information
that's unencrypted.
204 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.137
Copyright @ NIMI Not to be Republished
• They should know not to share sensitive information Access Controls
over the phone unless they are 100% sure of the • For increased security, give employees only (and
audience. partners) access to the data they need. This includes
• Train employees on security policies and practices. both physical and logical access.
And make sure to update them and retrain at frequently. • Start by granting the least privilege. You can then
• Training materials should also review corporate policies escalate privileges to allow access to unauthorized data
and clearly detail consequences for any suspicious or on an as-needed basis.
malicious behavior amongst employees. They should Mobile Devices
be trained on various security policies, including:
• Laptops, smartphones, and tablets have increased the
- Acceptable Use and Unacceptable Use productivity and mobility of today's workforce. But along
- General Use and Ownership with that productivity comes vulnerability. Lost or stolen
laptops and other mobile devices are the top cause of
- Security & Proprietary Information data breaches.
- Blogging & Social Media • Enable auto-lock or require a password to access all
- Enforcement ie. the disciplinary action for non- devices.
compliance Monitoring
- Social Media • Make sure your business is set up to monitor systems
- Bring Your Own Device Policies and network devices for any abnormalities.
- Data Policy • Collect and correlate information from all places or
infrastructure - network, systems, and user activity.
- Mobile Device Management (MDM) Policy
• Don't just block activity at a firewall or IPS. Log it, review
- Mobile Device Support Policy it and learn from it.
- Policies Regarding Company-issued Devices • Install content filtering to monitor user activity from
- Loss & Theft within your business. The most common form of
employee misuse of the Internet is to surf unwanted
- Employee Termination Policy sites
- Security Incident Management Firewall
Anti-Virus & Anti-Malware Protection • Configure Firewall rules and Policies because a firewall
• Common forms of malware include: Worms, Key is the first line of defense against any attack (network
loggers, Video frame grabbers, Rootkits and Trojan or host). It acts a barrier between a public network and
horses. a private network.
• Install, update, schedule and run good Antivirus Remote Backup
programs. • Backup your data regularly to a remote location. Backup
• Adopt an "end point security" strategy to combat is one of the most neglected areas of computing and
malware threats. Endpoint security is an information therefore typically one of the biggest opportunities your
security concept that means that each device (or business has to mitigate risk.
endpoint) on a network should be responsible for and • Often, businesses invest in securing data from hackers
capable of providing for its own security. or malware, but then the data is physically destroyed
• Whatever your anti-malware solution, it should scan by natural causes. If the data doesn't exist, securing it
email for attached viruses, monitor files in real time for from outside threats has no meaning.
infections, and perform thorough scans of every file. Security Assessments & Penetration Testing
Data Encryption • To secure your business you must stay vigilant. There
• Data encryption is a powerful part of information are always people with wrong intentions looking for the
security. Encryption protects your data even after it next way to compromise your business's information
has been accessed. • Perform annual or, better, quarterly vulnerability
Patching assessments to identify new risks. The ever-changing
security environment is always creating new risks.
• Patching is essential to minimizing the risk to your
computer systems. Patches are often released to fix • Identify the new risks that apply to your business and
security holes in systems and applications. Make sure fix them before someone else finds them.
you keep all operating systems and applications you •
Get a formal Information Security Risk Assessment
run patched. Install the latest firmware updates on all done every three years, which is the life cycle of most
network devices. products these days.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.137 205
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.5.138
COPA - Cyber Security
206
Copyright @ NIMI Not to be Republished
in malformed data of every type they can imagine. If the • Vulnerabilities in the Java class library on which an
program crashes or otherwise misbehaves, the hacker then application depends for its security
tries to find a way to exploit the problem.
Understanding Security Vulnerabilities
Race Conditions
Flaws in Software or Protocol Designs
A race condition occurs when a pair of routine programming
calls in an application do not perform in the sequential Fundamental mistakes and oversight in Software design
manner that was intended to as per rules. It is a timing are the causes of design vulnerabilities. Design flaws result
event within software that can become a security in software not being secure thus making it a high level
vulnerability if the calls are not performed in the correct vulnerability case.
order. If the correct order of execution is required for the
proper functioning of the program, this is a bug. If an Computer networks depend on protocols that specify the
attacker can take advantage of the situation to insert messages that are exchanged at runtime, their format and
malicious code, change a filename, or otherwise interfere structure. Protocols are linked with different protocol
with the normal operation of the program, the race condition stacks, e.g., TCP/IP, or different models, e.g., OSI, and
is a security vulnerability. Attackers can sometimes take many protocols with underspecified security are still
advantage of small time gaps in the processing of code to present in practice. Some of the vulnerabilities arising due
interfere with the sequence of operations, which they then to flawed protocols are described below:
exploit.
A. TCP/IP. The TCP/IP protocol stack has some weak
In software development, time of check to time of use points that allow:
(TOCTTOU or TOCTOU, pronounced "TOCK too") is a
class of software bug caused by changes in a system • Spoofing : A spoofing attack is when a malicious party
between the checking of a condition (such as a security impersonates another device or user on a network in
credential) and the use of the results. This is one example order to launch attacks against network hosts, steal
of a race condition. data, spread malware, or bypass access controls. There
are several different types of spoofing attacks that
Interprocess Communication(IPC) malicious parties can use to accomplish this. They
are IP Address Spoofing Attacks, ARP (Address
Interprocess communication (IPC) is a set of programming Resolution Protocol ) Spoofing Attacks, DNS Server
interfaces that allow a programmer to coordinate activities Spoofing Attacks, etc.
among different program processes that can run • Telnet protocol : Telnet can be used to administer
concurrently in an operating system. This allows a program systems running Microsoft Windows 2000 and Unix.
to handle many user requests at the same time. These When using the telnet client to connect from a Microsoft
messaging protocols used for interprocess communication system to UNIX system and vice versa, user names
are often vulnerable to attack. and passwords are transmitted in clear text thus
creating security vulnerability.
Remote Procedure Call (RPC) is an interprocess
communication mechanism that allows a program running • File Transfer Protocol (FTP) : File Transfer Protocol
on one host to run code on a remote host. allows users to connect to remote systems and transfer
files back and forth. As part of establishing a connection
Insecure File Operations to a remote computer, FTP relies on a user name and
password combination for authentication. Use of FTP
In addition to time-of-check-time-of-use problems, many
poses a security problem similar to use of the Telnet
other file operations are insecure. Programmers often make
protocol because passwords typed to FTP are
assumptions about the ownership, location, or attributes
transmitted over the network in plain text, one character
of a file that might not be true. For example, you might
per packet. These packets can be intercepted.
assume that you can always write to a file created by
your program. However, if an attacker can change the • Weaknesses in how protocols and software are
permissions or flags on that file after you create it, and if implemented
you fail to check the result code after a write operation,
Even when a protocol is well designed, it can be vulnerable
you will not detect the fact that the file has been tampered
because of the way it is implemented. For example, a
with.
protocol for electronic mail may be implemented in a way
that permits intruders to connect to the mail port of the
B Types of Native Vulnerabilities
victim's machine and fool the machine into performing a
task not intended by the service. This type of vulnerability
Examples of Native Vulnerabilities are:
enables intruders to attack the victim's machine from
• Vulnerabilities in the sandboxing mechanism which remote sites without access to an account on the victim's
allow untrusted bytecode to circumvent the restrictions system.
imposed by the security manager
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 207
Copyright @ NIMI Not to be Republished
• Software may be vulnerable because of flaws that were D Insecure Cryptography
not identified before the software was released. This
type of vulnerability has a wide range of subclasses, Attackers' can decode any cryptographic mechanism or
which intruders often exploit using their own attack tools algorithm as main methods to hack them are discovered.
like race conditions in file access, non-existent checking
of data content and size etc. E Data Protection and Portability
Weaknesses in System and Network Configurations Although the cloud services are offered based on a contract
among client and a provider but what will happen when the
• System administrators and users may neglect to contract is terminated and client doesn't wants to continue
change the default settings in network configurations, anymore.
or they may simply set up their system to operate in a
way that leaves the network vulnerable. F Vendor Lock-in
• Asynchronous transfer mode (ATM). Security can be This vulnerability occurs due to immature providers and
compromised by what is referred to as "manhole new business models which raise the risk of failure and
manipulation"-direct access to network cables and going out of the business.
connections in underground parking garages and
elevator shafts. G Internet Dependency
• Frame relay. Similar to the ATM problem.
Cloud computing is an internet dependent technology
• Device administration. Switches and routers are easily where users are accessing the services via web browser.
managed by an HTTP interface or through a command What if the internet is not available or service is down,
line interface. Coupled to the use of weak passwords what will happen to users systems and operations that
(for example, public passwords), it allows anybody with are very critical and need to run 24 hours such as
some technical knowledge to take control of the device. Healthcare and Banking systems.
• Modems. A modem bypasses the "firewall" that protects
a network from outside intruders. A hacker using a "war Weaknesses in Online e-transactions
dialer" tool to identify the modem telephone number
and a "password cracker" tool to break a weak The tremendous increase in online transactions has been
password can gain access to the system. accompanied by an equal rise in the number and type of
attacks against the security of online payment systems.
• Weaknesses in Web or Cloud applications Some of these attacks have utilized vulnerabilities that
There are several significant vulnerabilities that should be have been published in reusable third-party components
considered when an organization is ready to move their utilized by websites, such as shopping cart software. Other
critical applications and data to a cloud computing attacks have used vulnerabilities that are common in any
environment, these vulnerabilities are described below : web application, such as SQL injection or cross-site
scripting.
A Session Riding and Hijacking
The common types of vulnerabilities in Online e-
Session riding refers to the hackers sending commands transactions are SQL injection, cross-site scripting,
to a web application on behalf of the targeted user by just information disclosure, path disclosure, price manipulation,
sending that user an email or tricking the user into visiting and buffer overflows.
a specially crafted website. Session riding deletes user Successful exploitation of these vulnerabilities can lead
data, executes online transactions like bids or orders, to a wide range of results. Information and path disclosure
sends spam to an intranet system via internet and changes vulnerabilities will typically act as initial stages leading to
system as well as network configurations or even opens further exploitation. SQL injection or price manipulation
the firewall. attacks could cripple the website, compromise
confidentiality, and in worst cases cause the e-commerce
B Virtual Machine Escape business to shut down completely.
VM escape is a vulnerability that enables a guest-level One of the main reasons for such vulnerabilities is the fact
VM to attack its host. Under this vulnerability an attacker that web application developers are often not very well
runs code on a VM that allows an OS running within it to versed with secure programming techniques.
break out and interact directly with the hypervisor.
Browser Security and Role of cookies and pop-ups
C Reliability and Availability of Service
Security vulnerabilities may allow a cookie's data to be
The cloud storage infrastructure may go down for a read by a hacker, used to gain access to user data, or
considerable time, causing data loss and access issues used to gain access (with the user's credentials) to the
with web services. website to which the cookie belongs.
208 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138
Copyright @ NIMI Not to be Republished
Pop-up ads or pop-ups Some of the vulnerabilities in Smartphones are Data
leakage resulting from device loss or theft, Unintentional
The "security" risks from popup windows are phishing, disclosure of data, Attacks on decommissioned
trapping to unwanted web sites etc. smartphones, Phishing attacks, Spyware attacks, Network
Spoofing Attacks, Surveillance(user under surveillance)
Security holes in Browser, Web Applications, OS, and attacks, Diallerware attacks(Stealing money), Financial
Smartphones malware attacks(Stealing credentials) and Network
congestion.
In security terminology, a hole refers to a software or
operating system vulnerability that could be exploited to Vulnerability Assessment Tools and Techniques
compromise the overall security of the computer system
or network on which the hole resides.The three different Vulnerability Assessment is a Security Exercise that
kinds of vulnerabilities are: identifies weaknesses, identifies and enumerates
vulnerabilities and reports on the discoveries about security
• Operating system vulnerabilities are those affecting the liabilities within networks, applications and systems.
Linux kernel; or components that ship with an operating
system produced by Microsoft, Apple, or a proprietary The Vulnerability Assessment detects vulnerabilities
Unix vendor, and defined as part of the operating via:
system by the vendor.
• Security technologies
• Browser vulnerabilities are those affecting components
defined as part of a web browser. This includes web - VA Scanners, Appliances and Software
browsers that ship with operating systems, such as
• Remediation technologies
Windows Internet Explorer and Apple's Safari, along
with third-party browsers, such as Mozilla Firefox and - Patch Management Systems(WSUS, SCCM,
Google Chrome. LanDesk,VMWare Update manager)
• Application vulnerabilities are those affecting all other
Vulnerability Assessment involves mainly the
components, including components published by
following three steps:
operating system vendors and other vendors.
Vulnerabilities in open source components that may • Information Gathering and Discovery which includes
ship with Linux distributions (such as the X Window Network Scanning, Ports Scanning, Directory Services
System, the GNOME desktop environment, GIMP, and and DNS Zones and Registers.
others) are considered application vulnerabilities. • Enumeration which includes Hosts and OS, Ports,
Services and their versions, information and SNMP
Security holes in Web Applications communities
The following is a list of top 10 threats in the OWASP(Open • Detection involving Identification of Weaknesses,
Web Applications Security project) category. Identification of Vulnerabilities, Report Generation and
Use of remediation tools.
Injection (Sqli -> SQL Injection),Broken Authentication &
Session Management, XSS (Cross Site Scripting),Insecure Vulnerability Assessment tools:
Direct Object Reference, Security Misconfiguration,
Sensitive Data Exposure, Missing Function Level Access Vulnerability Assessment tools detect, identify, measure
Control, Cross Site Request Forgery (CSRF Or XSRF), the effect of the vulnerabilities found at various levels. Most
Using Components With Known Vulnerabilities and Vulnerability Assessment tools are capable of scanning a
Unvalidated Redirect & Forwards. number of network nodes, including networking and
networked devices (switches, firewalls, printers, etc.) as
Security holes in OS well as server, desktop and portable computers.
Some of the vulnerabilities in UNIX OS are Setuid problems, Common Vulnerability Assessment Tools are Network
Trojan Horses and Terminal Troubles Scanners, Host Scanners, Database Scanners, Web
Application Scanners, Multilevel Scanners, Automated
Some of the vulnerabilities in Windows OS are Passwords, Penetration test tools and Vulnerability Scan
Peer to Peer File sharing, Vulnerabilities in embedded Consolidators.
automation features in Microsoft Outlook and Outlook
Express that can allow execution of rogue code. Techniques to Exploit Vulnerabilities
Some of the vulnerabilities in LINUX OS are missing Vulnerabilities can be exploited for ex. by the use of packet
permission checks, Uninitialized data, and Memory sniffers. Other tools are used to construct packets with
mismanagement forged addresses; one use of these tools is to mount a
denial-of-service attack in a way that hides the source of
the attack. Intruders also "spoof" computer addresses,
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 209
Copyright @ NIMI Not to be Republished
masking their real identity and successfully making 15 Make use of the session tracking mechanism built into
connections that would not otherwise be permitted. In this your development framework.
way, they exploit trust relationships between computers.
Risk is the combination of the probability of an event and
The most common exploits occur by the use of Trojans, its consequences. It refers to the likelihood of being
Viruses, Worms, Logic Bombs, Phishing, Forwarding and targeted by a given attack.
sharing Urban legends, Responding to Nigerian Scams
etc. Relationship between Threat, Vulnerability, and Risk
Techniques to Fix the Vulnerabilities Before defining the relationship between threat, vulnerability
and risk let us review the following terms:
Effective remediation demands continuous processes that
together are called Vulnerability Management. The Asset: In information Security, an asset is what we are
processes and related technology defined by vulnerability trying to protect. It may be people, property or information.
management help organizations efficiently find and fix
network security vulnerabilities. Systematic use of these Threat: Anything that can exploit a vulnerability,
processes protects business systems from ever more intentionally or accidentally and obtain, damage or destroy
frequent viruses, worms and other network-borne attacks. an asset.
Continuous Processes of Vulnerability Management Vulnerability: It refers to the weakness or gaps in our
involves Creating security policies & controls, Tracking protection efforts.
inventory / categorizing assets, Scanning systems for
vulnerabilities, Comparing vulnerabilities against inventory, Risk: When a threat exploits a vulnerability, it may cause
Classifying risks, Pre-testing of patches, Applying patches loss, damage or destruction of an asset. This is called a
and Re-scanning and confirming fixes. You can automate Risk.
most of them now with security applications and Web-
based services. Risk is therefore the intersection of assets, threats and
vulnerabilities.
Best Practices and Guidelines to mitigate security
Vulnerabilities ie. assets x threats x vulnerabilities = risk
210 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138
Copyright @ NIMI Not to be Republished
Understanding the value of an asset is the first step to 2 Technical or Logical : These are the virtual,
understanding what security mechanisms should be utilized application and technical controls (systems and
and what funds should go toward protecting it. software), such as firewalls, anti virus software,
encryption and maker/checker application routines.
What Is a Threat Source/Agent? Technical controls are carried out or managed by
computer systems.
A Threat Source or threat Agent is an entity with an
3 Activity phase controls can be either technical or
intention and capability to cause impact.
administrative and are classified as follows based on
Threat agents can take one or more of the following actions the level of risk mitigation:
against an asset: • Preventative controls exist to prevent the threat from
coming in contact with the weakness. These are
• Access - simple unauthorized access controls that prevent the loss or harm from occurring.
• Misuse - unauthorized use of assets (e.g., identity theft, For example, a control that enforces segregation of
setting up a porn distribution service on a compromised responsibilities (one person can submit a payment
server, etc.) request, but a second person must authorize it),
minimizes the chance an employee can issue
• Disclose - the threat agent illicitly discloses sensitive fraudulent payments.
information
• Detective controls exist to identify that the threat
• Modify - unauthorized changes to an asset has landed in our systems. These controls monitor
• Deny access - includes destruction, theft of a non- activity to identify instances where practices or
data asset, etc. procedures were not followed. For example, a
business might reconcile the general ledger or review
The threat agents can be any of the following: payment request audit logs to identify fraudulent
payments.
These individuals and groups can be classified as follows: • Corrective controls exist to mitigate or lessen the
effects of the threat being manifested. Corrective
• Non-Target Specific: Non-Target Specific Threat Agents controls restore the system or process back to the
are computer viruses, worms, trojans and logic bombs. state prior to a harmful event. For example, a
• Employees: Staff, contractors, operational/ business may implement a full restoration of a
maintenance personnel, or security guards who are system from backup tapes after evidence is found
annoyed with the company. that someone has improperly altered the payment
data.
• Organized Crime and Criminals: Criminals target
information that is of value to them, such as bank • Compensating controls are alternate controls
accounts, credit cards or intellectual property that can designed to accomplish the intent of the original
be converted into money. Criminals will often make use controls as closely as possible, when the originally
of insiders to help them. designed controls cannot be used due to limitations
of the environment.
• Corporations: Corporations are engaged in offensive
information warfare or competitive intelligence. Partners Risk likelihood
and competitors come under this category.
• Human, Unintentional: Accidents, carelessness. Risk likelihood is a rough measure of how likely this
particular vulnerability is to be uncovered and exploited by
• Human, Intentional: Insider, outsider. an attacker. It is not necessary to be over-precise in this
• Natural: Flood, fire, lightning, meteor, earthquakes. estimate. Generally, identifying whether the likelihood is
low, medium, or high is sufficient.
Risk Controls
There are a number of factors that can help determine the
If the mitigation of risk is the central focus of Information likelihood. The first set of factors are related to the threat
Security, Controls are the primary tools to achieve this agent involved. The goal is to estimate the likelihood of a
goal. A control is any device or process that is used to successful attack from a group of possible attackers. Note
reduce risk. that there may be multiple threat agents that can exploit a
particular vulnerability, so it's usually best to use the worst-
Basically the three types of controls are : case scenario. For example, an insider may be a much
more likely attacker than an anonymous outsider, but it
1 Administrative : Administrative controls are the actions depends on a number of factors.
that people take. Administrative controls are the
process of developing and ensuring compliance with The first set of factors are related to the threat agent involved.
policy and procedures The goal here is to estimate the likelihood of a successful
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 211
Copyright @ NIMI Not to be Republished
attack by this group of threat agents. The second factor to vulnerabilities emerge every day. Second, the choice of
be taken into account is the Motive behind the attacks. countermeasures (controls) used to manage risks must
The Access or resources required and the size of the group strike a balance between productivity, cost, effectiveness
of threat agents are the other factors to be considered. of the countermeasure, and the value of the informational
asset being protected.
The next set of factors are related to the vulnerability
involved. The goal here is to estimate the likelihood of the On the contrary, Risk Assessment is executed at discrete
particular vulnerability involved being discovered and time points (ex. once a year, on demand, etc.) and until
exploited. This takes into account the ease of discovery, the performance of the next assessment - provides a
the ease of exploit, the awareness to this group of threat temporary view of assessed risks.
agents, the likelihood of detection of this exploit.
Purpose of Risk Management
Factors for Estimating Impact
The principle reason for managing risk in an organization
When considering the impact of a successful attack, it's is to protect the mission and assets of the organization.
important to realize that there are two kinds of impacts. Therefore, risk management must be a management
The first is the "technical impact" on the application, the function rather than a technical function. Understanding
data it uses, and the functions it provides. The other is the risk, and in particular, understanding the specific risks to
"business impact" on the business and company operating a system allow the system owner to protect the information
the application. system commensurate with its value to the organization.
The fact is that all organizations have limited resources
Ultimately, the business impact is more important. and risk can never be reduced to zero. So, understanding
However, you may not have access to all the information risk, especially the magnitude of the risk, allows
required to figure out the business consequences of a organizations to prioritize scarce resources.
successful exploit. In this case, providing as much detail
about the technical risk will enable the appropriate Risk Assessment (Phases)
business representative to make a decision about the
business risk. The purpose of assessing risk is to assist management in
determining where to direct resources. There are four basic
Technical impact can be broken down into factors aligned strategies for managing risk: mitigation, transference,
with the traditional security areas of concern: confidentiality, acceptance and avoidance.
integrity, availability, and accountability. The goal is to
estimate the magnitude of the impact on the system if the Mitigation
vulnerability were to be exploited. The issues to be Mitigation is the most commonly considered risk
considered are Loss of confidentiality, Loss of integrity, management strategy. Mitigation involves fixing the flaw
Loss of availability and Loss of accountability. or providing some type of compensatory control to reduce
the likelihood or impact associated with the flaw. A common
The factors to be considered for assessing the business
mitigation for a technical security flaw is to install a patch
impact are financial damage, Reputation damage, Non-
provided by the vendor. Sometimes the process of
compliance to policies and Privacy violation.
determining mitigation strategies is called control analysis.
Risk Control Effectiveness
Transference
The risk control effectiveness depends on the Number of
Transference is the process of allowing another party to
systemic risks identified, Percentage of process areas
accept the risk on your behalf. This is not widely done for
involved in risk assessments, Percentage of key risks
IT systems, but everyone does it all the time in their
mitigated and Percentage of key risks monitored among
personal lives. Car, health and life insurance are all ways
many factors involved.
to transfer risk. In these cases, risk is transferred from the
individual to a pool of insurance holders, including the
Risk Management
insurance company. Note that this does not decrease the
likelihood or fix any flaws, but it does reduce the overall
Risk Management and Risk Assessment are major
impact (primarily financial) on the organization.
components of Information Security Management (ISM).
Acceptance
Risk management is the process of identifying
vulnerabilities and threats to the information resources used
Acceptance is the practice of simply allowing the system
by an organization and deciding what countermeasures
to operate with a known risk. Many low risks are simply
to take in reducing the based on the value of the asset.
accepted. Risks that have an extremely high cost to
mitigate are also often accepted. Beware of high risks
The process of risk management is an ongoing, iterative
being accepted by management. Ensure that this strategy
process. It must be repeated indefinitely. The business
environment is constantly changing and new threats and
212 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138
Copyright @ NIMI Not to be Republished
is in writing and accepted by the manager(s) making the tables and the description of the impact, it is possible to
decision. Often risks are accepted that should not have adequately communicate the assessment to the
been accepted, and then when the penetration occurs, organization's management.
the IT security personnel are held responsible. Typically,
business managers, not IT security personnel, are the The risk assessment includes the following actions and
ones authorized to accept risk on behalf of an organization. activities:
Qualitative Risk Assessment Effective ICT SCRM requires processes, procedures, and
tools that allow organizations to apply SCRM principles
Qualitative risk assessments assume that there is already consistently across all ICT systems. One such principle
a great degree of uncertainty in the likelihood and impact is to minimize the risk of counterfeit parts since they may
values and defines them, and thus risk, in somewhat lead to unpredictable behavior, early failures, or worse. It
subjective or qualitative terms. Similar to the issues in therefore becomes necessary to distinguish counterfeit
quantitative risk assessment, the great difficulty in parts from authentic parts.
qualitative risk assessment is defining the likelihood and
impact values. A structured language to express these characteristics is
needed, such that all members of a supply chain can
Moreover, these values need to be defined in a manner communicate about them, and which can be used to alert
that allows the same scales to be consistently used across others about counterfeits or express the criteria for
multiple risk assessments. Qualitative risk assessments legitimate items. A structured language to describe these
typically give risk results of "High", "Moderate" and "Low". observable attributes of both legitimate and illegitimate
However, by providing the impact and likelihood definition components is one tool for reducing supply chain risk.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 213
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.5.139
COPA - Cyber Security
Directory services
Objectives: At the end of this lesson you shall be able to
• describe directory and directory service
• describe the benefits of directory services
• mention the various implementations of directory services
• describe the logical and physical structure of active directory
• describe global catalog and group policy.
214
Copyright @ NIMI Not to be Republished
multi-vendor interoperability. In the 1980s, the International Active Directory
Telecommunication Union (ITU) and the International
Organization for Sandardization (ISO) came up with a set • Active Directory (AD) is a directory service that
of standards - X.500, for directory services. The protocol Microsoft developed for Windows domain networks and
decided upon is the Light weight Directory Access is included in most Windows Server operating systems
Protocol, LDAP, which is based on the directory information as a set of processes and services.
services of X.500, but uses the TCP/IP stack and a string
encoding scheme of the X.500 protocol DAP. • An AD domain controller authenticates and authorizes
all users and computers in a Windows domain type
Among the LDAP/X.500 based implementations are: network-assigning and enforcing security policies for
all computers and installing or updating software. For
• Active Directory: Microsoft's modern directory service example, when a user logs into a computer that is part
for Windows, originating from the X.500 directory, of a Windows domain, Active Directory checks the
created for use in Exchange Server, first shipped with submitted password and determines whether the user
Windows 2000 Server and is supported by successive is a system administrator or normal user.[3]
versions of Windows.
• Active Directory makes use of Lightweight Directory
• Apache Directory Server: Directory service written Access Protocol (LDAP) versions 2 and 3, Microsoft's
in Java, supporting LDAP, Kerberos 5 and the Change version of Kerberos, and DNS.
Password Protocol. LDAPv3 certified. The Apache
Directory Server is also a top level project of the Apache • Active Directory also makes user management easier
Software Foundation. as it acts as a single repository for all of this user and
computer related information.
• eDirectory: This is NetIQ's implementation of directory
services. It supports multiple architectures including • AD uses LDAP as its access protocol.
Windows, NetWare, Linux and several flavours of Unix
and has long been used for user administration, • AD relies on DNS as its locator service, enabling clients
configuration management, and software management. to locate domain controllers through DNS queries.
eDirectory has evolved into a central component in a Logical Structure of Active Directory
broader range of Identity management products. It was
previously known as Novell Directory Services. Active Directory is a distributed database that stores and
• Red Hat Directory Server: Red Hat released a manages information about network resources, as well as
directory service, that it acquired from AOL's Netscape application-specific data from directory enabled
Security Solutions unit, as a commercial product applications.
running on top of Red Hat Enterprise Linux called Red
Active Directory allows administrators to organize elements
Hat Directory Server and as the community supported
of a network (such as users, computers, devices, and so
389 Directory Server project.
on) into a hierarchical containment structure.
• Oracle Internet Directory: (OID) is Oracle
Corporation's directory service, which is compatible with In Active Directory, resources are organized in a logical
LDAP version 3. structure, and this grouping of resources logically enables
a resource to be found by its name rather than by its
• Sun Java System Directory Server: Sun
physical location.
Microsystems' current directory service offering.
• OpenDS: An open source directory service Benefits of AD Logical Structure
implementation from scratch in Java, backed by Sun
Microsystems. • Logical Structure provides more network security by
means of providing access to resources to only specified
• IBM Tivoli Directory Server: It is a customized build
groups (OU).
of an old release of OpenLDAP.
• Logical structure simplified the network management
• Windows NT Directory Services (NTDS), later
by administration, configuration and control of the
renamed Active Directory, replaces the former NT
network.
Domain system.
• The relationship between the logical structure of
• OpenLDAP : It supports all current computer
domains and forests simplifies resource sharing across
architectures, including Unix and Unix derivatives, Linux,
an organization.
Windows, z/OS, and a variety of embedded/realtime
systems. • As logical structure provides simplified network
management, it reduces the load on network resources
There are also plenty of open-source tools to create
and lower the total cost of ownership.
directory services, including OpenLDAP and the Kerberos
protocol, and Samba software.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.139 215
Copyright @ NIMI Not to be Republished
Components of AD Logical Structure Within forests are domains. A domain is defined as a logical
group of network objects (computers, users, devices) that
The logical structure components have relationship with share the same active directory database.
each other so it manage to control access to stored data
and finds how the data will be managed between different Within domains are organizational units. OUs can provide
domains in a forest. hierarchy to a domain, ease its administration, and can
resemble the organization's structure in managerial or
• Objects: like a user, computer, group, printer etc… geographical terms. OUs can contain other OUs-domains
are containers in this sense. The OU is the level at which
• Organizational Units - like any folder but in control of
administrative powers are commonly delegated, but
Active Directory
delegation can be performed on individual objects or
• Domains - Logical boundaries for objects attributes as well.
• Trees - Logical boundary for multiple domains
This is called the logical model because it is independent
• Forests - Logical boundary for multiple trees of the physical aspects of the deployment, such as the
Overall, one physical machine running as a Microsoft number of domain controllers required within each domain
Domain controller can control all these logical divisions and network topology.
with the help of 'A Operation Master' dedicated to perform
specific tasks. Figure 1 shows the relationship between forests, domains,
and organizational units.
The top-level container is the forest. A forest is a collection
of trees that share a common global catalog, directory Figure 1 Relationship between Active Directory Forests,
schema, logical structure, and directory configuration. The Domains, and Organizational Units(OUs)
forest represents the security boundary within which users,
computers, groups, and other objects are accessible.
Fig 1
Relationship between Active Directory Forests, Domains, and Organizational Units (OUs)
The Physical Structure of an Active Directory The physical structure of Active Directory:
The Active Directory physical structure checks when and • Domain Controllers: These computers run Microsoft
where logon and replication traffic occurs. The physical Windows Server 2003/2000, and Active Directory. Every
structure of Active Directory contains all the physical Domain Controller performs specific functions like
subnets present in network like domain controllers and replication, storage and authentication. It can support
replication between domain controllers. maximum one domain. It is always advised to have
more than one domain controller in each domain.
216 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.139
Copyright @ NIMI Not to be Republished
• Active Directory Sites: These sites are collection of OUs can be structured to allow for separate departments
well-connected computers. The reason why we create to have various levels of administrative control over their
site is domain controllers can communicate frequently own users. For example, a secretary in the Engineering
within the site. This way it minimizes the latency within department can be delegated control of resetting
site say changes made on one domain controller to be passwords for users within his own OU. Another advantage
replicated to other domain controllers. The other reason of OU use in these situations is that users can be easily
behind creating a site is to optimize bandwidth between dragged and dropped from one OU to another. For example,
domain controllers which are located in different if users are moved from one department to another, moving
locations. them into their new department's OU is extremely simple.
All IP subnets who share the common Local Area Network It is important to keep in mind that OU structure can be
(LAN) connectivity without knowing the actual physical modified on the fly any time an administrator feels fit to
location of computers is called site. make structural changes. This gives Active Directory the
added advantage of making changes any time.
A global catalog is a data storage source containing partial
representations of objects found in a multidomain Active Group Policy is a feature of the Microsoft Windows NT
Directory Domain Services (ADDS) forest. The global family of operating systems that control the working
catalog is stored on domain controllers specifically environment of user accounts and computer accounts.
assigned as global catalog servers. It can locate objects Group Policy provides the centralized management and
in any domain without knowing the actual domain name. configuration of operating systems, applications, and users'
settings in an Active Directory environment. A version of
Searches that are directed to the global catalog are faster Group Policy called Local Group Policy ("LGPO" or
because they do not involve referrals to different domain "LocalGPO") also allows Group Policy Object management
controllers. on standalone and non-domain computers. Group Policy
is one of the top reasons to deploy Active Directory
Organizing resources in OU because it allows you to manage user and computer
objects.
OUs are the primary method for organizing user, computer,
and other object information into a more easily Group Policy, in part, controls what users can and cannot
understandable layout. The organization has a root do on a computer system, for example: to enforce a
organizational unit where three nested organizational units password complexity policy that prevents users from
are placed. This nesting enables the organization to choosing an overly simple password, to allow or prevent
distribute users across multiple containers for easier unidentified users from remote computers to connect to a
viewing and administration of network resources. network share, to block access to the Windows Task
Manager or to restrict access to certain folders. A set of
OUs can be further sub divided into resource OUs for easy such configurations is called a Group Policy Object (GPO).
organization and delegation of administration. Far-flung
offices could have their own OUs for local administration Active Directory Backup and Restore
as well. It is important to understand, however, that an OU
should be created only if the organization has a specific Active Directory is one of the most critical components of
need to delegate administration to another set of your infrastructure. If it goes down, your network is
administrators. If the same person or group of people rendered useless. Therefore, to ensure business continuity
administer the entire domain, there is no need to increase and compliance, you need to have a solid backup and
the complexity of the environment by adding OUs. In fact, recovery plan in place for Active Directory.
too many OUs can impact group policies, logons, and
other factors. Where a Group Policy Preference Settings is configured
and there is also an equivalent Group Policy Setting
configured, then the value of the Group Policy Setting will
take precedence. group policy is security of
domain.Backup utility will automatically locate and include
them when you back up system state.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.139 217
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.5.140
COPA - Cyber Security
218
Copyright @ NIMI Not to be Republished
• Use of digital certificates issued and verified by a The next four layers are part of Oracle User Management:
Certificate Authority (CA) as part of a public key
infrastructure is considered another standard way to • Role-Based Access Control
perform authentication on the Internet. • Delegated Administration
• Another method of authentication, biometrics, depends • Registration Processes
on the user's presence and biological makeup (i.e.,
retina or fingerprints). This technology makes it more • Self Service and Approvals
difficult for hackers to break into computer systems.
Using special protocols for authentication like Secure In general, Access Control with begins with basic system
Sockets Layer (SSL), IP SEC, Secure Shell (SSH), administration tasks, progresses to more distributed, local
Kerberos authentication and Extensible Authentication modes of administration, and ultimately enables users to
Protocol (EAP) etc. perform some basic, predefined registration tasks on their
own. Table 1. illustrates how the layers build upon each
A security administrator maintains a database of other.
authorizations based on the security policy of the
organization. The reference monitor consults an Table 1
authorization database in order to determine if the user
attempting to do an operation is actually authorized to Layer of Access Level of
perform that operation. Auditing monitors and keeps a Administration
record of relevant activity in the system.
Self Service and Approvals End Users
It is important to make a clear distinction between
authentication and access control. Correctly establishing Registration Processes
the identity of the user is the responsibility of the
authentication service. Access control assumes that the Delegated Administration Local Administration
authentication of the user has been successfully verified
prior to enforcement of access control via a reference Role Based Access Control
monitor.
Data Security System Administrator
Successive Layers of Access Control
Function Security
Access Control is implemented in successive layers and
each layer builds upon the one that precedes it. The Security and Data Security mechanisms constitute
Organizations can, optionally, uptake the various layers the base layers of the security system, and contain the
depending on the degree of automation and scalability traditional system administrative capabilities. They limit
they wish to build upon the existing Function and Data the scope of User Management to basic system
Security models. There can be various models to administration by granting access to specific menus.
implement this. As an example, the Oracle User
Management has six layers of access control. Local Administrators
(Refer Fig 1) The Core Security layers include:
When Role-Based Access Control and Delegated
Fig 1 Administration are added to the Data Security and Function
1 Self Service and Approvals Security layers, system administration tasks can be
distributed to local administrators who manage a subset
2 Registraon Processes of the organization's users.
Oponal
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 219
Copyright @ NIMI Not to be Republished
In addition, organizations can use the Oracle Approvals role. The user does not have a control over the role that he
Management engine to create customized approval routing will be assigned.
for these requests.
• Discretionary Access Control (DAC)
There are three types of Preventive controls :
As the name suggests, this access control model is based
Administrative controls on a user's discretion. i.e, the owner of the resource can
give access rights on that resource to other users based
• Policies/Procedures: to identify the ways in which on his discretion. Access Control Lists (ACLs) are a typical
processes must be performed. This must go hand in example of DAC. Specifying the "rwx" permissions on a
hand with training, detective controls and audits. Unix file owned by you is another example of DAC Most of
the operating systems including windows, flavours of Unix
Physical Controls
are based on DAC Model.
• Using Biometric sensors, Smart cards etc.
• Mandatory Access Control (MAC)
Technical (Logical)Controls
In this Model, users/owners do not enjoy the privilege of
• Encryption deciding who can access their files. Here the operating
system is the decision maker overriding the user's wishes.
• Passwords and Tokens In this model every Subject (users) and Object (resources)
• Biometrics are classified and assigned with a security label. The
security labels of the subject and the object along with
• O.S. and Application Controls the security policy determine if the subject can access
• Identification and Authorization Technologies the object. The rules for how subjects access objects are
made by the security officer, configured by the
Access Control Mechanisms administrator, enforced by the operating system, and
supported by security technologies.
The following are the models/mechanisms for access
control. Each of the above Access Models has its own This is a stricter and rather static Access Control model
advantages and disadvantages. The selection of the as compared to DAC and is mostly suited for military
appropriate Access Model by an organization should be organizations where data classification and confidentiality
done by considering various factors such as type of is of prime importance. Special types of the Unix operating
business, no of users, organization's security policy etc. systems are based on MAC model.
Control Service Description This is to grant or deny user requests based on arbitrary
attributes of the user,arbitrary attributes of the object, and
Preventive Keep Undesirable Things from environment conditions that may be more relevant to the
Happening policies at hand.
Detective Identify Undesirable things that Password Cracking Methods And Their
have taken place Countermeasures:
Corrective Correct Undesirable things that There are number of methods used by hackers to hack
have taken place the accounts or steal personal information. Some of the
most commonly used methods to crack passwords and
Deterrent Discourage Security Violations their counter measures are as follows:
from taking place
1 BruteForce Attack
Recovery Restore Resources or Capabilities
after a Violation or Accident Any password can be cracked using Brute-force attack.
Brute-force attacks try every possible combinations of
Compensation Provide Alternatives to other numbers, letters and special characters until the right
Controls password is match. Brute- force attacks can take very
long time depending upon the complexity of the password.
• Role Based Access Control (RBAC) depending on the speed of computer and complexity of
the password.
Access decisions are based on an individual's roles and
responsibilities within the organization or user base. RBAC Countermeasure: Use long and complex passwords. Try
is also known as non-discretionary Access Control to use combination of upper and lowercase letters along
because the user inherits privileges that are tied to his
220 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140
Copyright @ NIMI Not to be Republished
with numbers. Brute-force attack will take very long time 6 Guessing:
to crack such complex and long passwords. You may
even keep changing the passwords frequently. This is a simple method to help you get someone's
password within seconds. If hacker knows you, he can
2 Social Engineering use information he knows about you to guess your
password. Hacker can also use combination of Social
Social engineering is process of manipulating someone Engineering and Guessing to acquire your password.
to trust you and get information from them. For example,
f the hacker was trying to get the password of a co-workers Counter measure: Don't use your name, surname, phone
or friends computer, he could call him pretending to be number or birth date as your password. Try to avoid creating
from the IT department or a bank and simply ask for his password that relates to you. Create complex and long
login or credit card details. password with combination of letters and numbers.
Countermeasure: Never ever give your sensitive Security classification for information
information like credit card details on phone.
Not all information is equal and so not all information
3 Rats And Keyloggers: requires the same degree of protection. This requires
information to be assigned a security classification.
In keylogging or rating the hacker sends keylogger or
Rat to the victim. This allows hacker to monitor everything
The first step in information classification is to identify a
victim do on his computer. Every keystroke is logged
member of senior management as the owner of the
including passwords. Moreover hacker can even control
particular information to be classified. Next, develop a
the victim's computer too.
classification policy. The policy should be able to:
Countermeasure: Never login to your bank account from
• Storing information
the cyber cafe or someone else’s computer. If it is very
important, use on-screen or virtual keyboard while tying • Transmitting information
the login. Use latest anti-virus software and keep the • Describe different classification labels,
definitions updated.
• Define the criteria for information to be assigned a
4 Phishing: particular label, and
• List the required security controls for each
Phishing is the most easiest and popular hacking method
classification.
used by hackers to get someone account details. In
Phishing attack hacker send fakepage of real website like • Disposing of unneeded information
facebook, gmail to victim. When someone logs in through • Protecting the integrity of information
that fake page his details is sent to the hacker. This fake
pages can be easily created and hosted on free web- • Allowing appropriate access and disclosure
hosting sites. • Establishing accountability.
Countermeasure: Phishing attacks are very easy to avoid. Some factors that influence which classification information
The url of this phishing pages are different from the real should be assigned include:
one. For example URL of phishing page of facebook might
look like facbbook.com (As you can see There are two • How much value that information has to the organization
"b"). Always make sure that websites url is correct. • How old the information is and
5 Rainbow Table: • Whether or not the information has become obsolete.
• Laws and other regulatory requirements
A Rainbow table is a huge pre- computed list of hashes for
every possible combination of characters. A password hash The Business Model for Information Security enables
is a password that has gone through a mathematical security professionals to examine security from systems
algorithm such as md5 and is transformed into something perspective, creating an environment where security can
which is not recognizable. A hash is a one way encryption be managed holistically, allowing actual risks to be
so once a password is hashed there is no way to get the addressed.
original string from the hashed string.
The type of information security classification labels
Countermeasure: Make sure you choose password that selected and used will depend on the nature of the
is long and complex. Creating tables for long and complex organization, with examples being:
password takes a very long time and a lot of resources.
• In the business sector, labels such as: Public,
Sensitive, Private and Confidential.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 221
Copyright @ NIMI Not to be Republished
• In the government sector, labels such as: Unclassified, Diameter
Sensitive But Unclassified, Restricted, Confidential,
Secret, Top Secret and their non-English equivalents. Diameter is an authentication, authorization, and
accounting protocol for computer networks. It evolved from
• In cross-sectoral formations, the Traffic Light Protocol,
and replaces the much less capable RADIUS protocol
which consists of: White, Green, Amber, and Red.
that preceded it. Diameter Applications extend the base
protocol by adding new commands and/or attributes. It
All employees in the organization, as well as business
provides better, better transport, better security, better
partners, must be trained on the classification scheme
proxying, better session control and better interoperability
and understand the required security controls and handling
when compared to RADIUS.
procedures for each classification. The classification of a
particular information asset that has been assigned should
TACACS
be reviewed periodically to ensure the classification is still
appropriate for the information and to ensure the security
Terminal Access Controller Access-Control System
controls required by the classification are in place.
(TACACS, usually pronounced like tack-axe) refers to a
family of related protocols handling remote authentication
Declassifying and downgrading
and related services for networked access control through
a centralized server. The original TACACS protocol, which
Information must be classified or designated only for the
dates back to 1984, was used for communicating with an
time it requires protection, after which it is to be declassified
authentication server, common in older UNIX networks.
or downgraded. This is because the classified or
Extended TACACS (XTACACS) is a proprietary extension
designated information will lose its sensitivity with the
to TACACS introduced by Cisco Systems in 1990 without
passage of time or the occurrence of specific events. This
backwards compatibility to the original protocol. Terminal
process contributes to the overall integrity of the security
Access Controller Access-Control System Plus
system, and ensures that information is made available
(TACACS+) is a protocol developed by Cisco and released
quickly and informally to interested members of the public.
as an open standard beginning in 1993.
Access Control Administration
Decentralized Access Control
Access control administration can be done in two ways.
• A decentralized access control administration method
• Centralized : Here one entity (dept or an individual) is gives control of access to the people closer to the
responsible for overseeing access to all corporate resources
resources. This type of administration provides a • In this approach, it is often the functional manager who
consistent and uniform method of controlling users assigns access control rights to employees.
access rights. Example: RADIUS, TACACS and
• Changes can happen faster through this type of
Diameter
administration because not just one entity is making
• Decentralized changes for the whole organization.
Access Control / Data Collection Protocols: AAA (RADIUS, • There is a possibility for conflicts to arise that may not
Diameter, and TACACS+) benefit the organization as because different managers
and departments can practice security and access
RADIUS, Diameter, and TACACS+ are three protocols for control in different ways.
carrying Authentication, Authorization, and Accounting
• There is a possibility of certain controls to overlap, in
(AAA) information between a Network Access Server
which case actions may not be properly proscribed or
(NAS) that wants to authenticate its links or end users.
restricted.
RADIUS • This type of administration does not provide methods
for consistent control, as a centralized method would.
The Remote Authentication Dial-In User Service (RADIUS)
is a client/server security protocol created by Lucent A Security Audit is essentially an assessment of how
InterNetworking Systems. RADIUS is an Internet draft effectively the organization's security policy is being
standard protocol. User profiles are stored in a central implemented. It is an independent review and examination
location, known as the RADIUS server. RADIUS clients of an IT system's policy, records, and activities.
(such as a PortMaster communications server)
communicate with the RADIUS server to authenticate Information systems audit is important because it gives
users. The server specifies back to the client what the assurance that the IT systems are adequately protected,
authenticated user is authorized to do. Although the term provide reliable information to users, and are properly
RADIUS refers to the network protocol that the client and managed to achieve their intended benefits. It also reduces
server use to communicate, it is often used to refer to the the risk data tampering, data loss or leakage, service
entire client/server system. disruption and poor management of IT systems.
222 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140
Copyright @ NIMI Not to be Republished
As Security Auditing and Testing (SAT) helps an Generally, computer security audits are performed by:
organization to understand the state of security for internal
reasons and provides assurance to external parties, it 1 Federal or State Regulators.
requires an attention of the highest degree. It helps to 2 Corporate Internal Auditors.
identify the gaps in the existing defenses.
3 External Auditors - Specialized in the areas related to
Establishing audit objectives technology auditing.
4 Consultants - Outsourcing the technology auditing
After planning an Audit and before proceeding to perform
where the organization lacks the specialized skill set.
the audit, one should establish the audit objectives.
Following is a list of objectives the auditor should review: First, the audit's scope should be decided and include all
company assets related to information security, including
• Personnel procedures and responsibilities including computer equipment, phones, network, email, data and
systems and cross-functional training any access-related items, such as cards, tokens and
passwords. Then, past and potential future asset threats
• Change management processes are in place and
must be reviewed. Anyone in the information security field
followed by IT and management personnel. Change
should stay apprised of new trends, as well as security
Management refers to the efficient and prompt handling
measures taken by other companies. Next, the auditing
of all changes to control IT infrastructure, in order to
team should estimate the amount of destruction that could
minimize the number and impact of any related
transpire under threatening conditions. There should be
incidents upon service.
an established plan and controls for maintaining business
• Appropriate back up procedures are in place to operations after a threat has occurred, which is called an
minimize downtime and prevent loss of important data intrusion prevention system.
• The data center has adequate physical security controls
Performing the review
to prevent unauthorized access to the data center
• Adequate environmental controls are in place to ensure The next step is collecting evidence to satisfy data center
equipment is protected from fire and flooding. audit objectives. This involves traveling to the data center
location and observing processes and procedures
Audit planning & preparation performed within the data center. The following review
procedures should be conducted to satisfy the pre-
The auditor should be adequately educated about the determined audit objectives:
company and its critical business activities before
conducting a data center review. The auditor should perform • The auditor should observe and interview data center
the following before conducting the review: employees to satisfy their objectives.
• The auditor should verify that all data center equipment
• Meet with IT management to determine possible areas
is working properly and effectively.
of concern
• All data center policies and procedures should be
• Review the current IT organization chart
documented and located at the data center. Important
• Review job descriptions of data center employees documented procedures include: data center personnel
• Research all operating systems, software applications job responsibilities, back up policies, security policies,
and data center equipment operating within the data employee termination policies, system operating
center procedures and an overview of operating systems.
• Review the company's IT policies and procedures • The auditor should assess the security of the client's
data center with respect to physical security controls
• Evaluate the company's IT budget and systems and environmental controls should be in place to ensure
planning documentation the security of data center equipment. These include:
• Review the data center's disaster recovery plan. Air conditioning units, raised floors, humidifiers and
uninterruptible power supply.
Performing an Audit • Backup procedures - The auditor should verify that the
client has backup procedures in place in the case of
There is no standard security-audit process, but auditors system failure. Clients may maintain a backup data
typically accomplish their job though personal interviews, center at a separate location that allows them to
vulnerability scans, examination of OS and security- instantaneously continue operations in the instance of
application settings, and network analyses, as well as by system failure.
studying historical data such as event logs. Auditors also
focus on the business's security policies to determine what
they cover, how they are used and whether they are effective
at meeting ongoing and future threats.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 223
Copyright @ NIMI Not to be Republished
Penetration Tests, Vulnerability Assessments And Access Control and Auditing
Security Audits
Physical and logical security
External Attackers often make use of already known
vulnerabilities and exploits in order to infiltrate in systems
There are multiple types of security, physical and logical.
and network. Taking appropriate defensive measures and
Physical security involves things like locks or biometrics.
adequate security design can mitigate this problem. This
Logical security examples consist of software safeguards
can also be achieved to a good extent by the recognizing
including access control and auditing, user account
already existing exposed systems and their risks at regular
management, violation and security activity reports, and
intervals. The risks may be detected in the earlier stages
firewalls.
and appropriate measures can be taken at an earlier stage.
Access control is a system enabling authorities to control
Vulnerability assessment is a practice used to identify all
access to areas and resources in a given physical facility
potential vulnerabilities that could be exploited in an
or computer-based information system. The Password for
environment. The assessment can be used to evaluate
a computer or PIN of an ATM system are forms of access
physical security, personnel, or system and network
control. Using an access control mechanism is important
security. Vulnerability identification tools may be used to
when persons seek to secure confidential, important, or
identify them. A list of every computer system by IP address
sensitive information and equipment.
and their associated vulnerabilities and steps on how to
"fix" the vulnerabilities should then be generated. Auditing an Access Control System is a way of tracking
Penetration test is carried out with the motive of "breaking the occurrence of entrance or attempted entrance into a
into the network" using the known vulnerabilities. From system. This is important because it shows how
here, the aim is to gain administrator or root access on successful the access control system is, as well as who
the most critical system in the network. This gives was denied access, and if they attempt entrance more
complete access to the network to tamper with or modify than once, what is their intention?
the systems and the data on the systems. A penetration
test is carried out to emulate what a real hacker would do Logical Audit is done to check the following:
and it proves to the company that the organization can
indeed be penetrated. • Strengths and weaknesses of Access Violations
• Security Activity Reports
Penetration testing is also referred to as ethical hacking.
In most cases, the security professional can look at reports • Logging activity reports
from a vulnerability scanner and understand the level of • Efficiency of firewalls
risk the company is facing.
• Reports on violations of security
Audit Controls • Reports of Attempts by unauthorized persons to hack
the system etc.
Review of Application Controls - It is the identification of
the risks of deployed technology and minimization of the Professional Ethics for Auditors
company's exposure to such risks, by ensuring that the
necessary controls and security are in place. To gain trust in an objective audit, it is necessary to uphold
a set of professional ethics. The professional ethics must
Review of General Computer Controls - It is done for be upheld by individual persons as well as by companies
providing a secure and stable environment for the providing services in the field of Information Security
application systems running on various platforms within Auditing. The professional ethics consist of the following
the company. principles:
system may be lost if errors are found in operational Honesty and confidentiality
systems
Honesty is the foundation of trust and forms the basis for
Objectives Of Controls the reliability of an assessment. Since sensitive business
processes and information are often found to be dependent
• To make sure data entering the computer are correct on information security, the confidentiality of the information
obtained during an audit and the discreet handling of the
• Check clerical handling of data before it is input to a results and findings of the IS audit are an important basis
computer for such work. IS auditors are aware of the value of the
• Provide means of detecting and tracing errors which information they receive and who owns it, and will not
occur due to bad data or bad program disclose this information without the corresponding
permission unless they are legally or professionally
• Ensure legal requirements are met required to do so.
• To guard against frauds
224 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140
Copyright @ NIMI Not to be Republished
Expert knowledge Information in an organization needs to be secured properly
against the consequences of breaches of confidentiality,
IS auditors only accept those jobs for which they have the integrity and availability. Proper security measures need
requisite knowledge and skills as well as the corresponding to be implemented to control and secure information from
experience and use these when performing their task. They unauthorized changes, deletions and disclosures. To find
continuously improve their knowledge as well as the the level of security measures that need to be applied, a
effectiveness and quality of their work. risk assessment is mandatory.
Objectivity and thoroughness Security policies are intended to define what is expected
from employees within an organization with respect to
An IS auditor must demonstrate the highest possible level information systems. The objective is to guide or control
of expert objectivity and thoroughness when collecting, the use of systems to reduce the risk to information assets.
evaluating, and passing on information on the activities or It also gives the staff who are dealing with information
business processes audited. The evaluation of all relevant systems an acceptable use policy, explaining what is
circumstances must be performed impartially and may allowed and what not. Security policies of all companies
not be influenced by the auditor's own interests or the are not same, but the key motive behind them is to protect
interests of others. assets. Security policies are designed with specific goals.
An IS auditor has the duty to report the results of the Information Security Audit Tools include utilities and power
examination precisely and truthfully to his client. This tools, both open source and commercial.
includes the impartial and understandable presentation of
the facts in the IS audit reports, the constructive evaluation Utility Tools : These are single-purpose tools that may
of the facts determined, and specific recommendations either be native to the operating system or freely available.
for improving the safeguards and processes. Utility tools require a manual approach, though they are
often included in customized scripts--or even commercial
Verifications and reproducibility products. You may even include native utilities, such as
ping available on most platforms, used to determine if a
The rational basis for reliable and comprehensible network target responds to ICMP packets.
conclusions and results is the clear and consistent
documentation of the actual facts. This also includes that Pros: Utility tools are freely available and are tightly focused
the IS audit team follows a documented and reproducible for a specific task, making them more efficient. They help
methodology to come to its conclusions. in discovering vulnerabilities much faster than those found
manually.
Compliance audit
Cons: It requires skill to use them. For a large audit, manual
A compliance audit is a comprehensive review of an testing is time-consuming and may produce inconsistent
organization's adherence to regulatory guidelines. results, depending on the skill of the auditor.
Independent accounting, security or IT consultants evaluate
the strength and thoroughness of compliance preparations. Traceroute: A network tracing utility used to determine
Auditors review security polices, user access controls and the network route to a host.
risk management procedures over the course of a
compliance audit. nslookup: used to determine domain ownership.
What is examined in a compliance audit will vary And open-source scripts, including:
depending upon whether an organization is a public or
private company, what kind of data it handles and if it Nmap: Free port-scanning utility.
transmits or stores sensitive financial data.
Crack: Popular password-cracking tool used to determine
Information Security Policies if passwords are weak by attempting to break them.
Organizations are giving more priority to development of John the Ripper: A password-cracking tool used primarily
information security policies, as protecting their assets is to discover Unix passwords.
one of the prominent things that needs to be considered.
Lack of clarity in information security policies can lead to binfo.c: A BIND version checker, binfo is a quick little
severe damages which cannot be recovered. So an script to pull back the version of named running on a remote
organization makes different strategies in implementing a name server.
security policy successfully. An information security policy
provides management direction and support for information ghba.c: A handy tool for extracting all the machine names
security across the organization. and IP addresses of a given class B or C subnet.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 225
Copyright @ NIMI Not to be Republished
Power Tools Google
Power Tools are multi-function bundled utilities to streamline A real hacker thinks outside the box and learns to use
and automate parts of the audit process. While some are tools in a way they may not have been intended. While
open-source packages, many are commercial products the Google search engine is not, strictly speaking, an
with custom vulnerability databases. auditing tool, it's great for gathering information about a
site. For example, trying entering "@DGET.com" (where
Pros: Automated tools scan for vulnerabilities against a "DGET" is your domain). Sometimes, this can yield some
database. Alerts may be tied into help desk monitoring good data, such as a system administrator posting
tools. In some cases, a scanning tool may be integrated technical details about his site, which conveniently
with a firewall or intrusion detection management station. contains his account name. Google is like the Unix "grep"
Some commercial scanners produce excellent reports command on steroids.
detailing exposures and associated risk.
Communicating Results
Cons: Scanners only check for vulnerabilities in their
database, which must be current. Many scanners are A final item to be considered is how to communicate with
marketed on the number of vulnerability checks performed. auditees, ie. the persons whose assets are being audited.
This isn't always a good indication of the tool's When informing auditees of continuous audit activity
effectiveness. Often, vulnerabilities are misdiagnosed. A results, it is important for the exchange to be independent
scanner can't accurately assess risk. and consistent.
Some of the Open-source power tools are Nessus, Reporting to senior management on defined
SARA(The Security Auditor's Research Assistant), parameters
Whisker, etc. among many others.
A typical audit report to the management and the
Some of the commercial scanners available today are management's response may look like the one shown in
Internet Security System's Internet Scanner, eEye Digital Table 1 below, but there are many other formats of the
Security's Retina, BindView's BV-Control, CORE Security reports and Reponses in use.
Technology's Auditing Tools Suite and Foundstone's
FoundScan.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140
226
Copyright @ NIMI Not to be Republished
Table 1
2 Patches are not The situation Install the latest Person Responsible :
up to date on increases the patches on the The chief information
LINUX based risk of the servers running on Office. This was a
servers. unauthorized LINUX operating result of complications No further
access to the systems. in red hat LINUX action
organization’s maintenance contracts required.
systems. It between the suppliers
also increases and the security team.
the risk of The issue was settled
system failure. in october 2014 and
patches were
installed.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 227
Copyright @ NIMI Not to be Republished
IT & ITES Related Theory for Exercise 2.5.141
COPA - Cyber Securtiy
228
Copyright @ NIMI Not to be Republished
• EPAL - The Enterprise Privacy Authorization Language Visit only trusted websites. Use applications like Site
is very similar to XACML, but is not yet a standard. Advisor etc. to know about the site you are opening.While
websites today share more information, they also provide
• WS-Privacy - "Web Service Privacy" will be a
their users with great specificity and control over these
specification for communicating privacy policy in web
sharing activities. On many websites you'll find that you
services. For example, it may specify how privacy
can define your audience when you share personal
policy information can be embedded in the SOAP
information or content, whether it's an audience of one or
envelope of a web service message.
the entire public.
Protecting Privacy on the Internet
Email has remained largely unchanged in the last decade.
On the internet you almost always give away a lot of Methods of exploiting email, however, have evolved
information about yourself. Unencrypted e-mails can be significantly and protecting personal information in email
read by the administrators of the e-mail server where the environments has become more challenging. In the past
connection is not encrypted (no https). Also the internet decade hacking has become more effective and phishing
service provider and other parties sniffing the traffic of that techniques, more elaborate. Here are some strategies for
connection are able to know the contents. Furthermore, protecting your privacy when using email:
the same applies to any kind of traffic generated on the
internet (web browsing, instant messaging, ...) In order 1 Use a secondary, "spam" email address
not to give away too much personal information, e-mails
2 Use email service providers with strong security and
can be encrypted and browsing of webpages as well as
spam filters
other online activities can be done traceless via
anonymizers, or, in cases those are not trusted, by open 3 Exercise caution when opening emails
source distributed anonymizers, so called mix nets.
4 Recognize that email is evolving towards openness and
Renowned open-source mix nets are I2P - The Anonymous
interconnectivity
Network or tor.
5 Use strong passwords and remember to sign-out
Protect Your Privacy Best Online Privacy Practices
The following is a list of tips and guidelines to safeguard 1 Minimize personal information sharing
your privacy, personal information online and prevent fraud
and abuse while using the Internet. 2 Look for trustmarks on websites and verify their
authenticity
• Get New Passwords: Use different, strong passwords 3 Consider temporary credit card numbers when shopping
for each of your online accounts so if one is online
compromised the rest are safe. Strong passwords
contains letters, numbers, different cases, and 4 Use strong passwords and remember to sign-out
symbols. Check your password's strength here. 5 Change your passwords frequently.
• Close Old Online Accounts: Unused online accounts 6 Use anti-virus and anti-spyware protection
are a liability. Hackers could use them to infiltrate your
more important accounts . Get rid of them. 7 Take advantage of browser privacy enhancing
capabilities and options
• Reduce Your Friends List.
8 Update your Browser and other tools.
• Go Paperless: Do not keep sensitive data online or in
your mail accounts. Mobile Privacy
• Shred Sensitive Documents: Get rid of unwanted 1 On mobile devices your personal information is more
documents containing sensitive data. Dispose them likely to be compromised via device theft or loss - take
securely, using a shredder. appropriate precautions
2 Your mobile device may be aware of your location and
Browser Privacy may share that data with applications and advertisers
Modern browsers have an impressive array of privacy
enhancing capabilities and options. They can, for example, CYBER CRIME ACT
warn you before you visit suspicious or fraudulent websites
and can also allow you to surf the web without downloading In the era of cyber world as the usage of computers became
tracking files like cookies to your computer. Also, most more popular, there was expansion in the growth of
browsers can inform you when a website uses SSL, a technology as well, and the term ‘Cyber’ became more
security measure that encrypts your data. When a website familiar to the people. The evolution of Information
uses SSL a browser may indicate this to you by displaying Technology (IT) gave birth to the cyber space wherein
a padlock icon (typically located on the bottom bar of your internet provides equal opportunities to all the people to
browser) or by highlighting the website's name in the access any information, data storage, analyse etc. with
address bar in green.
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.141 229
Copyright @ NIMI Not to be Republished
the use of high technology. Due to increase in the number Cyber-Stalking
of netizens, misuse of technology in the cyberspace was
clutching up which gave birth to cyber crimes at the It means expressed or implied a physical threat that
domestic and international level as well. creates fear through the use to computer technology such
as internet, e-mail, phones, text messages, webcam,
Though the word Crime carries its general meaning as “a websites or videos.
legal wrong that can be followed by criminal proceedings
which may result into punishment” whereas Cyber Crime Dissemination of Obscene Material
may be “unlawful acts wherein the computer is either a
tool or target or both”. It includes Indecent exposure/ Pornography (basically child
pornography), hosting of web site containing these
The world 1st computer specific law was enacted in the prohibited materials. These obscene matters may cause
year 1970 by the German State of Hesse in the form of harm to the mind of the adolescent and tend to deprave or
‘Data Protection Act, 1970’ with the advancement of cyber corrupt their mind.
technology. With the emergence of technology the misuse
of technology has also expanded to its optimum level and Defamation:
then there arises a need of strict statutory laws to regulate
the criminal activities in the cyber world and to protect It is an act of imputing any person with intent to lower
technological advancement system. It is under these down the dignity of the person by hacking his mail account
circumstances Indian parliament passed its and sending some mails with using vulgar language to
“INFORMATION TECHNOLOGY ACT, 2000” on 17th oct unknown persons mail account.
to have its exhaustive law to deal with the technology in
the field of e-commerce, e-governance, e-banking as well Hacking
as penalties and punishments in the field of cyber crimes.
It means unauthorized control/access over computer
Cyber Crimes Actually system and act of hacking completely destroys the whole
data as well as computer programmes. Hackers usually
It could be hackers vandalizing your site, viewing hacks telecommunication and mobile network.
confidential information, stealing trade secrets or
intellectual property with the use of internet. It can also Cracking
include ‘denial of services’ and viruses attacks preventing
regular traffic from reaching your site. Cyber crimes are It is amongst the gravest cyber crimes known till date. It
not limited to outsiders except in case of viruses and with is a dreadful feeling to know that a stranger has broken
respect to security related cyber crimes that usually done into your computer systems without your knowledge and
by the employees of particular company who can easily consent and has tampered with precious confidential data
access the password and data storage of the company and information.
for their benefits. Cyber crimes also includes criminal
activities done with the use of computers which further E-Mail Spoofing
perpetuates crimes i.e. financial crimes, sale of illegal
articles, pornography, online gambling, intellectual property A spoofed e-mail may be said to be one, which
crime, e-mail, spoofing, forgery, cyber defamation, cyber misrepresents its origin. It shows it’s origin to be different
stalking, unauthorized access to Computer system, theft from which actually it originates.
of information contained in the electronic form, e-mail
SMS Spoofing:
bombing, physically damaging the computer system etc.
Spoofing is a blocking through spam which means the
Classifications Of Cyber Crimes: Cyber Crimes which
unwanted uninvited messages. Here a offender steals
are growing day by day, it is very difficult to find out what
identity of another in the form of mobile phone number and
is actually a cyber crime and what is the conventional
sending SMS via internet and receiver gets the SMS from
crime so to come out of this confusion, cyber crimes can
the mobile phone number of the victim. It is very serious
be classified under different categories which are as follows:
cyber crime against any individual.
Cyber Crimes against Persons:
Carding
There are certain offences which affects the personality of
individuals can be defined as: It means false ATM cards i.e. Debit and Credit cards used
by criminals for their monetary benefits through withdrawing
Harassment via E-Mails: It is very common type of money from the victim’s bank account mala-fidely. There
harassment through sending letters, attachments of files is always unauthorized use of ATM cards in this type of
& folders i.e. via e-mails. At present harassment is common cyber crimes.
as usage of social sites i.e. Facebook, Twitter etc.
increasing day by day.
230 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.141
Copyright @ NIMI Not to be Republished
Cheating & Fraud Transmitting Virus: Viruses are programs that attach
themselves to a computer or a file and then circulate
It means the person who is doing the act of cyber crime themselves to other files and to other computers on a
i.e. stealing password and data storage has done it with network. They usually affect the data on a computer, either
having guilty mind which leads to fraud and cheating. by altering or deleting it. Worm attacks plays major role in
affecting the computerize system of the individuals.
Child Pornography
Cyber Trespass: It means to access someone’s computer
It involves the use of computer networks to create, without the right authorization of the owner and does not
distribute, or access materials that sexually exploit disturb, alter, misuse, or damage data or system by using
underage children. wireless internet connection.
Assault by Threat Internet Time Thefts: Basically, Internet time theft comes
under hacking. It is the use by an unauthorised person, of
Assault by Threat refers to threatening a person with fear the Internet hours paid for by another person. The person
for their lives or lives of their families through the use of a who gets access to someone else’s ISP user ID and
computer network i.e. E-mail, videos or phones. password, either by hacking or by gaining access to it by
illegal means, uses it to access the Internet without the
Crimes Against Persons Property: other person’s knowledge. You can identify time theft if
the Internet time has to be recharged often, despite
As there is rapid growth in the international trade where infrequent usage.
businesses and consumers are increasingly using
computers to create, transmit and to store information in Cybercrimes Against Government:
the electronic form instead of traditional paper documents.
There are certain offences done by group of persons
There are certain offences which affects persons property
intending to threaten the international governments by
which are as follows:
using internet facilities. It includes:
Intellectual Property Crimes Cyber Terrorism
Intellectual property consists of a bundle of rights. Any Cyber terrorism is a major burning issue in the domestic
unlawful act by which the owner is deprived completely or as well as global concern. The common form of these
partially of his rights is an offence. The common form of terrorist attacks on the Internet is by distributed denial of
IPR violation may be said to be software piracy, infringement service attacks, hate websites and hate e-mails, attacks
of copyright, trademark, patents, designs and service mark on sensitive computer networks etc. Cyber terrorism
violation, theft of computer source code, etc. activities endanger the sovereignty and integrity of the
nation.
Cyber Squatting
Cyber Warfare
It means where two persons claim for the same Domain
Name either by claiming that they had registered the name It refers to politically motivated hacking to conduct
first on by right of using it before the other or using sabotage and espionage. It is a form of information warfare
something similar to that previously. sometimes seen as analogous to conventional warfare
although this analogy is controversial for both its accuracy
Cyber Vandalism and its political motivation.
This type of offence is common as there is rapid growth in According to the Section: 43 of ‘Information Technology
the users of networking sites and phone networking where Act, 2000’ whoever does any act of destroys, deletes,
culprit will try to attack by sending bogus mails or alters and disrupts or causes disruption of any computer
messages through internet. Ex: Using credit cards by with the intention of damaging of the whole data of the
obtaining password illegally. computer system without the permission of the owner of
the computer, shall be liable to pay fine upto 1crore to the
Forgery person so affected by way of remedy. According to the
Section:43A which is inserted by ‘Information
It means to deceive large number of persons by sending Technology(Amendment) Act, 2008’ where a body
threatening mails as online business transactions are corporate is maintaining and protecting the data of the
becoming the habitual need of today’s life style. persons as provided by the central government, if there is
any negligent act or failure in protecting the data/
Affects To Whom information then a body corporate shall be liable to pay
compensation to person so affected. And Section 66 deals
Cyber Crimes always affects the companies of any size with ‘hacking with computer system’ and provides for
because almost all the companies gain an online presence imprisonment up to 3 years or fine, which may extend up
and take advantage of the rapid gains in the technology to 2 years or both.
but greater attention to be given to its security risks. In
the modern cyber world cyber crimes is the major issue
which is affecting individual as well as society at large
too.
232 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.141
Copyright @ NIMI Not to be Republished