COPA2 Ndsem TT
COPA2 Ndsem TT
COPA2 Ndsem TT
PROGRAMMING ASSISTANT
NSQF LEVEL - 4
TRADE THEORY
NATIONAL INSTRUCTIONAL
MEDIA INSTITUTE, CHENNAI
Post Box No. 3142, CTI Campus, Guindy, Chennai - 600 032
(i)
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 : [email protected], [email protected]
Website: www.nimi.gov.in
(ii)
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 1st
Year (Volume II of II) 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)
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)
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)
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)
(vii)
(viii)
Module 4 : E Commerce
(ix)
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.
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.94 3
Fig 1
Browser connects to a
Server and requests a Page
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.95 5
• 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”;
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
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
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
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
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
12 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96B
*= /= %=
+= -= <<=
^= |=
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.96B 13
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
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
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
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
Syntax
window.prompt(“sometext”,”default text”);
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.97A & 2.1.97B 19
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
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
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
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
24 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99
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
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
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
CHNM,COPA,ICTSM,IT
28 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.99
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
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
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
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
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
} student1.sayGoodBye(); // "Goodbye!"
34 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.100B
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
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
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
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
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
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
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
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
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
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
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
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
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
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
<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
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
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
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
Example 5 • document.anchors
56 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A
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
</script>
58 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A
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
60 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102A
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
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 63
64 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 65
Saving stylesheets
66 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 67
Uploading
68 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.102B 69
70
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
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
74 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B
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
76 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B
Fig 2
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.1.103A & 2.1.103B 77
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
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
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
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
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
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
IT & ITES : COPA - (NSQF Level - 4): Related Theory for Exercise 2.2.105A - 2.2.105D 85
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
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
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
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
90
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
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
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
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
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
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
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
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
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
End Sub
100 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.108
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
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
} 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
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
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
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
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
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
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
Debug.Print "The payment for "& person & " is " & pay
111
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
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
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
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
12 End Sub
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.113 117
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
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
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
• 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
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
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
124 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.114 & 2.2.115
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
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
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
Fig 1
128 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.117
Methods
129
130 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.2.118
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
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
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
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
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
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
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
‘ 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
‘ 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
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
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
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
- 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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.121 145
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
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
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
Fig 1
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 149
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
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
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
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
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
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
Ledger Group
156 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122
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
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.122 159
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
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
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
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
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
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
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
2,78,200 2,78,200
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.123 167
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
“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
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.124 171
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
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
174 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.125 & 2.3.126
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
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.127 & 2.3.128 177
178
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.129 179
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
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
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
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
Fig 1
Importing Masters
184 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.130
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
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.131 187
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
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.133 191
Fig 2
192 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.133
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
194
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.3.135 195
196
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
• 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
Fig 2
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.136 199
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
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
• 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
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
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
206
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 207
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
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
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.138 211
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
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
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.139 215
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
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
218
IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140 219
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
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
222 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.140
• 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
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
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
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
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
228
230 IT & ITES : COPA (NSQF Level - 4) - Related Theory for Exercise 2.5.141
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